Skip to content

A set of Jupyter notebooks meant to keep as notes for my own use.

Notifications You must be signed in to change notification settings

shahwar9/algorithms-diaries

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

A set of Jupyter notebooks meant to keep as notes for my own use.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages