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

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

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...