Skip to main content

Between Two Sets Hackerrank solution in Java with explanation

Java solution for Between Two Sets HackerRank Problem

Between Two Sets in java

There will be two arrays of integers. Determine all integers that satisfy the following two conditions:

  1. The elements of the first array are all factors of the integer being considered
  2. The integer being considered is a factor of all elements of the second array

These numbers are referred to as being between the two arrays. Determine how many such numbers exist.

So we have to all common numbers that are 

  1. Multiple of first array and  
  2. Factors of second array

Example 1 :

a = [2, 6]

b = [24, 36]

There are two numbers between the arrays : 6, 12. So answer is 2. 

Explanation :

Multiple of first array :

2 = 2, 4, 6, 8, 10, 12, 14 ...
6 = 6, 12, 18, 24, 30, 36 ...

Factors of second array :

24 = 1, 2, 3, 4, 6, 8, 12, 24
36 = 1, 2, 3, 4, 6, 9, 12, 18, 36

So all common numbers from both arrays are : 6 and 12, so answer is 2.

Example 2 :

a = [2, 4]

b = [16, 32, 96]

There are three numbers between the arrays : 4, 8 and 16. So answer is 3.

Explanation :

Multiple of first array :

2 = 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 ...
4 = 4, 8, 12, 16, 20, 24, 28, 32, 36 ...

Factors of second array :

16 = 1, 2, 4, 8, 16
32 = 1, 2, 4, 8, 16, 32
96 = 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 96

So all common numbers from both arrays are : 4, 8 and 16, so answer is 3.

See full description on HackerRank :

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.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    public static int getTotalX(List<Integer> a, List<Integer> b) {
    
        int lcm = a.get(0);
        for (int number : a) {
            lcm = getLCM(number, lcm);
        }
        
        int gcd = b.get(0);
        for (Integer integer : b) {
          gcd = getGCD(gcd, integer);
        }
        
        int result = 0;
        int multiple = 0;
        while (multiple <= gcd) {
          multiple += lcm;

          if (gcd % multiple == 0)
            result++;
        }

       return result;
    }
    
    static int getLCM(int n1, int n2) {
        if (n1 == 0 || n2 == 0)
          return 0;
        else {
          int gcd = getGCD(n1, n2);
          return Math.abs(n1 * n2) / gcd;
        }
    }
    
    static int getGCD(int n1, int n2) {
        if (n2 == 0) {
          return n1;
        }
        return getGCD(n2, n1 % n2);
    }


}

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

        String[] firstMultipleInput = bufferedReader.readLine()
            .replaceAll("\\s+$", "")
            .split(" ");

        int n = Integer.parseInt(firstMultipleInput[0]);

        int m = Integer.parseInt(firstMultipleInput[1]);

        List<Integer> arr = Stream.of(bufferedReader.readLine()
            .replaceAll("\\s+$", "").split(" "))
            .map(Integer::parseInt)
            .collect(toList());

        List<Integer> brr = Stream.of(bufferedReader.readLine()
            .replaceAll("\\s+$", "").split(" "))
            .map(Integer::parseInt)
            .collect(toList());

        int total = Result.getTotalX(arr, brr);

        bufferedWriter.write(String.valueOf(total));
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Solution explanation :

  • First we loop through first list and find LCM (least common multiple).
  • second we loop through second list and find GCD (Greatest common divisor) from that list.
  • And last, we do multiple of LCM and check GCD value divide by LCM or not. if GCD is dividable then we increment result by 1.

Output Explanation :

a = [2, 4]
b = [16, 32, 96]

  • lcm = 2, gcd = 16, multiple = 0, result = 0
    • After execute getLCM we get lcm = 4
    • After execute getGCD we get gcd = 16

  • lcm = 4, gcd = 16, multiple = 0, result = 0
    • while loop
    • multiple += lcm | 0 + 4 = 4
    • gcd % multiple == 0 | 16 % 4 == 0 becomes true
      • result = 1

  • lcm = 4, gcd = 16, multiple = 4, result = 1
    • multiple += lcm | 4 + 4 = 8
    • gcd % multiple == 0 | 16 % 8 == 0 becomes true
      • result = 2

  • lcm = 4, gcd = 16, multiple = 8, result = 2
    • multiple += lcm | 8 + 4 =12
    • gcd % multiple == 0 | 16 % 12 == 0 becomes false

  • lcm = 4, gcd = 16, multiple = 4, result = 1
    • multiple += lcm | 12 + 4 = 16
    • gcd % multiple == 0 | 16 % 16 == 0 becomes true
      • result = 3

  • result = 3 

 

See other Hackerrank problem and its solution in Java :

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