Longest Common Subsequence

You have been given two Strings “STR1” and “STR2” of characters. Your task is to find the length of the longest common subsequence.

A String ‘a’ is a subsequence of a String ‘b’ if ‘a’ can be obtained from ‘b’ by deletion of several (possibly, zero or all) characters. A common subsequence of two Strings is a subsequence that is common to both Strings.

Input Format :
The first line contains an integer ‘T’ denoting the number of test cases. Then each test case follows. 

The first input line of each test case contains two space-separated Strings “STR1” and “STR2” representing two Strings. 
Output Format :
For each test case, print the length of the longest common subsequence. 

Print the output of each test case in a separate line. 
Note:
You are not required to print the expected output; it has already been taken care of. Just implement the function. 
Constraints :
1 <= T <= 50 
1 <= |STR1| <= 10^2
1 <= |STR2| <= 10^2

Where |STR1| and |STR2| denote the length of “STR1” and “STR2” respectively. 

Time Limit: 1 sec 
CodingNinjas
author
2y

This problem can be solved using recursion. In this approach, we will start form last element of both the strings. If elements at the last matches then we will decrement length of both the string else...read more

CodingNinjas
author
2y
Recursive Brute Force

The basic idea of this approach is to break the original problem into sub-problems. Let us assume we want to find the length of the longest common subsequence of “STR1” and “STR2...read more

CodingNinjas
author
2y
Recursive + Memoization.

Let us observe the recursion tree for the case where STR1 = “abc” and STR2 = “cabd”

After observing the tree, we’ll find that there are some redundant function calls which mean...read more

CodingNinjas
author
2y
Iterative Dynamic Programming + Memoization.

The basic idea of this approach is to solve the problem iteratively.

Let DP[I] J] be our dynamic programming matrix to store the length of LCS of substring ...read more

CodingNinjas
author
2y
Dynamic Programming + Space Optimization

We can observe in the previous approach that the current state depends on one immediate previous row. This suggests using a dynamic programming matrix of 2*M di...read more

Add answer anonymously...
One Convergence Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter