0
0
DSA Pythonprogramming~10 mins

Sliding Window on Arrays in DSA Python - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to calculate the sum of the first window of size k in the array.

DSA Python
def initial_window_sum(arr, k):
    window_sum = sum(arr[[1]:k])
    return window_sum
Drag options to blanks, or click blank then click option'
A0
B-1
Ck
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Starting the slice at 1 instead of 0, which misses the first element.
Using k as the start index, which results in an empty slice.
2fill in blank
medium

Complete the code to slide the window by one position and update the sum.

DSA Python
def slide_window_sum(arr, window_sum, start, k):
    window_sum = window_sum - arr[start] + arr[start + [1]]
    return window_sum
Drag options to blanks, or click blank then click option'
A1
Bk - 1
Cstart
Dk
Attempts:
3 left
💡 Hint
Common Mistakes
Using start + 1 instead of start + k, which adds the wrong element.
Using k - 1 which is off by one for the new element index.
3fill in blank
hard

Fix the error in the code to correctly find the maximum sum of any window of size k.

DSA Python
def max_window_sum(arr, k):
    max_sum = sum(arr[0:k])
    window_sum = max_sum
    for i in range(1, len(arr) - k + 1):
        window_sum = window_sum - arr[i - 1] + arr[i + [1]]
        if window_sum > max_sum:
            max_sum = window_sum
    return max_sum
Drag options to blanks, or click blank then click option'
Ak
Bk - 1
C1
Di
Attempts:
3 left
💡 Hint
Common Mistakes
Using i + k which goes out of range.
Using i which is the start index, not the new element index.
4fill in blank
hard

Fill both blanks to create a dictionary of window sums keyed by the window's start index.

DSA Python
def window_sums_dict(arr, k):
    sums = {}
    current_sum = sum(arr[0:k])
    sums[0] = current_sum
    for i in range(1, len(arr) - k + 1):
        current_sum = current_sum - arr[i - [1]] + arr[i + [2]]
        sums[i] = current_sum
    return sums
Drag options to blanks, or click blank then click option'
A1
Bk
Ck - 1
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using k instead of 1 for the leaving element index.
Using k instead of k - 1 for the entering element index.
5fill in blank
hard

Fill all three blanks to create a list of averages of each sliding window of size k.

DSA Python
def sliding_window_averages(arr, k):
    averages = []
    window_sum = sum(arr[0:k])
    averages.append(window_sum / [1])
    for i in range(1, len(arr) - k + 1):
        window_sum = window_sum - arr[i - [2]] + arr[i + [3]]
        averages.append(window_sum / k)
    return averages
Drag options to blanks, or click blank then click option'
Ak
B1
Ck - 1
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Dividing by 1 instead of k for the average.
Using wrong indices for elements leaving or entering the window.