Peaks in Array - Problem

A peak in an array arr is an element that is greater than its previous and next element in arr.

You are given an integer array nums and a 2D integer array queries. You have to process queries of two types:

  • queries[i] = [1, li, ri] - determine the count of peak elements in the subarray nums[li..ri]
  • queries[i] = [2, indexi, vali] - change nums[indexi] to vali

Return an array answer containing the results of the queries of the first type in order.

Note: The first and the last element of an array or a subarray cannot be a peak.

Input & Output

Example 1 — Basic Peak Counting
$ Input: nums = [2,8,6,1,5], queries = [[2,3,4],[1,0,4]]
Output: [1]
💡 Note: After updating nums[3] = 4, array becomes [2,8,6,4,5]. Query [1,0,4] counts peaks in range [0,4]. Only index 1 (value 8) is a peak since 8 > 2 and 8 > 6.
Example 2 — Multiple Queries
$ Input: nums = [1,3,2,4,1], queries = [[1,1,4],[2,2,5],[1,0,3]]
Output: [2,1]
💡 Note: First query [1,1,4]: peaks at indices 1 (3>1,3>2) and 3 (4>2,4>1), count=2. After update nums[2]=5: [1,3,5,4,1]. Second query [1,0,3]: only peak at index 1 (3>1,3>5 is false), but index 2 (5>3,5>4) is peak, count=1.
Example 3 — Edge Case No Peaks
$ Input: nums = [1,2,3], queries = [[1,0,2]]
Output: [0]
💡 Note: Range [0,2] has no valid peak positions since first and last elements cannot be peaks. Only index 1 could be a peak, but 2 < 3, so no peaks found.

Constraints

  • 3 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105
  • 1 ≤ queries.length ≤ 105
  • queries[i] = [1, li, ri] or queries[i] = [2, indexi, vali]
  • 0 ≤ li < ri ≤ nums.length - 1
  • 0 ≤ indexi ≤ nums.length - 1
  • 1 ≤ vali ≤ 105

Visualization

Tap to expand
Peaks in Array: Finding Mountain PeaksInput: nums = [1,3,2,4,1], queries = [[1,1,4]]13241idx 0idx 1idx 2idx 3idx 4PEAKPEAKQuery Range [1,4]✓ Peak: 3 > 1 and 3 > 2✓ Peak: 4 > 2 and 4 > 1Output: [2] - Found 2 peaks in range
Understanding the Visualization
1
Input Array
Array with elements marked as peaks or non-peaks
2
Query Processing
Count peaks in range or update array values
3
Output
Results for all range queries
Key Takeaway
🎯 Key Insight: Use segment trees or BIT to efficiently track peak counts across range queries while handling dynamic updates
Asked in
Google 25 Facebook 18 Amazon 15 Microsoft 12
12.5K Views
Medium Frequency
~35 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen