Skip to content

Latest commit

 

History

History
28 lines (19 loc) · 929 Bytes

README.md

File metadata and controls

28 lines (19 loc) · 929 Bytes

Grokking Coding Interview Patterns

1. Sliding Window

A typical problem is given an array of N elements. Calculate average of elements of subarray of size K.

Brute force algorithms takes O(N*K) to solve this.

def find_averages_of_subarrays(K, arr):
  result = []
  windowSum, windowStart = 0.0, 0
  for windowEnd in range(len(arr)):
    windowSum += arr[windowEnd]  # add the next element
    # slide the window, we don't need to slide if we've not hit the required window size of 'k'
    if windowEnd >= K - 1:
      result.append(windowSum / K)  # calculate the average
      windowSum -= arr[windowStart]  # subtract the element going out
      windowStart += 1  # slide the window ahead

  return result


def main():
  result = find_averages_of_subarrays(5, [1, 3, 2, 6, -1, 4, 1, 8, 2])
  print("Averages of subarrays of size K: " + str(result))


main()