Problem · String

Longest Common Subsequence Length

Learn this problem
MediumAmazon logoAmazonFULLTIMEONSITE INTERVIEW
See Amazon hiring insights

Problem statement

Given two lowercase strings first and second, return the length of their longest common subsequence.

A subsequence is formed by deleting zero or more characters without changing the relative order of the remaining characters. The characters in a common subsequence must appear in both strings in the same relative order; they do not need to occupy consecutive positions.

Function

longestCommonSubsequence(first: String, second: String) → int

Examples

Example 1

first = "abcde"second = "ace"return = 3

The string ace appears in both inputs in the same relative order.

Example 2

first = "abc"second = "def"return = 0

The two strings share no character, so the longest common subsequence is empty.

Constraints

  • 0 <= first.length, second.length <= 1000
  • first and second contain only lowercase English letters.

More Amazon problems

drafts saved locally
public int longestCommonSubsequence(String first, String second) {
    // Write your code here.
}
first"abcde"
second"ace"
expected3
checking account