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.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given an integer array nums.
A subarray of nums is called stable if it contains no inversions, i.e., there is no pair of indices i < j such that nums[i] > nums[j].
You are also given a 2D integer array queries of length q, where each queries[i] = [li, ri] represents a query. For each query [li, ri], compute the number of stable subarrays that lie entirely within the segment nums[li..ri].
Return an integer array ans of length q, where ans[i] is the answer to the ith query.
Note:
Example 1:
Input: nums = [3,1,2], queries = [[0,1],[1,2],[0,2]]
Output: [2,3,4]
Explanation:
queries[0] = [0, 1], the subarray is [nums[0], nums[1]] = [3, 1].
[3] and [1]. The total number of stable subarrays is 2.queries[1] = [1, 2], the subarray is [nums[1], nums[2]] = [1, 2].
[1], [2], and [1, 2]. The total number of stable subarrays is 3.queries[2] = [0, 2], the subarray is [nums[0], nums[1], nums[2]] = [3, 1, 2].
[3], [1], [2], and [1, 2]. The total number of stable subarrays is 4.Thus, ans = [2, 3, 4].
Example 2:
Input: nums = [2,2], queries = [[0,1],[0,0]]
Output: [3,1]
Explanation:
queries[0] = [0, 1], the subarray is [nums[0], nums[1]] = [2, 2].
[2], [2], and [2, 2]. The total number of stable subarrays is 3.queries[1] = [0, 0], the subarray is [nums[0]] = [2].
[2]. The total number of stable subarrays is 1.Thus, ans = [3, 1].
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 1051 <= queries.length <= 105queries[i] = [li, ri]0 <= li <= ri <= nums.length - 1Problem summary: You are given an integer array nums. A subarray of nums is called stable if it contains no inversions, i.e., there is no pair of indices i < j such that nums[i] > nums[j]. You are also given a 2D integer array queries of length q, where each queries[i] = [li, ri] represents a query. For each query [li, ri], compute the number of stable subarrays that lie entirely within the segment nums[li..ri]. Return an integer array ans of length q, where ans[i] is the answer to the ith query. Note: A single element subarray is considered stable.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search
[3,1,2] [[0,1],[1,2],[0,2]]
[2,2] [[0,1],[0,0]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3748: Count Stable Subarrays
class Solution {
public long[] countStableSubarrays(int[] nums, int[][] queries) {
List<Integer> seg = new ArrayList<>();
List<Long> s = new ArrayList<>();
s.add(0L);
int l = 0;
int n = nums.length;
for (int r = 0; r < n; r++) {
if (r == n - 1 || nums[r] > nums[r + 1]) {
seg.add(l);
int k = r - l + 1;
s.add(s.getLast() + (long) k * (k + 1) / 2);
l = r + 1;
}
}
long[] ans = new long[queries.length];
for (int q = 0; q < queries.length; q++) {
int left = queries[q][0];
int right = queries[q][1];
int i = upperBound(seg, left);
int j = upperBound(seg, right) - 1;
if (i > j) {
int k = right - left + 1;
ans[q] = (long) k * (k + 1) / 2;
} else {
int a = seg.get(i) - left;
int b = right - seg.get(j) + 1;
ans[q] = (long) a * (a + 1) / 2 + s.get(j) - s.get(i) + (long) b * (b + 1) / 2;
}
}
return ans;
}
private int upperBound(List<Integer> list, int target) {
int l = 0, r = list.size();
while (l < r) {
int mid = (l + r) >> 1;
if (list.get(mid) > target) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
}
// Accepted solution for LeetCode #3748: Count Stable Subarrays
func countStableSubarrays(nums []int, queries [][]int) []int64 {
n := len(nums)
seg := []int{}
s := []int64{0}
l := 0
for r := 0; r < n; r++ {
if r == n-1 || nums[r] > nums[r+1] {
seg = append(seg, l)
k := int64(r - l + 1)
s = append(s, s[len(s)-1]+k*(k+1)/2)
l = r + 1
}
}
ans := make([]int64, len(queries))
for idx, q := range queries {
left, right := q[0], q[1]
i := sort.SearchInts(seg, left+1)
j := sort.SearchInts(seg, right+1) - 1
if i > j {
k := int64(right - left + 1)
ans[idx] = k * (k + 1) / 2
} else {
a := int64(seg[i] - left)
b := int64(right - seg[j] + 1)
ans[idx] = a*(a+1)/2 + s[j] - s[i] + b*(b+1)/2
}
}
return ans
}
# Accepted solution for LeetCode #3748: Count Stable Subarrays
class Solution:
def countStableSubarrays(
self, nums: List[int], queries: List[List[int]]
) -> List[int]:
s = [0]
l, n = 0, len(nums)
seg = []
for r, x in enumerate(nums):
if r == n - 1 or x > nums[r + 1]:
seg.append(l)
k = r - l + 1
s.append(s[-1] + (1 + k) * k // 2)
l = r + 1
ans = []
for l, r in queries:
i = bisect_right(seg, l)
j = bisect_right(seg, r) - 1
if i > j:
k = r - l + 1
ans.append((1 + k) * k // 2)
else:
a = seg[i] - l
b = r - seg[j] + 1
ans.append((1 + a) * a // 2 + s[j] - s[i] + (1 + b) * b // 2)
return ans
// Accepted solution for LeetCode #3748: Count Stable 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 #3748: Count Stable Subarrays
// class Solution {
// public long[] countStableSubarrays(int[] nums, int[][] queries) {
// List<Integer> seg = new ArrayList<>();
// List<Long> s = new ArrayList<>();
// s.add(0L);
//
// int l = 0;
// int n = nums.length;
// for (int r = 0; r < n; r++) {
// if (r == n - 1 || nums[r] > nums[r + 1]) {
// seg.add(l);
// int k = r - l + 1;
// s.add(s.getLast() + (long) k * (k + 1) / 2);
// l = r + 1;
// }
// }
//
// long[] ans = new long[queries.length];
// for (int q = 0; q < queries.length; q++) {
// int left = queries[q][0];
// int right = queries[q][1];
//
// int i = upperBound(seg, left);
// int j = upperBound(seg, right) - 1;
//
// if (i > j) {
// int k = right - left + 1;
// ans[q] = (long) k * (k + 1) / 2;
// } else {
// int a = seg.get(i) - left;
// int b = right - seg.get(j) + 1;
// ans[q] = (long) a * (a + 1) / 2 + s.get(j) - s.get(i) + (long) b * (b + 1) / 2;
// }
// }
// return ans;
// }
//
// private int upperBound(List<Integer> list, int target) {
// int l = 0, r = list.size();
// while (l < r) {
// int mid = (l + r) >> 1;
// if (list.get(mid) > target) {
// r = mid;
// } else {
// l = mid + 1;
// }
// }
// return l;
// }
// }
// Accepted solution for LeetCode #3748: Count Stable Subarrays
function countStableSubarrays(nums: number[], queries: number[][]): number[] {
const n = nums.length;
const seg: number[] = [];
const s: number[] = [0];
let l = 0;
for (let r = 0; r < n; r++) {
if (r === n - 1 || nums[r] > nums[r + 1]) {
seg.push(l);
const k = r - l + 1;
s.push(s[s.length - 1] + (k * (k + 1)) / 2);
l = r + 1;
}
}
const ans: number[] = [];
for (const [left, right] of queries) {
const i = _.sortedIndex(seg, left + 1);
const j = _.sortedIndex(seg, right + 1) - 1;
if (i > j) {
const k = right - left + 1;
ans.push((k * (k + 1)) / 2);
} else {
const a = seg[i] - left;
const b = right - seg[j] + 1;
ans.push((a * (a + 1)) / 2 + s[j] - s[i] + (b * (b + 1)) / 2);
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
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: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.