Start learning free

LESSON 249 OF 314 · DYNAMIC PROGRAMMING

Longest Common Subsequence in Swift: O(n · m) Dynamic Programming

Practice O(n · m) Read the full explanation

You are given two strings text1 and text2. Return the length of their longest common subsequence, or 0 if they have no common subsequence.

A subsequence of a string is what remains after deleting some of its characters, possibly none, without changing the order of the others. For example, "ace" is a subsequence of "abcde", but "aec" is not: the characters must keep their order. A common subsequence of two strings is a subsequence of both of them.

 

Example 1:

Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: "ace" is a subsequence of both strings. text2 has only 3 characters, so no common subsequence can be longer.

Example 2:

Input: text1 = "abcbdab", text2 = "bdcaba"
Output: 4
Explanation: "bcba" is a subsequence of both: b, c, b and a appear in this order in each string. "bdab" works too, and no common subsequence has 5 characters. Only the length is returned.

Example 3:

Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: No character appears in both strings, so the only common subsequence is the empty one.

 

Constraints:

  • 1 <= text1.length, text2.length <= 1000
  • text1 and text2 are made of lowercase English letters only, a to z.

Note:

Your algorithm should run in O(n · m) time and space, where n is the length of text1 and m the length of text2.



Trying every subsequence is far too slow: a string of 1000 characters has 21000 of them. Solve smaller versions of the problem instead: let dp[i][j] be the length of the longest common subsequence of the first i characters of text1 and the first j characters of text2. The table has (n + 1) × (m + 1) entries. Row 0 and column 0 stand for an empty prefix, which has nothing in common with anything, so they stay 0. The answer is dp[n][m].

Fill the table row by row, so the entries above, to the left and diagonally up-left of dp[i][j] are already known. Look at the last characters of the two prefixes, text1[i - 1] and text2[j - 1]:
  • When they are equal, dp[i][j] = dp[i - 1][j - 1] + 1. Adding this shared character to the best common subsequence of the two shorter prefixes reaches that length, and nothing does better: removing the last character of any common subsequence leaves a common subsequence of the two shorter prefixes.
  • When they differ, dp[i][j] is the larger of dp[i - 1][j] and dp[i][j - 1]. A common subsequence can't end with both of them, so it leaves out at least one, and then it is a common subsequence of the prefixes without that character.

The table has (n + 1) × (m + 1) entries, and each one takes a constant amount of work: O(n · m) time and O(n · m) space.
Each row reads only itself and the row above it, so two rows of m + 1 numbers are enough, which brings the space down to O(m). The lesson keeps the whole table, which is easier to follow.
STEP 1 OF 8
    Ctrl + Enter to check

    SWIFT · DYNAMIC PROGRAMMING

    Longest Common Subsequence in Swift, explained

    Problem overview

    The method longestCommonSubsequence receives two strings, text1 and text2, and returns the length of their longest common subsequence, or 0 if they share none. A subsequence is what remains of a string after deleting some characters (maybe none) without reordering the rest. "ace" is a subsequence of "abcde", but "aec" is not. A common subsequence is one that both strings contain. Both strings have 1 to 1000 lowercase letters, and the method must run in O(n · m) time, where n and m are the lengths.

    For "abcde" and "ace" the answer is 3, because "ace" appears in both. For "abcbdab" and "bdcaba" it is 4: "bcba" and "bdab" both work, and the method returns only the length. For "abc" and "def" it is 0.

    Approach: a table of prefixes

    A string of 1000 characters has 2^1000 subsequences, so listing them is out of the question. Instead, solve smaller versions of the problem and reuse the answers. Let dp[i][j] be the length of the longest common subsequence of the first i characters of text1 and the first j characters of text2. The answer to the whole problem is dp[n][m].

    Row 0 and column 0 stand for an empty prefix, which has nothing in common with any string, so they stay 0. That's why the table has n + 1 rows and m + 1 columns.

    To fill dp[i][j], look at the last characters of the two prefixes, text1[i - 1] and text2[j - 1]:

    • They are equal. Then dp[i][j] = dp[i - 1][j - 1] + 1. The shared character extends the best answer for the two shorter prefixes by one, and nothing does better: removing the last character from any common subsequence leaves a common subsequence of the shorter prefixes.
    • They differ. A common subsequence can't end with both characters, so it leaves out at least one of them. Then it is a common subsequence of the prefixes without that character, and dp[i][j] is the larger of dp[i - 1][j] and dp[i][j - 1].

    Filling the table row by row, left to right, guarantees the cell above, the cell on the left and the cell diagonally up-left are known when you need them.

    This is the table for text1 = "abcde" (the rows) and text2 = "ace" (the columns), printed by a real run:

    [0, 0, 0, 0]
    [0, 1, 1, 1]
    [0, 1, 1, 1]
    [0, 1, 2, 2]
    [0, 1, 2, 2]
    [0, 1, 2, 3]

    The bottom-right entry is 3, the answer.

    Step by step

    1. Copy each string's bytes into an array. chars1 comes from Array(text1.utf8) and chars2 from Array(text2.utf8), both with let. An array can be read by position, and the strings hold only the letters a to z, one byte each, so comparing bytes compares letters.
    2. Store the lengths in n and m, with let. They come up often.
    3. Create the table dp with var: n + 1 rows, each a row of m + 1 zeros, using repeating: and count: twice.
    4. Loop over the rows with i in 1...n. Row 0 is already zeros. Write the closing brace right away.
    5. Loop over the columns inside it with j in 1...m, and close that loop too.
    6. Handle equal characters. If chars1[i - 1] == chars2[j - 1], set dp[i][j] to dp[i - 1][j - 1] + 1. The first i characters end at index i - 1, because the array counts from 0 and the table counts characters.
    7. Handle different characters in the else: set dp[i][j] to max(dp[i - 1][j], dp[i][j - 1]).
    8. Return dp[n][m] after the outer loop.

    The solution in Swift

    class Solution {
        func longestCommonSubsequence(_ text1: String, _ text2: String) -> Int {
            let chars1 = Array(text1.utf8)
            let chars2 = Array(text2.utf8)
            let n = chars1.count
            let m = chars2.count
            var dp = [[Int]](repeating: [Int](repeating: 0, count: m + 1), count: n + 1)
            for i in 1...n {
                for j in 1...m {
                    if chars1[i - 1] == chars2[j - 1] {
                        dp[i][j] = dp[i - 1][j - 1] + 1
                    } else {
                        dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
                    }
                }
            }
            return dp[n][m]
        }
    }
    

    The Swift details worth a closer look:

    • Strings can't be indexed by an integer. text1[3] doesn't compile, because a String is a sequence of characters of varying size. Converting once to an array lets the loops use chars1[i - 1].
    • utf8 versus characters. text1.utf8 is a view of the string's bytes, so Array(text1.utf8) is an array of UInt8 values. For lowercase English letters each byte is one letter. For text with accented letters the byte count and the character count differ: "héllo" has 5 characters but 6 bytes. The lesson's strings never contain such letters. Array(text1) would give an array of Character values, which is the safer choice for general text.
    • Comparing bytes. chars1[i - 1] == chars2[j - 1] compares two UInt8 values with ==.
    • Arrays are values. [Int](repeating: 0, count: m + 1) is copied into each of the n + 1 rows, so writing dp[i][j] changes only that row. The rows are independent.
    • Closed ranges. 1...n includes n. A closed range can't end below its start, but both strings have at least one character, so 1...n and 1...m are always valid.
    • Nested subscripts. dp[i][j] reads row i and then its column j. Assigning through two subscripts works because dp is a var.

    Complexity

    Time: O(n · m). The table has (n + 1) · (m + 1) entries and each one takes constant work.

    Space: O(n · m). The method keeps the whole table. Each row reads only itself and the row above it, so two rows would be enough and would reduce the space to O(m). The lesson keeps the full table because it is easier to follow. For two strings of 1000 characters the table has about a million entries, which is fine.

    Edge cases and common mistakes

    • No shared letters. "a" and "b" return 0.
    • Identical strings. "abc" and "abc" return 3, the full length.
    • Repeated letters. "aaaa" and "aa" return 2: the shorter string fits inside the longer one.
    • Same letters, opposite order. "abc" and "cba" return 1. A common subsequence has to keep the order in both strings.
    • Off-by-one on indexes. The table row i refers to character i - 1 of the array. Using chars1[i] would read past the end on the last row and stop the program.
    • Confusing a subsequence with a substring. A substring must be contiguous. "ace" is not a substring of "abcde", but it is a subsequence.
    • Big inputs. Two strings of 1000 characters are fine for this method. Trying every subsequence is not.

    Testing

    Results from running the reference solution:

    • "abcde", "ace" gives 3.
    • "abcbdab", "bdcaba" gives 4.
    • "abc", "def" gives 0.
    • "a", "a" gives 1.
    • "aaaa", "aa" gives 2.
    • "abc", "cba" gives 1.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free