Skip to content
  • Home
  • Contact Us
  • About Us
  • Privacy Policy
  • DMCA
  • Linkedin
  • Pinterest
  • Facebook
thecscience

TheCScience

TheCScience is a blog that publishes daily tutorials and guides on engineering subjects and everything that related to computer science and technology

  • Home
  • Human values
  • Microprocessor
  • Digital communication
  • Linux
  • outsystems guide
  • Toggle search form
HackerRank Subarray Division Problem Solution

HackerRank Subarray Division Problem Solution

Posted on April 11, 2023April 12, 2023 By Yashwant Parihar No Comments on HackerRank Subarray Division Problem Solution

In this post, We are going to solve HackerRank Subarray Division Problem.

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

Determine how many ways she can divide the chocolate.

Example

s = [2, 2. 1. 3. 2]

d = 4

m = 2

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

Function Description

Complete the birthday function in the editor below.

birthday has the following parameter(s):

  • int s[n]: the numbers on each of the squares of chocolate
  • int d: Ron’s birth day
  • int m: Ron’s birth month

Returns

  • int: the number of ways the bar can be divided

Input Format

The first line contains an integer n, the number of squares in the chocolate bar.
The second line contains n space-separated integers s[I], the numbers on the chocolate squares where 0 < I < n.
The third line contains two space-separated integers, d and m, Ron’s birthday and his birth month.

Sample Input 0

5
1 2 1 3 2
3 2

Sample Output 0

2

Explanation 0

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

Sample Input 1

6
1 1 1 1 1 1
3 2

Sample Output 1

0

Explanation 1

Lily only wants to give Ron m = 2 consecutive squares of chocolate whose integers sum to d = 3. There are no possible pieces satisfying these constraints:

Thus, we print 0 as our answer.

Sample Input 2

1
4
4 1

Sample Output 2

1

Explanation 2

Lily only wants to give Ron m = 1 square of chocolate with an integer value of d = 4. Because the only square of chocolate in the bar satisfies this constraint, we print 1 as our answer.

HackerRank Subarray Division Problem Solution
HackerRank Subarray Division Problem Solution

Table of Contents

  • Subarray Division C Solution
  • Subarray Division C++ Solution
  • Subarray Division C Sharp Solution
  • Subarray Division Java Solution
  • Subarray Division JavaScript Solution
  • Subarray Division Python Solution

Subarray Division C Solution

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int n; 
    scanf("%d",&n);
    int *squares = malloc(sizeof(int) * n);
    for(int squares_i = 0; squares_i < n; squares_i++){
       scanf("%d",&squares[squares_i]);
    }
    int d; 
    int m; 
    scanf("%d %d",&d,&m);
    int i,cont,sum,j;
    for(i=0;i<n;i++){
        sum=0;
        for(j=0;j<m;j++){
            if((i+j)<n){
                sum = sum +squares[i+j];
            }
            else{
                break;
            }
        }
        if(sum == d){
            cont++;
        }
    }
    printf("%d\n",cont);
    
    
    return 0;
}

Subarray Division C++ Solution

//Birthday Chocolate
#include <iostream>
#include <vector>
using namespace std;
int n,a[105],resenje,m,d;
vector <int> v;
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
        cin>>a[i];
    cin>>d>>m;
    for(int i=1;i<=n;i++)
    {
        if(i+m>n+1)
            break;
        int sum=0;
        for(int j=i;j<i+m;j++)
            sum+=a[j];
          //  cout<<sum<<"\n";
        if(sum==d)
            resenje++;
    }
    cout<<resenje;
    return 0;
}

