HackerRank Two Strings Solution

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

HackerRank Two Strings Solution
HackerRank Two Strings Solution

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

HackerRank Two Strings Solution

Task

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.

These do not share a substring.

s1 = ‘be’
s2 = ‘cat’

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.

Constraints

  • s1 and s2 consist of characters in the range ascii[a-z].
  • 1 <= p <= 10
  • 1 <= |s1|, |s2| <= 105

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 s2 share no common substrings.

HackerRank Two Strings Solution

Two Strings Solution in C

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
    int k;
    scanf("%d",&k);
    while(k>0)
        {
        char str[110000],btr[110000];
        int cn1[500],cn2[500],i,j,t,a,b;
        for(i=0;i<500;i++)
            {
            cn1[i]=0;
            cn2[i]=0;
        }
        scanf("%s",str);
        scanf("%s",btr);
        a=strlen(str);
        b=strlen(btr);
        for(i=0;i<a;i++)
            {
            cn1[str[i]]++;
        }
        for(i=0;i<b;i++)
            {
            cn2[btr[i]]++;
        }
        t=0;
        for(i=0;i<500;i++)
            {
            if(cn1[i]*cn2[i]>0)
                {
                t=1;
                break;
            }
        }
        if(t)
            {
            printf("YES\n");
        }
        else
            {
            printf("NO\n");
        }
        k--;
    }
    return 0;
}

Two Strings Solution in Cpp

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int a; cin >> a;
    for (int g=0;g<a; g++)
    {
        string b,c; cin >> b >> c; map <char,int> k; 
        for (int y=0;y<b.length(); y++) k[b[y]]=1; int counter=0; 
        for (int y=0;y<c.length(); y++) 
        {
            if (k[c[y]]) counter=1; 
        }
        if (counter) cout << "YES" << '\n';
        else cout << "NO" << '\n'; 
    }return 0; 
}

Two Strings Solution in Java

import java.util.Scanner;
public class Solution {
	public static void main(String[] args) throws Exception {
		Scanner in = new Scanner(System.in);
		int N = in.nextInt();
		testCase:
		for(int i = 0; i < N; i++) {
			String left = in.next();
			String right = in.next();
			boolean[] leftC = new boolean[26];
			for(int j = 0; j < left.length(); j++) {
				leftC[left.charAt(j) - 'a'] = true;
			}
			for(int k = 0; k < right.length(); k++) {
				if(leftC[right.charAt(k) - 'a']) {
					System.out.println("YES");
					continue testCase;
				}
			}
			System.out.println("NO");
		}
	}
}
Ezoicreport this ad

Two Strings Solution in Python

t=input()
for j in xrange(t):
  a=set(raw_input().strip())
  b=set(raw_input().strip())
  if len(a.intersection(b))>0:
    print "YES"
  else:
    print "NO"

Two Strings Solution using JavaScript

function containsCommonSubstring(a,b) {
    // Since a one character common substring is still a substring, we can just check for
    // a character in common.  A map should be easy way to do that.
    var map = {};
    for (var i = 0; i < a.length; i++) {
        // We could count it, but just having an entry should be sufficient.  Seems like a boolean.
        map[a[i]] = true;
    }
    for (var i = 0; i < b.length; i++) {
        if (map[b[i]]) return true;
    }
    return false;
}
function processData(input) {
    var lines = input.split("\n");
    var T = lines[0];
    for (var i = 0; i < T; i++) {
        var a = lines[2*i+1];
        var b = lines[2*i+2];
        if (containsCommonSubstring(a,b)) {
            process.stdout.write("YES\n");
        } else {
            process.stdout.write("NO\n");
        }        
    }
} 
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 Solution in Scala

  object Solution {
    def main(args : Array[String]): Unit = {
      val input = scala.io.Source.stdin.getLines drop 1
      input.grouped(2).foreach { twoLines =>
        val List(str1,str2) = twoLines.toList
        val commonChars = str1.toSet.intersect(str2.toSet)
        if (commonChars.isEmpty) println("NO")
        else println("YES")
      }
    }
  }

Two Strings Solution in Pascal

const fi='';
      fo='';
var a,b:string;
    t:byte;
    f,g:text;
    i:longint;
function kt(a,b:string):boolean;
var j,k:longint;
begin
         kt:=false;
         for j:=1 to length(a) do
          for k:=1 to length(b) do
           if a[j]=b[k] then exit(true);
end;
begin
assign(f,fi);reset(f);
readln(f,t);
assign(g,fo);rewrite(g);
for i:=1 to t do
begin
        readln(f,a);
        readln(f,b);
        if kt(a,b) then writeln(g,'YES') else writeln(g,'NO');
end;
close(g);
close(f);
end.

Disclaimer: This problem (Two Strings) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: HackerRank Sherlock and the Valid String Solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad