#3748

Count Stable Subarrays

Hard
ArrayBinary SearchPrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Identify maximal non-decreasing segments in the array. Each segment contributes stable subarrays based on its length.

⚙️

Algorithm

3 steps
  1. 1Step 1: Traverse the array to identify lengths of maximal non-decreasing segments.
  2. 2Step 2: For each segment of length L, calculate stable subarrays as L * (L + 1) / 2.
  3. 3Step 3: Build a prefix sum array to quickly answer each query based on precomputed stable subarray counts.
solution.py14 lines
1def countStableSubarrays(nums, queries):
2    n = len(nums)
3    stable_counts = [0] * n
4    length = 1
5    for i in range(1, n):
6        if nums[i] >= nums[i - 1]: length += 1
7        else:
8            for j in range(length): stable_counts[i - j - 1] += length - j
9            length = 1
10    for j in range(length): stable_counts[n - j - 1] += length - j
11    prefix_sum = [0] * n
12    prefix_sum[0] = stable_counts[0]
13    for i in range(1, n): prefix_sum[i] = prefix_sum[i - 1] + stable_counts[i]
14    return [prefix_sum[r] - (prefix_sum[l - 1] if l > 0 else 0) for l, r in queries]

Complexity note: This complexity is achieved by processing the array in a single pass to identify segments and using a prefix sum for quick query responses.

  • 1Maximal non-decreasing segments help in counting stable subarrays efficiently.
  • 2Stable subarrays can be derived from segment lengths using combinatorial counting.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.