Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Longest Common Subsequence

Medium Acceptance 50.00% Points 30.00

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.

Hints
Hint 1
Expected Time Complexity: O(m * n)
Hint 2
Expected Auxiliary Space: O(m * n)
Hint 3
where m and n are sizes of s1 and s2 respectively.
Constraints
  • 1<= m, n <=10^3
  • Both strings s1 and s2 contain only uppercase English letters.
Companies
Amazon Microsoft
Topics
Array String Dynamic Programming
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions