Problem
Given an array of numbers and an index i
, return the index of the nearest larger number of the number at index i
, where distance is measured in array indices.
For example, given [4, 1, 3, 5, 6]
and index 0
, you should return 3
.
If two distances to larger numbers are the equal, then return any one of them. If the array at i
doesn’t have a nearest larger integer, then return null.
Follow-up: If you can preprocess the array, can you do this in constant time?
Examples
Example 1
|
|
Example 2
|
|
Solution
To find the nearest larger number for the given index i
, we need to check both directions (left and right) in the array for the nearest larger number. The idea is to explore both neighbors and keep track of the nearest larger number found.
Method 1 - Linear Search + Two Pointer Technique
Approach
- Linear Search:
- Start from index
i
and explore both directions (left and right) to find the nearest index with a larger number. - Keep track of the nearest distance and index while exploring both directions simultaneously.
- Start from index
- Two Pointer Technique:
- Use two pointers (
left
andright
) initialized to indexi
. - Move both pointers outward (in left and right direction) and keep checking for larger numbers until the end of the array is reached.
- Use two pointers (
For the follow-up, we can create an auxiliary array during preprocessing that stores the nearest larger indices for each element, allowing us to query in constant time.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is the number of elements in the array, as we may need to scan the entire array in the worst case. - 🧺 Space complexity:
O(1)
for the space used by the pointers and result index.