Length of a Longest Shared Subsequence

Quick Overview

Length of a Longest Shared Subsequence. Return the maximum length of a sequence appearing in both text1 and text2 after deleting zero or more characters without reordering those left.

Length of a Longest Shared Subsequence

Company: Apple

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem Return the maximum length of a sequence appearing in both text1 and text2 after deleting zero or more characters without reordering those left. The characters need not be contiguous. Return 0 when they share no character. ```cpp class Solution { public: int longestCommonSubsequence(string text1, string text2); }; ``` ### Examples **Example 1:** ```text Input: text1 = "abcd", text2 = "bd" Output: 2 Explanation: bd is a subsequence of each and uses all of the shorter string. ``` **Example 2:** ```text Input: text1 = "aaaa", text2 = "aa" Output: 2 Explanation: Each matching occurrence can be used once, so the shorter length is the limit. ``` ### Constraints - Each input string has length 1 to 1000. - Both use lowercase English letters only. ### Contract considerations Return only a length; multiple longest subsequences do not create ambiguity in this numeric result. ```hint Read the boundary condition May a shared sequence skip positions in either input without reordering the characters it keeps? ``` ### Boundary reminders Return only a length; multiple longest subsequences do not create ambiguity in this numeric result.

Overview: Length of a Longest Shared Subsequence. Return the maximum length of a sequence appearing in both text1 and text2 after deleting zero or more characters without reordering those left.

Apple logo
Apple
Source window: 0–3 months · as of Oct 21, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Return the maximum length of a sequence appearing in both text1 and text2 after deleting zero or more characters without reordering those left. The characters need not be contiguous. Return 0 when they share no character.

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2);
};

Examples

Example 1:

Input: text1 = "abcd", text2 = "bd"
Output: 2
Explanation: bd is a subsequence of each and uses all of the shorter string.

Example 2:

Input: text1 = "aaaa", text2 = "aa"
Output: 2
Explanation: Each matching occurrence can be used once, so the shorter length is the limit.

Constraints

  • Each input string has length 1 to 1000.
  • Both use lowercase English letters only.

Contract considerations

Return only a length; multiple longest subsequences do not create ambiguity in this numeric result.

Boundary reminders

Return only a length; multiple longest subsequences do not create ambiguity in this numeric result.