Sitemap
Rohit K.

Rohit K.

Analyst

SubArray Division Hackerrank Solution In Python3.0

2 min readNov 22, 2022

--

This problem is from hackerrank and the questions involved some new concepts which are new to us.

Hello folks here we are again with a new hackerrank question which is also asked in the mountblue interview, this problem involves the concept of sliding window. and as per the tradition we will going to understand the problem first and then we will see the bruteforce approach and then we will be going to the main optimized solution that is sliding window problem.

Problem Statement:

S = [2,2,1,3,2]

d = 4

m = 2

Lily wants to find segments summing to Ron’s birth day,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

Get Rohit K.’s stories in your inbox

Join Medium for free to get updates from this writer.

The first line contains an integer , the number of squares in the chocolate bar.
The second line contains space-separated integers , the numbers on the chocolate squares where .
The third line contains two space-separated integers, and , Ron’s birth day and his birth month.

Sample Input 0

5
1 2 1 3 2
3 2
2

sample Input 1

5
1 2 1 3 2
3 2

output

2

according to question it says lilywants to share continuos segment of the array whose length comes out to be the bday month and the sum of the number on the square is equal to the bday date

s= {2,2,1,3,2}

d=4 rons bday date

m = 2 in how many ways can we make 4 {2,2} and {1,3}

Approach:

The Bruteforce approach should be using two pointers i and j namely i for iterating over the array and summing the number and j for counter to counting the number of ways it adds up to 4

Approach 2:

Using Sliding Window Technique

def birthday(s,d,m):
count = 0
totsl = sum(s[:m]) //sum of first m element

if total = = d :
count += 1


// sliding window

for i in range(len(s)):
total += s[i]//for each itr we need to add element to total\
total -= s[i-m] // we need to negate the element which are out of the sliding window
if total == d :
count += 1
return count


Follow for more hackerrank answers and many amazing content

--

--