Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given a 0-indexed integer array nums. A subarray of nums is called continuous if:
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.
Example 1:
Input: nums = [5,4,2,4] Output: 8 Explanation: Continuous subarray of size 1: [5], [4], [2], [4]. Continuous subarray of size 2: [5,4], [4,2], [2,4]. Continuous subarray of size 3: [4,2,4]. There are no subarrys of size 4. Total continuous subarrays = 4 + 3 + 1 = 8. It can be shown that there are no more continuous subarrays.
Example 2:
Input: nums = [1,2,3] Output: 6 Explanation: Continuous subarray of size 1: [1], [2], [3]. Continuous subarray of size 2: [1,2], [2,3]. Continuous subarray of size 3: [1,2,3]. Total continuous subarrays = 3 + 2 + 1 = 6.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 109Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Sliding Window · Segment Tree · Monotonic Queue
[5,4,2,4]
[1,2,3]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2762: Continuous Subarrays
class Solution {
public long continuousSubarrays(int[] nums) {
long ans = 0;
int i = 0, n = nums.length;
TreeMap<Integer, Integer> tm = new TreeMap<>();
for (int j = 0; j < n; ++j) {
tm.merge(nums[j], 1, Integer::sum);
while (tm.lastEntry().getKey() - tm.firstEntry().getKey() > 2) {
tm.merge(nums[i], -1, Integer::sum);
if (tm.get(nums[i]) == 0) {
tm.remove(nums[i]);
}
++i;
}
ans += j - i + 1;
}
return ans;
}
}
// Accepted solution for LeetCode #2762: Continuous Subarrays
func continuousSubarrays(nums []int) (ans int64) {
i := 0
tm := treemap.NewWithIntComparator()
for j, x := range nums {
if v, ok := tm.Get(x); ok {
tm.Put(x, v.(int)+1)
} else {
tm.Put(x, 1)
}
for {
a, _ := tm.Min()
b, _ := tm.Max()
if b.(int)-a.(int) > 2 {
if v, _ := tm.Get(nums[i]); v.(int) == 1 {
tm.Remove(nums[i])
} else {
tm.Put(nums[i], v.(int)-1)
}
i++
} else {
break
}
}
ans += int64(j - i + 1)
}
return
}
# Accepted solution for LeetCode #2762: Continuous Subarrays
class Solution:
def continuousSubarrays(self, nums: List[int]) -> int:
ans = i = 0
sl = SortedList()
for x in nums:
sl.add(x)
while sl[-1] - sl[0] > 2:
sl.remove(nums[i])
i += 1
ans += len(sl)
return ans
// Accepted solution for LeetCode #2762: Continuous Subarrays
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #2762: Continuous Subarrays
// class Solution {
// public long continuousSubarrays(int[] nums) {
// long ans = 0;
// int i = 0, n = nums.length;
// TreeMap<Integer, Integer> tm = new TreeMap<>();
// for (int j = 0; j < n; ++j) {
// tm.merge(nums[j], 1, Integer::sum);
// while (tm.lastEntry().getKey() - tm.firstEntry().getKey() > 2) {
// tm.merge(nums[i], -1, Integer::sum);
// if (tm.get(nums[i]) == 0) {
// tm.remove(nums[i]);
// }
// ++i;
// }
// ans += j - i + 1;
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #2762: Continuous Subarrays
function continuousSubarrays(nums: number[]): number {
const [minQ, maxQ]: [number[], number[]] = [[], []];
const n = nums.length;
let res = 0;
for (let r = 0, l = 0; r < n; r++) {
const x = nums[r];
while (minQ.length && nums[minQ.at(-1)!] > x) minQ.pop();
while (maxQ.length && nums[maxQ.at(-1)!] < x) maxQ.pop();
minQ.push(r);
maxQ.push(r);
while (minQ.length && maxQ.length && nums[maxQ[0]] - nums[minQ[0]] > 2) {
if (maxQ[0] < minQ[0]) {
l = maxQ[0] + 1;
maxQ.shift();
} else {
l = minQ[0] + 1;
minQ.shift();
}
}
res += r - l + 1;
}
return res;
}
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.