Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Sliding Window Algorithm with REST API
📖 Scenario: You are building a simple REST API that processes a list of numbers sent by users. The API will find the maximum sum of any continuous sub-list of a fixed size using the sliding window algorithm. This technique helps efficiently analyze data streams or time series.
🎯 Goal: Create a REST API endpoint that accepts a list of integers and a window size, then returns the maximum sum of any continuous sub-list of that size using the sliding window algorithm.
📋 What You'll Learn
Use Python with FastAPI to create the REST API
Accept JSON input with a list of integers called numbers and an integer window_size
Implement the sliding window algorithm to find the maximum sum of any continuous sub-list of length window_size
Return the maximum sum as JSON response
💡 Why This Matters
🌍 Real World
Sliding window algorithms are used in real-time data processing, such as analyzing sensor data, financial time series, or network traffic to find patterns or anomalies efficiently.
💼 Career
Understanding how to implement efficient algorithms and expose them via REST APIs is valuable for backend developers, data engineers, and software engineers working with data streams or microservices.
Progress0 / 4 steps
1
Set up the FastAPI app and input data model
Write code to import FastAPI and Pydantic's BaseModel. Create a FastAPI app called app. Define a Pydantic model called NumbersInput with two fields: numbers as a list of integers and window_size as an integer.
Rest API
Hint
Remember to import FastAPI and BaseModel first. Then create the app and the input data model with the exact field names.
2
Create the API endpoint and receive input
Add a POST endpoint /max_sum_window to the app that accepts a JSON body of type NumbersInput. Inside the function, assign the input list to numbers and the window size to k.
Rest API
Hint
Define the POST route and extract the input values into variables named exactly numbers and k.
3
Implement the sliding window algorithm to find max sum
Inside the max_sum_window function, write code to calculate the maximum sum of any continuous sub-list of length k using the sliding window algorithm. Use variables window_sum for the current window sum and max_sum for the maximum sum found. Iterate over the list with a for loop using i as the index.
Rest API
Hint
Start by summing the first k numbers. Then slide the window by adding the new number and subtracting the old one. Update max_sum if the current window sum is bigger.
4
Return the maximum sum as JSON response
At the end of the max_sum_window function, return a dictionary with the key max_sum and the value as the calculated maximum sum.
Rest API
Hint
Return a dictionary with the key max_sum and the value as the maximum sum found.
Practice
(1/5)
1. What is the main advantage of using the sliding window algorithm in processing data streams?
easy
A. It processes data in fixed-size chunks efficiently by reusing previous computations.
B. It sorts the entire data before processing.
C. It stores all data in memory for faster access.
D. It processes data randomly without any order.
Solution
Step 1: Understand the sliding window concept
The sliding window algorithm processes data in fixed-size chunks, moving forward by removing the oldest data and adding new data.
Step 2: Identify the main advantage
This approach avoids recalculating over the entire data repeatedly, saving time and memory.
Final Answer:
It processes data in fixed-size chunks efficiently by reusing previous computations. -> Option A
Quick Check:
Sliding window = efficient chunk processing [OK]
Hint: Remember: sliding window reuses old results to save time [OK]
Common Mistakes:
Thinking it sorts data first
Assuming it stores all data in memory
Believing it processes data randomly
2. Which of the following is the correct way to initialize a sliding window of size 3 over a list named data in Python?
easy
A. window = data[3]
B. window = data[0:3]
C. window = data(0,3)
D. window = data[:]
Solution
Step 1: Recall Python list slicing syntax
To get the first 3 elements, use data[0:3], which includes indices 0, 1, and 2.
Step 2: Check other options
data(0,3) is invalid syntax, data[3] gets only one element at index 3, data[:] gets the whole list.
Final Answer:
window = data[0:3] -> Option B
Quick Check:
Slice first 3 elements = data[0:3] [OK]
Hint: Use data[start:end] to slice lists in Python [OK]
Common Mistakes:
Using parentheses instead of brackets
Selecting a single element instead of a slice
Taking the whole list instead of a window
3. Given the Python code below, what will be the output?
data = [1, 3, 5, 7, 9]
window_size = 3
result = []
for i in range(len(data) - window_size + 1):
window_sum = sum(data[i:i+window_size])
result.append(window_sum)
print(result)
medium
A. [1, 3, 5]
B. [15, 21, 27]
C. [3, 5, 7]
D. [9, 15, 21]
Solution
Step 1: Understand the loop range and slicing
The loop runs from i=0 to i=2 (5 - 3 + 1 = 3 iterations). Each slice is data[i:i+3].
Hint: Sum slices of size window_size in a loop [OK]
Common Mistakes:
Incorrect loop range causing index errors
Summing wrong slices
Confusing window size with list length
4. The following code tries to implement a sliding window sum but has a bug. What is the error?
data = [2, 4, 6, 8]
window_size = 2
result = []
for i in range(len(data) - window_size):
window_sum = sum(data[i:i+window_size])
result.append(window_sum)
print(result)
medium
A. The result list is not initialized.
B. The sum function is used incorrectly.
C. The loop range misses the last window, causing incomplete results.
D. Window size is larger than data length.
Solution
Step 1: Analyze the loop range
The loop runs from 0 to len(data) - window_size - 1, which is 4 - 2 - 1 = 1, so only indices 0 and 1.
Step 2: Identify missing last window
The last valid window starts at index 2 (data[2:4]), but the loop excludes it because it should run to len(data) - window_size + 1.
Final Answer:
The loop range misses the last window, causing incomplete results. -> Option C
Quick Check:
Loop range must cover all windows [OK]
Hint: Use range(len(data) - window_size + 1) for full coverage [OK]
Common Mistakes:
Using wrong loop range causing missed windows
Misusing sum function
Not initializing result list
5. You want to find the maximum sum of any sliding window of size 4 in a large list data. Which approach is most efficient?
hard
A. Use a sliding window by adding the new element and subtracting the oldest element from the previous sum.
B. Calculate sum of each window from scratch using sum(data[i:i+4]) in a loop.
C. Sort the entire list and pick the top 4 elements to sum.
D. Use recursion to calculate sums of all windows.
Solution
Step 1: Understand the problem of efficiency
Calculating sum from scratch for each window is slow for large data because it repeats work.
Step 2: Apply sliding window optimization
By keeping the previous window sum, add the new element and subtract the oldest element to get the next sum quickly.
Step 3: Evaluate other options
Sorting does not help find consecutive window sums; recursion adds overhead and is inefficient here.
Final Answer:
Use a sliding window by adding the new element and subtracting the oldest element from the previous sum. -> Option A
Quick Check:
Sliding window sum update = add new - remove old [OK]
Hint: Update sums by adding new and removing old element [OK]