LeetCode #3676 — MEDIUM

Count Bowl Subarrays

Move from brute-force thinking to an efficient approach using array strategy.

Solve on LeetCode
The Problem

Problem Statement

You are given an integer array nums with distinct elements.

A subarray nums[l...r] of nums is called a bowl if:

  • The subarray has length at least 3. That is, r - l + 1 >= 3.
  • The minimum of its two ends is strictly greater than the maximum of all elements in between. That is, min(nums[l], nums[r]) > max(nums[l + 1], ..., nums[r - 1]).

Return the number of bowl subarrays in nums.

Example 1:

Input: nums = [2,5,3,1,4]

Output: 2

Explanation:

The bowl subarrays are [3, 1, 4] and [5, 3, 1, 4].

  • [3, 1, 4] is a bowl because min(3, 4) = 3 > max(1) = 1.
  • [5, 3, 1, 4] is a bowl because min(5, 4) = 4 > max(3, 1) = 3.

Example 2:

Input: nums = [5,1,2,3,4]

Output: 3

Explanation:

The bowl subarrays are [5, 1, 2], [5, 1, 2, 3] and [5, 1, 2, 3, 4].

Example 3:

Input: nums = [1000000000,999999999,999999998]

Output: 0

Explanation:

No subarray is a bowl.

Constraints:

  • 3 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • nums consists of distinct elements.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given an integer array nums with distinct elements. A subarray nums[l...r] of nums is called a bowl if: The subarray has length at least 3. That is, r - l + 1 >= 3. The minimum of its two ends is strictly greater than the maximum of all elements in between. That is, min(nums[l], nums[r]) > max(nums[l + 1], ..., nums[r - 1]). Return the number of bowl subarrays in nums.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Stack

Example 1

[2,5,3,1,4]

Example 2

[5,1,2,3,4]

Example 3

[1000000000,999999999,999999998]
Step 02

Core Insight

What unlocks the optimal approach

  • Use monotonic stacks to find nearest greater elements on both sides.
  • The bowl condition depends on comparing both ends with the maximum of the middle - avoid recomputing max by preprocessing.
  • Think in terms of "valid endpoints" rather than enumerating all subarrays.
  • There's symmetry: you can check both (left endpoint is smaller) and (right endpoint is smaller) cases separately.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3676: Count Bowl Subarrays
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3676: Count Bowl Subarrays
// package main
// 
// // https://space.bilibili.com/206214
// func bowlSubarrays1(nums []int) (ans int64) {
// 	st := []int{}
// 	for i, x := range nums {
// 		for len(st) > 0 && nums[st[len(st)-1]] < x {
// 			// j=st[len(st)-1] 右侧严格大于 nums[j] 的数的下标是 i
// 			if i-st[len(st)-1] > 1 { // 子数组的长度至少为 3
// 				ans++
// 			}
// 			st = st[:len(st)-1]
// 		}
// 		// i 左侧大于等于 nums[i] 的数的下标是 st[len(st)-1]
// 		if len(st) > 0 && i-st[len(st)-1] > 1 { // 子数组的长度至少为 3
// 			ans++
// 		}
// 		st = append(st, i)
// 	}
// 	return
// }
// 
// func bowlSubarrays(nums []int) (ans int64) {
// 	st := nums[:0]
// 	for _, x := range nums {
// 		for len(st) > 0 && st[len(st)-1] < x {
// 			st = st[:len(st)-1]
// 			if len(st) > 0 {
// 				ans++
// 			}
// 		}
// 		st = append(st, x)
// 	}
// 	return
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n)
Space
O(n)

Approach Breakdown

BRUTE FORCE
O(n²) time
O(1) space

For each element, scan left (or right) to find the next greater/smaller element. The inner scan can visit up to n elements per outer iteration, giving O(n²) total comparisons. No extra space needed beyond loop variables.

MONOTONIC STACK
O(n) time
O(n) space

Each element is pushed onto the stack at most once and popped at most once, giving 2n total operations = O(n). The stack itself holds at most n elements in the worst case. The key insight: amortized O(1) per element despite the inner while-loop.

Shortcut: Each element pushed once + popped once → O(n) amortized. The inner while-loop does not make it O(n²).
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

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.

Breaking monotonic invariant

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.