HackerRank Common Child Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Common Child Solution. This problem is a part of the HackerRank Algorithms Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

HackerRank Common Child Solution
HackerRank Common Child Solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

HackerRank Common Child


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. Letters cannot be rearranged. Given two strings of equal length, what’s the longest string that can be constructed such that it is a child of both?


s1 = ‘ABCD’
s2 = ‘ABDC’

These strings have two children with maximum length 3, ABC and ABD. They can be formed by eliminating either the D or C from both strings. Return 3.

Function Description

Complete the commonChild function in the editor below.

commonChild has the following parameter(s):

  • string s1: a string
  • string s2: another string


  • int: the length of the longest string which is a common child of the input strings

Input Format

There are two lines, each with a string, s1 and s2.


  • 1 <= |s1|, |s2| <= 5000 where |s| means “the length of s
  • All characters are upper case in the range ascii[A-Z].

Sample Input


Sample Output



The longest string that can be formed by deleting zero or more characters from HARRY and SALLY is AY, whose length is 2.

Sample Input 1


Sample Output 1


Explanation 1

AA and BB have no characters in common and hence the output is 0.

Sample Input 2


Sample Output 2


Explanation 2

The longest string that can be formed between SHINCHAN and NOHARAAA while maintaining the order is NHA.

Sample Input 3


Sample Output 3


Explanation 3

BD is the longest child of the given strings.

HackerRank Common Child Solution

Common Child Solution in C

#define SORT(a,n) qsort(a,n,sizeof(int),intcmp)
#define s(n)                        scanf("%d",&n)
#define sc(n)                       scanf("%c",&n)
#define sl(n)                       scanf("%I64d",&n)
#define sf(n)                       scanf("%lf",&n)
#define ss(n)                       scanf("%s",n)
#define fill(a,v)                   memset(a, v, sizeof(a))
int intcmp(const void *f,const void *s)
   return (*(int *)f -*(int *)s);
int gcd(int a,int b){ return ((b==0)?a:gcd(b,a%b));}
int max(int a,int b){ return(a>b)?a:b;}

#define MAX 8192
#define MODBY 1000000007

typedef long long int lld;
typedef long double Lf;
int preprocess()
   return 0;
int lcs[MAX][MAX];
int main()
   int cases;
   int i,j,n;
   char a[MAX],b[MAX];
         else lcs[i][j]=max(lcs[i-1][j],lcs[i][j-1]);
   return 0;

Common Child Solution in Cpp

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <cstring>
#include <string>
#include <cmath>
#include <ctime>
#include <utility>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <sstream>
#define FOR(a,b,c) for (int a=b,_c=c;a<=_c;a++)
#define FORD(a,b,c) for (int a=b;a>=c;a--)
#define REP(i,a) for(int i=0,_a=(a); i<_a; ++i)
#define REPD(i,a) for(int i=(a)-1; i>=0; --i)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define sz(a) int(a.size())
#define reset(a,b) memset(a,b,sizeof(a))
#define oo 1000000007

using namespace std;

typedef long long ll;
typedef pair<int, int> pii;

const int maxn=5007;

int dp[maxn][maxn],n;
char a[maxn],b[maxn];

int main(){
    FOR(i,1,n) FOR(j,1,n){
        if(a[i]==b[j]) dp[i][j]=max(dp[i][j],dp[i-1][j-1]+1);
    return 0;

Common Child Solution 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) throws IOException
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        char x[]=br.readLine().toCharArray();
        char y[]=br.readLine().toCharArray();
        int a[][]=new int[x.length+1][];
        int dir[][]=new int[x.length+1][];//0 for terminating condtion,1=diagonal,2=left,3=upper
        for(int i=0;i<a.length;i++)
            a[i]=new int[y.length+1];
            dir[i]=new int[y.length+1];
        for(int i=1;i<x.length+1;i++)
            for(int j=1;j<a[0].length;j++)
             /*   if(i==0||j==0)
                    if(a[i-1][j]>a[i][j-1])//upper is greater
                    else//left is greater
        int row=a.length-1;
        int col=a[0].length-1;

Common Child Solution in Python

from __future__ import division
from sys import stdin
from collections import defaultdict

def lcs(s1, s2):
    prev = defaultdict(int)
    for i in range(len(s1)):
        cur = defaultdict(int)
        for j in range(len(s2)):
            cur[j] = prev[j - 1] + 1 if s1[i] == s2[j] else max(cur[j - 1], prev[j])
        prev = cur
    return prev[len(s2)-1]
def main():
    s, t = stdin.next().strip(), stdin.next().strip()
    print lcs(s, t)


Common Child Solution using JavaScript

function processData(input) {
    var parts = input.split("\n"),
        firstStr = parts[0],
        secondStr = parts[1],
        strLen = firstStr.length,
  		arrPrev = new Array(strLen + 1),
        arrCurr = new Array(strLen + 1);
  	for (var ii = 0; ii <= strLen; ii++) {
      arrPrev[ii] = 0;
      arrCurr[ii] = 0;
  	//for (var ii = 0; ii <= strLen; ii++) {
    //  console.log(arrPrev[ii]);
  	for (ii = 1; ii <= strLen; ii++) {
      for (var jj = 1; jj <= strLen; jj++) {
        if (firstStr[ii - 1] == secondStr[jj - 1]) {
          arrCurr[jj] = arrPrev[jj - 1] + 1;
        else {
          arrCurr[jj] = Math.max(arrCurr[jj - 1], arrPrev[jj]);
      arrPrev = arrCurr.slice(0);

_input = "";
process.stdin.on("data", function (input) {
    _input += input;

process.stdin.on("end", function () {

Common Child Solution in Scala

object Solution {
  def lcs(x: String, y: String): Int = {
    val m = x.length
    val n = y.length
    val c = Array.ofDim[Int](m + 1, n + 1)
    for (i <- 1 to m; j <- 1 to n) {
      if (x(i - 1) == y(j - 1)) c(i)(j) = c(i - 1)(j - 1) + 1
      else c(i)(j) = c(i)(j - 1) max c(i - 1)(j)

  def main(args: Array[String]): Unit = {
    val a = readLine()
    val b = readLine()
    println(lcs(a, b))

Common Child Solution in Pascal

var s1,s2:ansistring;
    f:array[0..5000,0..5000] of integer;
    readln(s1);readln(s2); n:=length(s1);
    for i:=0 to n do f[0,i]:=0;
    for j:=0 to n do f[j,0]:=0;
    for i:=1 to n do
        for j:=1 to n do 
            if s1[i]=s2[j] then f[i,j]:=f[i-1,j-1]+1 else
                if f[i-1,j]>f[i,j-1] then f[i,j]:=f[i-1,j] else f[i,j]:=f[i,j-1];

Disclaimer: This problem (Common Child) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.


1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite. 

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedi

Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe. 

Sharing Is Caring

Leave a Comment