Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    The longest shared subsequence

    MediumAbout 25 minFull AccessLearn it: Unique Paths and Longest Common Subsequence: 2D state

    The task

    A diff tool lines up two versions of a text by the longest sequence of characters they share in the same order.

    Complete LongestCommonSubsequence(string a, string b). Return the length of the longest string that is a subsequence of both a and b: its characters appear in both in the same order, but not necessarily next to each other. Matching is case-sensitive. Neither text is null.

    Signature

    public static int LongestCommonSubsequence(string a, string b)

    Examples

    • "dotnet", "donut" → 4. "dont" appears in both, in that order.
    • "xaxbxcx", "abc" → 3. The letters a, b, c need not be next to each other.

    Limits: Texts of up to 1,000 characters each.

    The tests check: empty texts, equal texts, no letter in common, letter case, repeated letters, rotated halves, letters far apart, and two texts of 400 and of 1,000 letters in time.

    Hints

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      public static class Solution
      {
          // The length of the longest subsequence that a and b have in common (case-sensitive).
          public static int LongestCommonSubsequence(string a, string b)
          {
              throw new NotImplementedException();
          }
      }

      This problem comes with TechInterviewNotes Full Access

      Unlock all paid content on TechInterviewNotes.