Member-only story

JavaScript Interview: Subarray Division Question using Sliding Window Approach

Marika Lam
1 min readJun 29, 2024

--

Prompt

Solution

function birthday(s, d, m) {
console.log(s);
let count = 0;

// Write your code here
for (let i=0; i<s.length; i++){
let sum = 0;
for (let j=0; j<m; j++){
sum = sum+s[i+j];
}
console.log("--", s[i],s[i+1], sum)
if (sum == d){
count++;
}
}
return count;
}

Explanation

I used the sliding window technique. It is a common algorithmic approach used for solving various problems that involve processing or analyzing a sequential data structure, such as arrays, strings or streams.

The time complexity of the sliding window technique is usually linear or close to linear O(n). N is the size of the input data structure. This is because you process each element once as the window slides through the data.

The space complexity is generally constant, O(1) because you’re maintaining a fixed size window and a few additional variables to perform calculations or store intermediate results. Space complexity refers to the total amount of memory space used by an algorithm/program, including the space of input values for execution. The amount of extra memory used doesn’t grow with the input size, it remains constant regardless of input size.

--

--

No responses yet