Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Longest Common Subsequence

Medium Acceptance 50% Points 30

Given two strings, s1 and s2, the task is to find the length of the Longest Common Subsequence. If there is no common subsequence, return 0. A subsequence is a string generated from the original string by deleting 0 or more characters, without changing the relative order of the remaining characters.

Examples
Example 1

Example 1

Input: s1 = "XYZW", s2 = "XYWZ"

Output: 3

Explanation: The longest common subsequences of "XYZW" and "XYWZ" are "XYZ" and "XYW", both of length 3.

Example 2

Example 2

Input: s1 = "ABCDGH", s2 = "AEDFHR"

Output: 3

Explanation: The longest common subsequence of "ABCDGH" and "AEDFHR" is "ADH", which has a length of 3.

Constraints
  • 1<= m, n <=10^3
  • Both strings s1 and s2 contain only uppercase English letters.
Hints
  • Expected Time Complexity: O(m * n)
  • Expected Auxiliary Space: O(m * n)
  • where m and n are sizes of s1 and s2 respectively.
Topics
Array String Dynamic Programming
Companies
Amazon Microsoft
Added 12 Mar 2025 50% acceptance
Ln 1, Col 1Sign in to save your code
XYZW
XYWZ
3