Subarray Division C Sharp Solution

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

    static void Main(String[] args) {
        int n = Convert.ToInt32(Console.ReadLine());
        string[] squares_temp = Console.ReadLine().Split(' ');
        int[] squares = Array.ConvertAll(squares_temp,Int32.Parse);
        string[] tokens_d = Console.ReadLine().Split(' ');
        int d = Convert.ToInt32(tokens_d[0]);
        int m = Convert.ToInt32(tokens_d[1]);
        // your code goes here
        
        if(!CheckInput(n, squares, d, m))
        {
            Console.WriteLine("Invalid input.");
        }
        
        Console.WriteLine(CalculateCombinations(n, squares, d, m));
    }
    
    static int CalculateCombinations(int n, int[] squares, int d, int m)
    {
        int result = 0;
        for(int startIndex = 0; (startIndex + m) <= n; startIndex++)
        {
            if(squares.Skip(startIndex).Take(m).ToArray().Sum() == d)
            {
                result++;
            }
        }
        return result;        
    }
    
    static bool CheckInput(int n, int[] squares, int d, int m)
    {
        if(n < 1 || n > 100)
        {
            return false;
        }    
        
        foreach(int square in squares)
        {
            if(square < 1 || square > 5)
            {
                return false;
            }
        }
        
        if(d < 1 || d > 31)
        {
            return false;
        }
        
        if(m < 1 || m > 12)
        {
            return false;            
        }
        
        return true;
        
    }
}

Subarray Division Java Solution

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 {

    /*
     * Complete the 'birthday' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts following parameters:
     *  1. INTEGER_ARRAY s
     *  2. INTEGER d
     *  3. INTEGER m
     */

  public static int birthday(List<Integer> s, int d, int m) {
    int ways = 0;
    for (int i = 0; i + m - 1 < s.size(); i++) {
      List<Integer> list = s.subList(i, i + m);
      if (list.stream().reduce(0, Integer::sum) == d) {
        ways++;
      }
    }
    return ways;
  }

}

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();
    }
}

Subarray Division JavaScript Solution

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function getWays(squares, d, m){
    // Complete this function
    var count = 0;
    var index = 0;
    while (index <= squares.length - m) {
        var sum = squares[index];
        for (var i = 1; i < m; i  ++) {
            sum += squares[index + i];
        }
        if (sum === d) {
            count ++;
        }
        index ++;
    }
    return count;
}

function main() {
    var n = parseInt(readLine());
    s = readLine().split(' ');
    s = s.map(Number);
    var d_temp = readLine().split(' ');
    var d = parseInt(d_temp[0]);
    var m = parseInt(d_temp[1]);
    var result = getWays(s, d, m);
    console.log(result);

}

Subarray Division Python Solution

#!/bin/python3

import sys


n = int(input().strip())
squares = list(map(int, input().strip().split(' ')))
d,m = input().strip().split(' ')
d,m = [int(d),int(m)]
# your code goes here

shared = 0

for i in range(n):
    if sum(squares[i:i+m]) == d:
        shared += 1

print(shared)

Other Solutions

  • HackerRank Divisible Sum Pairs Problem Solution
  • HackerRank Migratory Birds Problem Solution
c, C#, C++, HackerRank Solutions, java, javascript, python Tags:C, cpp, CSharp, Hackerrank Solutions, java, javascript, python

Post navigation

Previous Post: HackerRank Breaking the Records Solution
Next Post: HackerRank Divisible Sum Pairs Problem Solution

Related Posts

HackerRank Bear and Steady Gene Problem Solution HackerRank Bear and Steady Gene Solution c
HackerRank Service Lane Problem Solution HackerRank Service Lane Problem Solution c
HackerRank Jumping on the Clouds Problem Solution HackerRank Jumping on the Clouds Solution c
HackerRank Gridland Provinces Problem Solution HackerRank Gridland Provinces Problem Solution c
HackerRank Find Strings Problem Solution HackerRank Find Strings Problem Solution c
HackerRank Between Two Sets Problem Solution HackerRank Between Two Sets Problem Solution c

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Pick Your Subject
Human Values

Copyright © 2023 TheCScience.

Powered by PressBook Grid Blogs theme