In this post, we will solve Common Child HackerRank Solution. This problem (Common Child) is a part of HackerRank Problem Solving series.
Solution – Common Child – HackerRank Solution
C++
#include <bits/stdc++.h> using namespace std; // Complete the commonChild function below. int commonChild(string s1, string s2) { int iLen1 = s1.length(); int iLen2 = s2.length(); vector<vector<int>> vMatrix(iLen2 + 1, vector<int>(iLen1 + 1, 0)); for (int i = 1; i <= iLen2; ++i) { for (int j = 1; j <= iLen1; ++j) { if ( s2[i - 1] == s1[j - 1] ) { vMatrix[i][j] = vMatrix[i-1][j-1] + 1; } else { vMatrix[i][j] = max(vMatrix[i-1][j], vMatrix[i][j-1]); } } } return vMatrix[iLen2][iLen1]; } int main() { ofstream fout(getenv("OUTPUT_PATH")); string s1; getline(cin, s1); string s2; getline(cin, s2); int result = commonChild(s1, s2); fout << result << "\n"; fout.close(); return 0; }
Python
import os # Complete the commonChild function below. def commonChild(s1, s2): maxAt = {} for i1 in range(len(s1)): maxForI1 = 0 for i2 in range(len(s2)): potentialSum = maxForI1 + 1 # You might be tempted to use the max() function to simplify the next three lines, # but that makes the solution so much slower that several of the test cases fail. other = maxAt.get(i2, 0) if other > maxForI1: maxForI1 = other if s1[i1] == s2[i2]: maxAt[i2] = potentialSum return max(maxAt.values(), default=0) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s1 = input() s2 = input() result = commonChild(s1, s2) fptr.write(str(result) + '\n') fptr.close()
Java
import java.io.*; import java.util.*; public class Solution { public int child(String str1, String str2){ int L[][] = new int[str1.length()+1][str2.length()+1]; for(int i=0;i<=str1.length();i++){ for(int j=0;j<=str2.length();j++){ if(i==0 || j==0) L[i][j]=0; else if(str1.charAt(i-1)==str2.charAt(j-1)){ L[i][j] = L[i-1][j-1]+1; } else{ L[i][j] = Math.max(L[i-1][j],L[i][j-1]); } } } return L[str1.length()][str2.length()]; } public static void main(String[] args){ Solution ob = new Solution(); Scanner sc = new Scanner(System.in); String str1 = sc.nextLine(); String str2 = sc.nextLine(); int ans = ob.child(str1,str2); System.out.println(ans); } }
Note: This problem (Common Child) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.