Skip to main content
Back to problems
#480
Hard Algorithms

Sliding window median

Array Hash Table Sliding Window Heap (Priority Queue)
38.9% acceptance
Jan 13, 2026
3565
237
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. For examples, if arr = [2,3,4], the median is 3. For examples, if arr = [1,2,3,4], the median is (2 + 3) / 2 = 2.5. You are given an integer array nums and an integer k. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the median array for each window in the original array. Answers within 10-5 of the actual value will be accepted.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn median_sliding_window(nums: Vec<i32>, k: i32) -> Vec<f64> {
    let k = k as usize;
    let mut result = Vec::with_capacity(nums.len() - k + 1);
    let mut window: Vec<i32> = Vec::with_capacity(k);
    
    // Initialize first window
    for i in 0..k {
      window.push(nums[i]);
    }
    window.sort_unstable();
    result.push(Self::get_median_from_sorted(&window, k));
    
    // Slide the window
    for i in k..nums.len() {
      let to_remove = nums[i - k];
      let to_add = nums[i];
      
      // Remove element using binary search
      if let Ok(pos) = window.binary_search(&to_remove) {
        window.remove(pos);
      }
      
      // Insert element using binary search
      match window.binary_search(&to_add) {
        Ok(pos) => window.insert(pos, to_add),
        Err(pos) => window.insert(pos, to_add),
      }
      
      result.push(Self::get_median_from_sorted(&window, k));
    }
    
    result
  }
  
  fn get_median_from_sorted(window: &[i32], k: usize) -> f64 {
    if k % 2 == 1 {
      window[k / 2] as f64
    } else {
      (window[k / 2 - 1] as f64 + window[k / 2] as f64) / 2.0
    }
  }
}