FastPrepLongest Common Subsequence Length

Longest Common Subsequence Length

Indeed logoIndeed● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Return the length of the longest common subsequence of first and second. A subsequence is obtained by deleting zero or more characters without changing the order of those kept. Kept characters do not need to be adjacent.

For this exercise, assume the inputs are strings of uppercase and lowercase English letters. Compare characters exactly and allow repeated letters; each position can be selected at most once.

For this exercise, assume you return only the maximum length, not the subsequence itself. Return 0 when either string is empty or the strings share no character.

Function

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

Examples

Example 1

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

The characters a, c and e occur in this order in both strings. They need not be adjacent.

Example 2

first = "abc"second = "cab"return = 2

The subsequence ab has length two. No three-character subsequence matches both orders.

Example 3

first = "Ab"second = "ab"return = 1

Only lowercase b matches under case-sensitive equality.

Constraints

  • For this exercise, assume 0 <= first.length, second.length <= 500.
  • Every character is an uppercase or lowercase English letter; equality is case-sensitive.

More Indeed problems

See Indeed hiring insights
public int longestCommonSubsequence(String first, String second) {
    // Write your code here.
    return 0;
}
first"abcde"
second"ace"
expected3
Checking account…