Skip to main content

Subarray Division HackerRank solution in Java with examples

Java solution for Subarray Division hackerRank Problem

Subarray Division java solution

Problem Description :

Two children, Lily and Ron, want to share a chocolate bar. Each of the squares has an integer on it.  

Lily decides to share a contiguous segment of the bar selected such that: 

  • The length of the segment matches Ron's birth month, and,
  • The sum of the integers on the squares is equal to his birth day.

Determine how many ways she can divide the chocolate.

Example 1 :

s = [2, 2, 3, 1, 2]
d = 4
m = 2

Output : 2

Lily wants to find segments summing to Ron's birth day, d = 4 with a length equaling his birth month, m = 2 In this case, there are two segments meeting her criteria: [2, 2] and [1, 3]

Example 2 :

Input :

s = [1, 2, 1, 3, 2]
d = 3
m = 2

Output : 2

Explanation :

Lily wants to give Ron m = 2 squares summing to d = 3. The following two segments meet the criteria:

1 + 2 = 3 and 2 + 1 = 3

Example 3 :

Input :

s = [4, 5, 4, 2, 4, 5, 2, 3, 2, 1, 1, 5, 4]
d = 15
m = 4

Output : 3

Explanation :

Lily wants to give Ron m = 4 squares summing to d = 15. The following three segments meet the criteria:

  1. 4 + 5 + 4 + 2 = 15 
  2. 5 + 4 + 2 + 4 = 15
  3. 4 + 2 + 4 + 5 = 15
So lets see solution :
 

Solution 1 : Using while loop

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 birthday (List<Integer> s, int d, int m) {
       
        int ans = 0;
        
        for (int i = 0; i < s.size(); i++) {
            int temp = 0;
            int sum = 0;
            int j = i;
           
            while (m != temp) {
                if (j < s.size()) {
                    sum = sum + s.get(j++);
                }
                temp++;
            }
            
            if (sum == d)
                ans++;
        }
        return ans;
    }

}

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")));

        int n = Integer.parseInt(bufferedReader.readLine().trim());

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

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

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

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

        int result = Result.birthday(s, d, m);

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

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

Solution explanation :

  • In above solution, we are traverse all value of given list. In for loop there is another while loop is used to get sum of all value that are between ith to m. e.g if current index = 0 and m = 2 then we are getting sum of 0th and 1st index of list.
  • After for loop, check if sum value and d value is matched or not. if value matched then increment ans.
  • return ans.
Output explanation :

s = [2, 2, 3, 1, 2], d = 4, m = 2

  • i = 0, j = 0, ans = 0, temp = 0, sum = 0
  • m != temp | 2 != 0 becomes true
    • j < s.size() | 0 < 5 becomes true
      • sum = sum + s.get(j++); | sum = 0 + 2 | sum = 2
    • temp = 1 
  • 2 != 1 becomes true
    • 1 < 5 becomes true
      • sum = 4
    • temp = 2 
  • 2 != 2 becomes false
  • sum == d | 4 == 4 becomes true
    • ans = 1

  • i = 1, j = 1, ans = 1, temp = 0, sum = 0
  • 2 != 0 becomes true
    • 1 < 5 becomes true
      • sum = 2 
    • temp = 1
  • 2 != 1 becomes true
    • 2 < 5 becomes true
      • sum = 5
    • temp = 2
  • 2 != 2 becomes false

  • i = 2, j = 2, ans = 1, temp = 0, sum = 0
  • 2 != 0 becomes true
    • 2 < 5 becomes true
      • sum = 3
    • temp = 1
  • 2 != 1 becomes true
    • 3 < 5 becomes true
      • sum = 4
    • temp = 2
  • 2 != 2 becomes false 
  • sum == d | 4 == 4 becomes true
    • ans = 2

  • i = 3, j = 3, ans = 2, temp = 0, sum = 0
  • 2 != 0 becomes true
    • 3 < 5 becomes true
      • sum = 1
    • temp = 1
  • 2 != 1 becomes true
    • 4 < 5 becomes true
      • sum = 3
    • temp = 2
  • 2 != 2 becomes false

  • i = 4, j = 4, ans = 2, temp = 0, sum = 0
  • 2 != 0 becomes true
    • 4 < 5 becomes true
      • sum = 2
    • temp = 1
  • 2 != 1 becomes true
    • 5 < 5 becomes false
    • temp = 2
  • 2 != 2 becomes false

  • Return 2

Solution 2 : Using for loop

public static int birthday(List<Integer> s, int d, int m) {
    int ans = 0;
    
    for (int i = 0; i <= s.size()-m; i++) {
        int sum=0;
        
        for (int j = i; j < m+i; j++) {
          sum += s.get(j);  
        }
        
        if (sum==d) {
            ans++;
        }
    }
    return ans;
}

Solution explanation :

  • This solution same as above but here we are using for loop instead of while loop.
  • First we traverse through list from 0th to list size - m.
  • In second for loop we are iterating from current ith index to till given m value. and incrementing sum value.
  • If sum and d value matched then increment ans and last return ans.

Solution 3 : Using Java 8 Stream API

public static int birthday(List<Integer> s, int d, int m) {
    int ans = 0;

    
    // Convert list of integer to array of int
    int[] array = s.stream().mapToInt(i -> i).toArray();
         
    for (int i = 0; i <= s.size()-m; i++){
        if (Arrays.stream(array, i, i+m).sum() == d) {
            ans++;
        }
    }
    return ans;
}

Solution explanation :

  • Convert list of integers to array of int | List<Integer> -> int[]
  • Traverse through 0th index to list size - m.
  • Here we are using Arrays.stream instead of for and while loop. if total sum is equals to d then increment ans.
  • Return ans.


Happy Coding...

Other HackerRank problem and Solution in Java :


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