Start learning free

LESSON 249 OF 314 · DYNAMIC PROGRAMMING

Longest Common Subsequence in Kotlin: 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 7
    Ctrl + Enter to check

    KOTLIN · DYNAMIC PROGRAMMING

    Longest Common Subsequence in Kotlin, explained

    Problem overview

    The function longestCommonSubsequence receives two strings, text1 and text2, and returns the length of their longest common subsequence. A subsequence is what remains after deleting some characters, possibly none, while keeping the order of the rest. So "ace" is a subsequence of "abcde", but "aec" is not. A common subsequence is a subsequence of both strings, and the result is 0 when the strings share no character. Both strings have 1 to 1000 lowercase letters, and the statement asks for O(n * m) time and space, where n and m are the two lengths.

    For "abcde" and "ace" the answer is 3: "ace" appears in both. For "abcbdab" and "bdcaba" it is 4. Both "bcba" and "bdab" have that length, and only the length is returned.

    Approach: solve every pair of prefixes

    A 1000-character string has 2^1000 subsequences, so comparing them all is out of the question. Instead, solve smaller versions of the problem. 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 is dp[n][m]. An empty prefix has nothing in common with anything, so row 0 and column 0 stay 0.

    Look at the last characters of the two prefixes, text1[i - 1] and text2[j - 1] (the first i characters end at index i - 1):

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

    Filling the table row by row and left to right guarantees that the cells above, to the left and diagonally up-left are known when they are needed. This is the table for "abcde" and "ace", with one row per prefix of text1 (starting with the empty prefix) and one column per prefix of text2:

    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, 3, is the answer.

    Step by step

    1. Store the lengths text1.length and text2.length in n and m, since they appear throughout.
    2. Create the table with Array(n + 1) { IntArray(m + 1) }. It has one more row and column than the strings have characters, to hold the empty prefixes. A new IntArray starts with zeros, which is exactly the starting value row 0 and column 0 need.
    3. Loop i over 1..n. Row 0 is the empty prefix and is already done.
    4. Loop j over 1..m inside it, for the same reason.
    5. Handle equal last characters. If text1[i - 1] == text2[j - 1], set dp[i][j] to dp[i - 1][j - 1] + 1.
    6. Handle different last characters in the else branch: dp[i][j] is maxOf(dp[i - 1][j], dp[i][j - 1]).
    7. Return dp[n][m], the answer for both whole strings.

    The solution in Kotlin

    class Solution {
        fun longestCommonSubsequence(text1: String, text2: String): Int {
            val n = text1.length
            val m = text2.length
            val dp = Array(n + 1) { IntArray(m + 1) }
            for (i in 1..n) {
                for (j in 1..m) {
                    if (text1[i - 1] == text2[j - 1]) {
                        dp[i][j] = dp[i - 1][j - 1] + 1
                    } else {
                        dp[i][j] = maxOf(dp[i - 1][j], dp[i][j - 1])
                    }
                }
            }
            return dp[n][m]
        }
    }
    

    The Kotlin details worth a look:

    • A table of rows. Array(n + 1) { IntArray(m + 1) } is an Array<IntArray>. The lambda runs once for each row, so every row is a separate array. Reusing one pre-built IntArray for all the rows would make them share the same storage, and writing to one row would change them all. Elements are read and written as dp[i][j].
    • String indexing. text1[i - 1] returns a Char, and == on two Char values compares them by value. The index is zero-based, which is why the table's i maps to character i - 1.
    • 1..n is inclusive. It runs from 1 to n, the last row. The strings are never empty under the constraints, but for an empty string the range would be empty and the answer would stay 0.
    • if as a statement. Both branches assign to dp[i][j]. The braces are optional for one-line branches but make the two cases easy to see.
    • maxOf comes from the standard library and needs no import.
    • Memory. A 1000 by 1000 problem needs a table of about a million Int values, around 4 MB, which is comfortable.

    Complexity

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

    Space: O(n * m). The whole table is kept. Each row reads only itself and the row above, so two rows of m + 1 numbers would be enough for O(m) space, at the cost of a less direct picture of the table. The lesson keeps the full table.

    Edge cases and common mistakes

    • No common character. "abc" and "def" give 0, and so do "a" and "b".
    • Identical strings. "abc" and "abc" give 3, and "a" with "a" gives 1.
    • Same letters, different order. "abc" and "cba" give 1: subsequences must keep their order.
    • Repeated letters. "aaaa" and "aa" give 2, the length of the shorter string.
    • Off-by-one indexing. Writing text1[i] instead of text1[i - 1] compares the wrong characters and eventually reads past the end of the string, throwing a StringIndexOutOfBoundsException when i reaches n.
    • Confusing it with a substring. A common substring needs consecutive characters, and a subsequence doesn't. In the case of differing characters, a substring table would reset to 0, while here the larger neighbour is kept.
    • Leaving out a case. Using only dp[i - 1][j] in the else branch ignores the answers that skip a character of text2 instead.

    Testing

    These inputs give the following results from the reference solution:

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