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

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 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.st

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 last