← Questions
Longest subarray whose ends exceed everything between
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's online assessment, last asked Sep 2025. It tests monotonic stack and arrays.
Given an integer array, return the length of the longest contiguous segment [i..j] (at least two elements long) whose two end elements are both strictly greater than every element strictly between them. A pair of neighbours always qualifies, since nothing lies between them. Do better than checking every pair of ends.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
longest_segment(nums: list[int]) -> int— 0 when the array has fewer than two elements.
Example
longest_segment([1, 3, 2, 4, 1]) -> 3 # [3, 2, 4]: inside max 2 < min(3, 4)
longest_segment([4, 2, 6]) -> 3
longest_segment([5, 1, 2, 1, 6]) -> 5 # inside max 2 < min(5, 6)
longest_segment([3, 3, 3]) -> 2 # an equal value inside does not count as smaller
longest_segment([7]) -> 0
Constraints
-
0 <= n <= 10^5; values may be negative and may repeat. - Faster than O(n²); O(n) is possible.
Clarifying questions
- Is a segment of two adjacent elements valid? (Yes.)
- Must the ends be strictly greater than the inside, or is equal allowed? (Strictly.)
- Return the length only, or the segment too?
What a strong answer covers
- The observation that
(i, j)is valid exactly when nothing between them is at leastmin(nums[i], nums[j]), which is what a monotonic stack of decreasing values tracks. - Sweep
jleft to right with a stack of indices whose values are decreasing: pop every index whose value is smaller thannums[j]and record the segment from it toj; the index left on top (value at leastnums[j]) also pairs withj; if its value equalsnums[j], pop it too, so a later larger element never pairs across an equal one. O(n) time, O(n) space. - Why each valid pair the answer needs is seen at the moment one end pops or meets the other.
- A brute-force O(n²) checker over random small arrays, especially with repeated values.
Follow-ups
- Count all valid segments instead of finding the longest.
- Ends must be at least the inside values (not strictly greater).
Where it's asked
- Amazon · Online assessment · Last asked Sep 2025Coding problems plus a repository bug-fix section with a built-in assistant or a design scenario, then a work-style survey · AI only inside the bug-fix section's built-in assistant
What it tests
monotonic stack · arrays
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
