Using sliding window technique to solve coding interview questions.
Published in
4 min readApr 1, 2020
This blog is a part of my “15 days cheat sheet for hacking technical interviews at big tech companies”. In this blog, we discuss how sliding window technique can help to simplify the code and reduce the time complexity.
Sample Question 1
Let’s start with the following interview question:
Given an array of integers and a number k.
Return the highest sum of any k consecutive elements in the array.Examples:Input: arr = [1, 5, 2, 3, 7, 1], k = 3
Output: 12 (the sum of subarray [2, 3, 7])Input: arr = [5, -3, 7, -6, 8], k = 2
Output: 4 (the sum of subarray [-3, 7])Input: arr = [5, -3, 7, -6, 8], k = 3
Output: 9 (the sum of subarray [5, -3, 7] or [7, -6, 8])
Brute Force Approach
The most intuitive way is to find all possible consecutive subarray of k
elements, sum up and compare them. This method requires nested for loop, the outer for loop iterates through the starting index of the subarray and the nested loop calculates the sum of the subarray.