Skip to content
TheCScience
TheCScience
  • Home
  • Human values
  • NCERT Solutions
  • HackerRank solutions
    • HackerRank Algorithms problems solutions
    • HackerRank C solutions
    • HackerRank C++ solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
TheCScience
HackerRank Two Strings Problem Solution

HackerRank Two Strings Problem Solution

Yashwant Parihar, April 28, 2023May 6, 2023

In this post, we will solve HackerRank Two Strings Problem Solution.

Given two strings, determine if they share a common substring. A substring may be as small
as one character.
Example
s1 = ‘and’
s2 = ‘art’
These share the common substring a.
s1 = ‘be’
s2 = ‘cat’
These do not share a substring.

Function Description

Complete the function twoStrings in the editor below.

twoStrings has the following parameter(s):

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

Returns

  • string: either YES or NO

Input Format
The first line contains a single integer p, the number of test cases.
The following p pairs of lines are as follows:

  • The first line contains string s1.
  • The second line contains string s2.

Output Format

For each pair of strings, return YES or NO.

Sample Input

2
hello
world
hi
world

Sample Output

YES
NO

Explanation
We have p = 2 pairs to check:

  1. s1 “hello”, s2 = “world”. The substrings “o” and “1” are common to both
    strings.
  2. a “hi”, b = “world”. s1 and $2 share no common substrings.
HackerRank Two Strings Problem Solution
HackerRank Two Strings Problem Solution

Two Strings C Solution

#include<stdio.h>
#include<string.h>
int main()
{
	int k,t;
	char *i,*j;
	char s1[200000],s2[200000],ch;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%s",s1);
		scanf("%s",s2);
		ch='a';
		k=0;
		while(ch<='z')
		{
			i=strchr(s1,ch);
			j=strchr(s2,ch);
			if(i!=NULL && j!=NULL)
			{
				k++;
				break;
			}
			else
				ch=ch+1;
		}
		if(k==1)
			printf("YES\n");
		else
			printf("NO\n");
	}
}

Two Strings C++ Solution

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


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int t;
    cin>>t;
    cin.ignore();
    for (int i=0;i<t;i++){
        string s1,s2;
        getline(cin,s1);
        getline(cin,s2);
        int c[256];
        bool flag=false;
        for (int j=0;j<256;j++){
            c[j]=0;
        }
        for (int j=0;j<s1.length();j++){
            c[s1[j]-'a']++;
        }
        for (int j=0;j<s2.length();j++){
            if (c[s2[j]-'a']!=0){
                cout<<"YES"<<endl;
                flag=true;
                break;
            }
        }
        if (!flag){
            cout<<"NO"<<endl;
        }
    }
    
    return 0;
}

Two Strings C Sharp Solution

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

public class HC
    {
        public bool HaveCommon(char[] a, char[] b)
        {
            foreach (char c in a)
            {
                //foreach (char d in b)
                //    if (d == c) return true;
                if (b.Contains(c)) return true;
            }
            return false;
        }
    }

class Solution {
    static void Main(String[] args) {
        int n = int.Parse(Console.ReadLine());
             List<string> answers = new List<string>();

             for (int i = 0; i < n; i++)
             {
                 string temp = Console.ReadLine();
                 char[] a = temp.ToCharArray().Distinct().ToArray();
                 temp = Console.ReadLine();
                 char[] b = temp.ToCharArray().Distinct().ToArray();
                 HC hc = new HC();
                 if (hc.HaveCommon(a, b))
                     answers.Add("YES");
                 else
                     answers.Add("NO");
             }

             foreach (string s in answers) Console.WriteLine(s);
    }
}

Two Strings Java Solution

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'twoStrings' function below.
     *
     * The function is expected to return a STRING.
     * The function accepts following parameters:
     *  1. STRING s1
     *  2. STRING s2
     */

    public static String twoStrings(String s1, String s2) {
      Set<Character> s1Set = new HashSet<>();
        Set<Character> s2Set = new HashSet<>();

        for (char c : s1.toCharArray()) {
            s1Set.add(c);
        }
        for (char c : s2.toCharArray()) {
            s2Set.add(c);
        }

        Set<Character> biggestSet = s1Set.size() >= s2Set.size() ? s1Set : s2Set;
        Set<Character> comparedSet = biggestSet == s1Set ? s2Set : s1Set;

        for (Character symbol : biggestSet) {
            if (comparedSet.stream().anyMatch(c -> c.equals(symbol))) {
                return "YES";
            }
        }

        return "NO";

    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int q = Integer.parseInt(bufferedReader.readLine().trim());

        IntStream.range(0, q).forEach(qItr -> {
            try {
                String s1 = bufferedReader.readLine();

                String s2 = bufferedReader.readLine();

                String result = Result.twoStrings(s1, s2);

                bufferedWriter.write(result);
                bufferedWriter.newLine();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Two Strings JavaScript Solution

function processData(input) {
    var lines = input.split("\n");
    var N = parseInt(lines[0]);
    var s1,s2,hash=[];
    for(var i = 0 ; i<N ; i++){
        hash=[];
        s1=lines[i*2+1];
        s2=lines[i*2+2];
        for(var j = 0 ; j < s1.length ; j++){
            hash[s1.charAt(j)+""]="true";
        }
        for(var j = 0 ; j < s2.length ; j++){
            if(hash[s2.charAt(j)]=="true"){
                console.log("YES");
                break;
            }
            if(j==s2.length-1)console.log("NO");
        }
    }
} 

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

process.stdin.on("end", function () {
   processData(_input);
});

Two Strings Python Solution

def common(a, b):
    L = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    for c in L:
        if c in a and c in b:
            return "YES"
    return "NO"


t = int(input())
for t in range(t):
    a = input()
    b = input()
    print(common(a, b))

Other Solutions

  • HackerRank String Construction Problem Solution
  • HackerRank Sherlock and the Valid String Solution
c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython

Post navigation

Previous post
Next post

Leave a Reply

You must be logged in to post a comment.

  • HackerRank Dynamic Array Problem Solution
  • HackerRank 2D Array – DS Problem Solution
  • Hackerrank Array – DS Problem Solution
  • Von Neumann and Harvard Machine Architecture
  • Development of Computers
©2025 TheCScience | WordPress Theme by SuperbThemes