Skip to main content

Two Strings HackerRank solution in Java with Explanation | Programming Blog

Find common substring in Java from two String

Two Strings HackerRank solution in Java with Explanation | Programming Blog

Problem Description :

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

Example 1 :

s1 = "and"
s2 = "art"

These share the common substring 'a'.

So answer will be YES

Example 2 :

s1 = "Hi"
s2 = "World"

Answer : NO

See full description on Hackerrank :

Two Strings Problem Description

Lets see solution :

We will see two solutions :

  1. Using Map
  2. Using Character Array

In this problem, first approach pass all test cases but second approach gives Time Limit Error. but for learning purpose we will see that also. So lets turn on learning mode.

Solution 1 : Finding common substring using Map in Java

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    static String twoStrings (String s1, String s2) {
        
        boolean containsSubstring = false;
        Map<Character, Integer> map = new HashMap<>();
        
        for (int i = 0; i < s1.length(); i++) {
            map.put(s1.charAt(i), i);
        }
        
        for (int j = 0; j < s2.length(); j++) {
            if (map.containsKey(s2.charAt(j))) {
                containsSubstring = true;
                break;
            }
        }
        return containsSubstring ? "YES" : "NO";
    }


    private static final Scanner scanner = new Scanner(System.in);

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

        int q = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int qItr = 0; qItr < q; qItr++) {
            String s1 = scanner.nextLine();

            String s2 = scanner.nextLine();

            String result = twoStrings(s1, s2);

            bufferedWriter.write(result);
            bufferedWriter.newLine();
        }

        bufferedWriter.close();

        scanner.close();
    }
}

Solution Explanation :

  • Create new HashMap with Character as key and Integer as value.
  • Loop through String length and store all characters of String s1 using charAt() method in Map. Take character as Key and index as Value (we can take any integer as value).
  • Now traverse through second String till string length and check for current character is contains in map or not. If current character matches with map key we will assign true to containsSubstring variable and break the for loop. 
  • Last, return "YES" or "NO" string based on containsSubstring variable.

Output Explanation :

s1 = java
s2 = csharp

  • containsSubstring = false
  • For loop for string s1 or s2 characters in map (we are putting s1)
  • i = 0, s1.length = 4 | 0 < 4 becomes true
    • map = [j = 0]
  • i = 1 | 1 < 4 becomes true
    • map = [j = 0, a = 1]
  • i = 2 | 2 < 4 becomes true
    • map = [j = 0, a = 1, v = 2]
  • i = 3 | 3 < 4 becomes true
    • map = [j = 0, a = 3, v = 2]
  • i = 4 | 4 < 4 becomes false

  • For loop | Checking s2 characters in s1
  • j = 0, s2.length = 6 | 0 < 6 becomes true
    • if (map.containsKey(s2.charAt(j))) | map does not contains character 'c' so becomes false
  • j = 1 | 1 < 6 becomes true
    • map does not contains character 's' so becomes false   
  • j = 2 | 2 < 6 becomes true
    • map does not contains character 'h' so becomes false
  • j = 3 | 3 < 6 becomes true
    • map contains character 'a' so becomes true
      • containsSubstring = true
      • break for loop; 
  • containsSubstring ? "YES" : "NO" | Return YES.

 

Solution 2 : Two Strings solution using For loop in Java (brute force approach)

As i said above this solution gives Time limit exceeded error on HackerRank.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    static String twoStrings(String s1, String s2) {
        boolean containsSubstring = false;
        
        for (int i = 0; i < s1.length(); i++) {
            for (int j = 0; j < s2.length(); j++) {
                if (s1.charAt(i) == s2.charAt(j)) {
                    containsSubstring = true;
                    break;
                }
            }    
            if (containsSubstring) {
                break;
            }
        }
        return containsSubstring ? "YES" : "NO";
    }


    private static final Scanner scanner = new Scanner(System.in);

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

        int q = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int qItr = 0; qItr < q; qItr++) {
            String s1 = scanner.nextLine();

            String s2 = scanner.nextLine();

            String result = twoStrings(s1, s2);

            bufferedWriter.write(result);
            bufferedWriter.newLine();
        }

        bufferedWriter.close();

        scanner.close();
    }
}

Solution explanation :

  • In this we are using brute force technique, means we are checking all characters of both string until find same.
  • So first we are traverse through first string 0 to string length.
  • In second for loop we are taking all characters one by one and checking with first sting's characters.
  • If any characters match we are set to true containsSubstring variable and break the both loop.
  • Last, return "YES" or "NO" based on containsSubstringvariable.

 

Happy Learning... Happy Coding ...

Other HackerRank Solutions and Articles :

Comments

Popular posts from this blog

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And ...

Sales by Match HackerRank Solution | Java Solution

HackerRank Sales by Match problem solution in Java   Problem Description : Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n=7 socks with colors socks = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .   Example 1 : Input : n = 6 arr = [1, 2, 3, 4, 5, 6] Output : 0 Explanation : We have 6 socks with all different colors, So print 0. Example 2 : Input : n = 10 arr = [1, 2, 3, 4, 1, 4, 2, 7, 9, 9] Output : 4 Explanation : We have 10 socks. There is pair of color 1, 2, 4 and 9, So print 4. This problem easily solved by HashMap . Store all pair of socks one by one in Map and check if any pair is present in Map or not. If pair is present then increment ans variable by 1 ...