Maximal Range That Each Element Is Maximum in It - Problem

You're given an array of distinct integers, and your task is to find the maximum range where each element can be the dominant leader!

For each element nums[i] in the array, you need to determine the longest possible subarray where nums[i] is the maximum element. Think of it as finding the "sphere of influence" for each number - how far can its dominance extend?

Goal: Return an array ans where ans[i] represents the maximum length of any subarray that contains nums[i] as its maximum element.

Example: In array [2, 1, 4, 9, 3], the element 9 can dominate the entire array (length 5), while 1 can only dominate a subarray of length 1 (just itself).

Input & Output

example_1.py โ€” Basic Case
$ Input: [2, 1, 4, 9, 3]
โ€บ Output: [2, 1, 3, 5, 1]
๐Ÿ’ก Note: Element 2 can dominate subarray [2,1] (length 2). Element 1 can only dominate itself (length 1). Element 4 can dominate [2,1,4] (length 3). Element 9 can dominate the entire array (length 5). Element 3 can only dominate itself (length 1).
example_2.py โ€” Ascending Order
$ Input: [1, 2, 3, 4, 5]
โ€บ Output: [1, 1, 1, 1, 5]
๐Ÿ’ก Note: In ascending order, each element (except the last) can only dominate itself, as there's always a greater element immediately to the right. The last element (5) can dominate the entire array since it's the global maximum.
example_3.py โ€” Single Element
$ Input: [42]
โ€บ Output: [1]
๐Ÿ’ก Note: With only one element, it can dominate a subarray of length 1 (itself).

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 106
  • All elements in nums are distinct
  • The array is 0-indexed

Visualization

Tap to expand
Mountain Peak Visibility RangeArray: [2, 1, 4, 9, 3] โ†’ Heights of mountain peaks21493Peak '4' can see range of length 3: [2,1,4]No taller peak on leftBlocked by peak '9'๐Ÿ’ก Each peak's visible range extends until blocked by taller peaks on both sides
Understanding the Visualization
1
Identify Peaks
Each number represents a mountain peak of that height
2
Look Left
Find the nearest taller peak to the left (or mountain base if none)
3
Look Right
Find the nearest taller peak to the right (or mountain base if none)
4
Calculate Visibility
The visible range is everything between the blocking peaks
Key Takeaway
๐ŸŽฏ Key Insight: Use monotonic stack to efficiently find the nearest greater elements, which define the boundaries of each element's maximum range.
Asked in
Google 42 Amazon 35 Meta 28 Microsoft 22 Apple 18
68.4K Views
Medium-High Frequency
~18 min Avg. Time
1.8K 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