Skip to main content
Back to problems
#2762
Medium Algorithms

Continuous subarrays

Array Queue Sliding Window Heap (Priority Queue) Ordered Set Monotonic Queue
57.9% acceptance
Feb 25, 2026
1496
97
You are given a 0-indexed integer array nums. A subarray of nums is called continuous if: Let i, i + 1, ..., j be the indices in the subarray. Then, for each pair of indices i <= i1, i2 <= j, 0 <= |nums[i1] - nums[i2]| <= 2. Return the total number of continuous subarrays. A subarray is a contiguous non-empty sequence of elements within an array.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn continuous_subarrays(nums: Vec<i32>) -> i64 {
    use std::collections::BTreeMap;
    let n = nums.len();
    let mut ans: i64 = 0;
    let mut left = 0usize;
    let mut freq: BTreeMap<i32, i32> = BTreeMap::new();
    for right in 0..n {
      *freq.entry(nums[right]).or_insert(0) += 1;
      while freq.keys().last().unwrap() - freq.keys().next().unwrap() > 2 {
        let e = freq.get_mut(&nums[left]).unwrap();
        *e -= 1;
        if *e == 0 { freq.remove(&nums[left]); }
        left += 1;
      }
      ans += (right - left + 1) as i64;
    }
    ans
  }
}