Two Strings - HashMap - Easy - HackerRank
💻 coding

Two Strings - HashMap - Easy - HackerRank

1 min read 259 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to determine if two strings share a common substring, which can be as small as one character.
  • 2The function twoStrings returns 'YES' if a common substring exists and 'NO' otherwise.
  • 3The solution uses a HashSet to efficiently check for common characters between the two strings.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to determine if two strings share a common substring, which can be as small as one character."

Two Strings - HashMap - Easy - HackerRank

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 . Constraints

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

For each pair of strings, return YES or NO.

Sample Input

2 hello world hi world Sample Output

YES NO Explanation

using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Solution {

 // Complete the twoStrings function below.
 static string twoStrings(string s1, string s2) {
 var set = new HashSet<char>();
 for(int i=0;i<s1.Length;i++){
 set.Add(s1[i]);
 }

 for(int i=0;i<s2.Length;i++){
 if(set.Contains(s2[i])){
 return "YES";
 } 
 }

 return "NO";
 }

 static void Main(string[] args) {
 TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

 int q = Convert.ToInt32(Console.ReadLine());

 for (int qItr = 0; qItr < q; qItr++) {
 string s1 = Console.ReadLine();

 string s2 = Console.ReadLine();

 string result = twoStrings(s1, s2);

 textWriter.WriteLine(result);
 }

 textWriter.Flush();
 textWriter.Close();
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 24 October 2020 · 1 min read · 259 words

Part of AskGif Blog · coding

You might also like

Two Strings - HashMap - Easy - HackerRank | AskGif Blog