Hackerrank - Two Strings Solution
1 min read

Hackerrank - Two Strings Solution

Hackerrank - Two Strings Solution

Given two strings, determine if they share a common substring. A substring may be as small as one character.

For example, the words "a", "and", "art" share the common substring . The words "be" and "cat" do not share a substring.

Function Description

Complete the function twoStrings in the editor below. It should return a string, either YES or NO based on whether the strings share a common substring.

twoStrings has the following parameter(s):

  • s1, s2: two strings to analyze .

Input Format

The first line contains a single integer , the number of test cases.

The following  pairs of lines are as follows:

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


  • and  consist of characters in the range ascii[a-z].

Output Format

For each pair of strings, return YES or NO.

Sample Input


Sample Output



We have  pairs to check:

  1. s1= "hello", s2="world" . The substrings "o" and "l" are common to both strings.
  2. a="hi", b="world" . a and b share no common substrings.

Solution in Python

def twoStrings(s1, s2):
    return "YES" if set(s1) & set(s2) else "NO"
for _ in range(int(input())):
    print(twoStrings(input(), input()))

We can also write as follows

def twoStrings(s1, s2):
    if set(s1) & set(s2):
        return "YES"
        return "NO"
for _ in range(int(input())):
    print(twoStrings(input(), input()))

Solution Explanation

First, we convert both s1 and s2 as sets, so that we can apply set operations.

Now to get the common elements between s1 and s2. We just have to use a set intersection.

We can write set intersection, where a and b are two sets, in python as

a & b

or we can write it as follows


Enjoying these posts? Subscribe for more

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.