Common Child


Problem Statement :


A string is said to be a child of a another string if it can be formed by deleting 0 or more characters from the other string. Given two strings of equal length, what's the longest string that can be constructed such that it is a child of both?

For example, ABCD and ABDC have two children with maximum length 3, ABC and ABD. They can be formed by eliminating either the D or C from both strings. Note that we will not consider ABCD as a common child because we can't rearrange characters and ABCD  ABDC.

Function Description

Complete the commonChild function in the editor below. It should return the longest string which is a common child of the input strings.

commonChild has the following parameter(s):

s1, s2: two equal length strings
Input Format

There is one line with two space-separated strings, s1 and s2.

Constraints

1  <=   | s1 | , | s2 |  <=  5000
All characters are upper case in the range ascii[A-Z].
Output Format

Print the length of the longest string s, such that  is a child of both s1 and s2.



Solution :



title-img


                            Solution in C :

In  C :




#include<stdio.h>
#include<string.h>
char str1[5005],str2[5005];
int c[5005][5005];
int main()
{
  int i,j,m,n;
  scanf("%s %s",str1+1,str2+1);
  m=strlen(str1+1);
  n=strlen(str2+1);
  for(i=1;i<=m;i++)c[i][0]=0;
  for(j=0;j<=n;j++)c[0][j]=0;
  for(i=1;i<=m;i++)
    for(j=1;j<=n;j++)
      {
	if(str1[i]==str2[j])
	  c[i][j]=c[i-1][j-1]+1;
	else if(c[i-1][j]>=c[i][j-1])
	  c[i][j]=c[i-1][j];
	else
	  c[i][j]=c[i][j-1];
      }
  printf("%d\n",c[m][n]);
  return 0;
}
                        


                        Solution in C++ :

In  C++ :





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

int dp[5005][5005];

int main() {
    string a, b;
    cin >> a >> b;
    
    for(int i = 0; i < a.size(); ++i)
        for(int j = 0; j < b.size(); ++j)
            if(a[i] == b[j])
                dp[i + 1][j + 1] = dp[i][j] + 1;
            else
                dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]);
    
    cout << dp[a.size()][b.size()];
    return 0;
}
                    


                        Solution in Java :

In   Java ;





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

public class Solution {

    public static void main(String[] args) {
    	Scanner s = new Scanner(System.in);
		String s1 = s.nextLine();
		String s2 = s.nextLine();
		int[][] lengths = new int[s1.length()+1][s2.length()+1];
		
		for (int i = 1; i < lengths.length; i++) {
			for (int j = 1; j < lengths.length; j++) {
				if (s1.charAt(i-1) == s2.charAt(j-1)) {
					lengths[i][j] = lengths[i-1][j-1] + 1;
				}
				else if (lengths[i][j-1] > lengths[i-1][j]) {
					lengths[i][j] = lengths[i][j-1];
				}
				else {
					lengths[i][j] = lengths[i-1][j];
				}
			}
		}
		System.out.println(lengths[lengths.length-1][lengths.length-1]);
    }
}
                    


                        Solution in Python : 
                            
In  Python3 :






def llis(a, b):
    m = len(a)
    n = len(b)
    prev = [0 for x in range(n + 1)]
    for i in range(1, m + 1):
        curr = [0 for x in range(n + 1)]
        for j in range(1, n + 1):
            curr[j] = max(prev[j], curr[j - 1])
            if a[i - 1] == b[j - 1]:
                curr[j] = max(curr[j], prev[j - 1] + 1)
        prev = curr
    return curr[n]
    
if __name__ == '__main__':
    a = input().strip()
    b = input().strip()
    c = set(a) & set(b)
    a = "".join([x for x in a if x in c])
    b = "".join([x for x in b if x in c])
    print(llis(a, b))
                    


View More Similar Problems

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →

Delete duplicate-value nodes from a sorted linked list

This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -

View Solution →

Cycle Detection

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer

View Solution →

Find Merge Point of Two Lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share

View Solution →

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →

Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

View Solution →