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

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

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...