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 array of positive integers nums.
Return the number of subarrays of nums, where the first and the last elements of the subarray are equal to the largest element in the subarray.
Example 1:
Input: nums = [1,4,3,3,2]
Output: 6
Explanation:
There are 6 subarrays which have the first and the last elements equal to the largest element of the subarray:
[1,4,3,3,2], with its largest element 1. The first element is 1 and the last element is also 1.[1,4,3,3,2], with its largest element 4. The first element is 4 and the last element is also 4.[1,4,3,3,2], with its largest element 3. The first element is 3 and the last element is also 3.[1,4,3,3,2], with its largest element 3. The first element is 3 and the last element is also 3.[1,4,3,3,2], with its largest element 2. The first element is 2 and the last element is also 2.[1,4,3,3,2], with its largest element 3. The first element is 3 and the last element is also 3.Hence, we return 6.
Example 2:
Input: nums = [3,3,3]
Output: 6
Explanation:
There are 6 subarrays which have the first and the last elements equal to the largest element of the subarray:
[3,3,3], with its largest element 3. The first element is 3 and the last element is also 3.[3,3,3], with its largest element 3. The first element is 3 and the last element is also 3.[3,3,3], with its largest element 3. The first element is 3 and the last element is also 3.[3,3,3], with its largest element 3. The first element is 3 and the last element is also 3.[3,3,3], with its largest element 3. The first element is 3 and the last element is also 3.[3,3,3], with its largest element 3. The first element is 3 and the last element is also 3.Hence, we return 6.
Example 3:
Input: nums = [1]
Output: 1
Explanation:
There is a single subarray of nums which is [1], with its largest element 1. The first element is 1 and the last element is also 1.
Hence, we return 1.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 109Problem summary: You are given an array of positive integers nums. Return the number of subarrays of nums, where the first and the last elements of the subarray are equal to the largest element in the subarray.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search · Stack
[1,4,3,3,2]
[3,3,3]
[1]
number-of-subarrays-with-bounded-maximum)count-subarrays-with-fixed-bounds)count-subarrays-where-max-element-appears-at-least-k-times)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3113: Find the Number of Subarrays Where Boundary Elements Are Maximum
class Solution {
public long numberOfSubarrays(int[] nums) {
Deque<int[]> stk = new ArrayDeque<>();
long ans = 0;
for (int x : nums) {
while (!stk.isEmpty() && stk.peek()[0] < x) {
stk.pop();
}
if (stk.isEmpty() || stk.peek()[0] > x) {
stk.push(new int[] {x, 1});
} else {
stk.peek()[1]++;
}
ans += stk.peek()[1];
}
return ans;
}
}
// Accepted solution for LeetCode #3113: Find the Number of Subarrays Where Boundary Elements Are Maximum
func numberOfSubarrays(nums []int) (ans int64) {
stk := [][2]int{}
for _, x := range nums {
for len(stk) > 0 && stk[len(stk)-1][0] < x {
stk = stk[:len(stk)-1]
}
if len(stk) == 0 || stk[len(stk)-1][0] > x {
stk = append(stk, [2]int{x, 1})
} else {
stk[len(stk)-1][1]++
}
ans += int64(stk[len(stk)-1][1])
}
return
}
# Accepted solution for LeetCode #3113: Find the Number of Subarrays Where Boundary Elements Are Maximum
class Solution:
def numberOfSubarrays(self, nums: List[int]) -> int:
stk = []
ans = 0
for x in nums:
while stk and stk[-1][0] < x:
stk.pop()
if not stk or stk[-1][0] > x:
stk.append([x, 1])
else:
stk[-1][1] += 1
ans += stk[-1][1]
return ans
// Accepted solution for LeetCode #3113: Find the Number of Subarrays Where Boundary Elements Are Maximum
// 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 #3113: Find the Number of Subarrays Where Boundary Elements Are Maximum
// class Solution {
// public long numberOfSubarrays(int[] nums) {
// Deque<int[]> stk = new ArrayDeque<>();
// long ans = 0;
// for (int x : nums) {
// while (!stk.isEmpty() && stk.peek()[0] < x) {
// stk.pop();
// }
// if (stk.isEmpty() || stk.peek()[0] > x) {
// stk.push(new int[] {x, 1});
// } else {
// stk.peek()[1]++;
// }
// ans += stk.peek()[1];
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #3113: Find the Number of Subarrays Where Boundary Elements Are Maximum
function numberOfSubarrays(nums: number[]): number {
const stk: number[][] = [];
let ans = 0;
for (const x of nums) {
while (stk.length > 0 && stk.at(-1)![0] < x) {
stk.pop();
}
if (stk.length === 0 || stk.at(-1)![0] > x) {
stk.push([x, 1]);
} else {
stk.at(-1)![1]++;
}
ans += stk.at(-1)![1];
}
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.
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.