Python 0480.py
class Solution:
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
# Python's list can be surprisingly efficient at times ...
mid = k // 2 # middle of sliding window (position of median)
right = k - 1
have = sorted(nums[ : right]) # initial window (without k-th value)
while right < len(nums):
insort(have, nums[right]) # add new value, keep list sorted
median = have[mid] # assume k is odd
if (k & 1) == 0: # but maybe it's even ...
median += have[mid - 1]
median /= 2
yield median # emit
# remove left-most value from the sorted list
right += 1
have.remove(nums[right - k]) # "slide out" value
Difficulty
and has an acceptance rate of about 39% (500k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- Heap (Priority Queue)
- Sliding Window
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation provides a generator-based solution for the sliding-window median problem. It receives an integer array nums and a window size k, then yields the median of each contiguous sub-array of length k. The core idea is to keep the current window in a sorted list, update it incrementally as the window slides, and compute the median directly from the sorted order. By using a generator (yield) the function streams results without allocating an auxiliary list for all medians, which reduces memory pressure when the input is large.
Initialization
The first phase prepares the data structures required for the sliding process.
mid = k // 2 # index of the median element
right = k - 1 # index of the last element that will be inserted first
have = sorted(nums[:right]) # sorted view of the first (k-1) elements
mid is computed once because the median position does not change while the window slides. right points to the element that will be added to complete the first full window. The list have holds the elements of the current window in sorted order, but deliberately excludes the element at right so that the first insertion can be performed uniformly with the subsequent steps.
Inserting the New Element
Each iteration begins by inserting the element that enters the window at position right. The standard library function insort inserts while preserving order, which avoids a full resort after every slide.
insort(have, nums[right]) # add new value, keep list sorted
Because have remains sorted, the median can be accessed by index without additional work.
Computing the Median
The median extraction distinguishes between odd and even window sizes. For an odd k, the median is the element at index mid. For an even k, the median is the average of the two central elements.
median = have[mid] # assume k is odd
if (k & 1) == 0: # even length window
median += have[mid - 1]
median /= 2
The bitwise test (k & 1) == 0 is a fast way to detect evenness, avoiding a modulo operation. The code directly updates the median variable, which is then emitted.
yield median # emit the current median
Because the function is a generator, each median is produced on demand, allowing the caller to iterate lazily.
Sliding the Window
After yielding the median, the window is advanced by one position. The index right is incremented, and the element that falls out of the window (the leftmost element) is removed from the sorted list.
right += 1
have.remove(nums[right - k]) # "slide out" value
right - k computes the index of the element that is now outside the window. The remove operation deletes the first occurrence of that value, which is safe because the list contains exactly one copy of each element from the current window. By performing removal after the insertion and median calculation, the code guarantees that the list always represents the exact contents of the window for the next iteration.
Edge-Case Handling
The algorithm gracefully handles several boundary conditions without extra branching.
When k equals 1, mid becomes 0, right is 0, and have is initialized as an empty list. The first insort inserts the sole element, the median is taken directly from have[0], and the subsequent removal deletes the same element, leaving have empty again. This cycle repeats for each element, correctly yielding each value as its own median.
When k equals the length of nums, the loop runs exactly once. The initial have contains all but the last element, the final insertion completes the full array, the median is computed, and the removal step attempts to delete the element at index right - k, which is -1. In Python, negative indices wrap around, so nums[-1] refers to the last element, which is precisely the element that just entered the window. The removal therefore restores have to its original state, and the loop terminates because right reaches len(nums).
For even values of k, the median calculation uses the average of the two central elements. The code adds the lower middle element (have[mid - 1]) to the upper middle (have[mid]) and then divides by 2, yielding a floating-point result even when both elements are integers. This matches the expected definition of median for even-sized windows.
If the input array contains duplicate values, the sorted list have may hold several identical entries. The remove call deletes only the first matching element, which corresponds to the leftmost occurrence in the window because the list reflects the order of insertion through sorting. Consequently, duplicates are handled correctly without ambiguity.
Performance Optimizations
The solution leverages several techniques to keep the runtime efficient.
Using a sorted list with insort provides logarithmic insertion time, avoiding the linear cost of re-sorting the entire window after each slide. The complementary remove operation also runs in linear time in the worst case, but because the list size is bounded by k, the overall per-step cost remains proportional to k.
Pre-computing the median index (mid) eliminates repeated division inside the loop. The bitwise even-check (k & 1) == 0 is faster than a modulo operation, reducing the overhead of the conditional branch that distinguishes odd and even windows.
The generator pattern (yield) prevents the allocation of a full result list. Consumers can process medians on the fly, which is especially beneficial when the number of windows (len(nums) - k + 1) is large.
By limiting the sorted container to exactly k elements, the algorithm ensures that memory usage stays constant with respect to the input size, scaling only with the window size. This bounded memory footprint, combined with the incremental update strategy, yields a solution that is both time-efficient for typical values of k and memory-conservative for long input streams.
ELI5 - Simplified Explanation
Imagine a toy box that holds a line of numbers. The code uses a special sliding window that acts like a frame moving across the numbers one by one to peek at a small group at a time. The box keeps these numbers in a tidy row from smallest to biggest so that finding the one in the middle is easy.
When the frame moves, a new number enters from the right side and joins the line, keeping everything in order. If the frame is the perfect size to have one exact number in the center, the program picks that one out. If the frame is shaped so that the center falls between two numbers, the program takes both of those numbers, adds them together, and cuts the total in half to find the value right in the middle. Once the middle is found, the number that was at the very start of the frame gets taken away to make room for new ones as the window slides forward. This continues until every group of numbers has been checked.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | ||||||||
| leetcode.ca | C++ | Java | Go | Python | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| linouk23 | C++ | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| sonugiri1043 | C++ | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++ | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| linouk23 | C++ | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| sonugiri1043 | C++ | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 295: Find Median from Data Stream
- problem 3107: Minimum Operations to Make Median of Array Equal to K
Solved On The Same Day
- problem 2453: Destroy Sequential Targets
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality