LCS Returns

Problem Statement :

Given two strings, a and b, find and print the total number of ways to insert a character at any position in string a such that the length of the Longest Common Subsequence of characters in the two strings increases by one.

Input Format

The first line contains a single string denoting a.
The second line contains a single string denoting b.



1 <= |a|,|b| <= 5000
Strings a and b are alphanumeric (i.e., consisting of arabic digits and/or upper and lower case English letters).
The new character being inserted must also be alphanumeric (i.e., a digit or upper/lower case English letter).


1 <= |a|,|b| <= 1000 for 66.7% of the maximum score.
Output Format

Print a single integer denoting the total number of ways to insert a character into string a in such a way that the length of the longest common subsequence of a and b increases by one.

Solution :


                            Solution in C :

In C++ :

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;

char a[6000], b[6000];
int la, lb;
int Pref[5005][5005], Suff[5005][5005];
bool Can[256];

int main() {
    cin >> (a + 1) >> (b + 1);
    la = strlen(a + 1);
    lb = strlen(b + 1);

    for(int i = 1; i <= la; ++i)
        for(int j = 1; j <= lb; ++j) {
            if(a[i] == b[j]) {
                Pref[i][j] = 1 + Pref[i - 1][j - 1];
            } else {
                Pref[i][j] = max(Pref[i - 1][j], Pref[i][j - 1]);
    for(int i = la; i >= 1; --i)
        for(int j = lb; j >= 1; --j) {
            if(a[i] == b[j])
                Suff[i][j] = 1 + Suff[i + 1][j + 1];
                Suff[i][j] = max(Suff[i + 1][j], Suff[i][j + 1]);
    int best = Pref[la][lb];
    int cnt = 0;
    for(int i = 1; i <= la + 1; ++i) {
        memset(Can, 0, sizeof(Can));
        for(int j = 1; j <= lb; ++j) {
            if(Can[b[j]]) continue;
            if(Pref[i - 1][j - 1] + Suff[i][j + 1] == best) {
                Can[b[j]] = 1;
                cnt += 1;
    cout << cnt << endl;
    return 0;

In Java :

import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(;
        char[] a =;
        char[] b =;
        int n = a.length;
        int m = b.length;
        int[][] dp = new int[n+2][m+2];
        int[][] dp2 = new int[n+2][m+2];
        for (int i=1; i<=n; i++) {
            for (int j=1; j<=m; j++) {
                if (a[i-1] == b[j-1]) {
                    dp[i][j] = dp[i-1][j-1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]);
        int r = dp[n][m], ans = 0;
        for (int i=n; i>=1; i--) {
            for (int j=m; j>=1; j--) {
                if (a[i-1] == b[j-1]) {
                    dp2[i][j] = dp2[i+1][j+1] + 1;
                } else {
                    dp2[i][j] = Math.max(dp2[i][j+1], dp2[i+1][j]);
        for (int i=0; i<=n; i++) {
            Set<Character> set = new HashSet<>();
            for (int j=1; j<=m; j++) if (!set.contains(b[j-1])) {
                int v = dp[i][j-1] + dp2[i+1][j+1];
                //System.out.print(v+" ");
                if (v == r) {
          //  System.out.println();

In C :

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int d1[5002][5002];
int d2[5002][5002];
char s1[6000],s2[6000];
int cc[256];

int main() {
    int i,j,l1,l2,p,c,ret=0;
    scanf("%s %s",s1,s2);
    for(i=1;i<=l1;i++) for(j=1;j<=l2;j++) {
        if (d1[i][j-1]>d1[i][j]) d1[i][j]=d1[i][j-1];
        if (s1[i-1]==s2[j-1]) d1[i][j]=d1[i-1][j-1]+1;
    for(i=l1-1;i>=0;i--) for(j=l2-1;j>=0;j--) {
        if (d2[i][j+1]>d2[i][j]) d2[i][j]=d2[i][j+1];
        if (s1[i]==s2[j]) d2[i][j]=d2[i+1][j+1]+1;
    for(i=0;i<=l1;i++) {
        for(j=0;j<l2;j++) if (d1[i][j]+d2[i][j+1]==d1[l1][l2]) cc[s2[j]]=1;
        for(j=0;j<128;j++) if (cc[j]) ret++,cc[j]=0;
    return 0;

In Python3 :

import string

#calculates longest common subsequence of 2 strings
def lcs(s1, s2):
    n = len(s1)
    m = len(s2)
    dp = [[0 for _ in range(m+1)] for _ in range(n+1)]
    for i in range(n):
        for j in range(m):
            if (s1[i] == s2[j]):
                dp[i+1][j+1] = dp[i][j] + 1
                dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j])
    return dp

#returns array of indexes from string 2 for each alphabet letter
def alpIndexes(s, alp):
    d = dict()
    for letter in alp:
        d[letter] = []
    for i in range(len(s)):
    return d

s1 = input().strip()
s2 = input().strip()
n = len(s1)
m = len(s2)
chars = list(string.ascii_lowercase) #lowercase alphabet letters array
charIndexes = alpIndexes(s2, chars)

dpl = lcs(s1, s2)
dpr = lcs(s1[::-1], s2[::-1])
lcs = dpl[n][m]
ans = 0
for i in range(0, n+1):
    for letter in chars:
        for j in charIndexes[letter]:
            if (dpl[i][j] + dpr[n-i][m-j-1] == lcs):
                ans += 1

View More Similar Problems

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →

Largest Rectangle

Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle

View Solution →

Simple Text Editor

In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,

View Solution →

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →


You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →