FastPrepNext Greater Indices and Maximum Gap

Next Greater Indices and Maximum Gap

TikTok logoTikTok● MediumINTERNPHONE SCREEN
Learn

Problem statement

You are given an integer array nums, indexed from 0.

For each index i, find the smallest index j > i such that nums[j] > nums[i]. This is the nearest strictly greater element to the right. If no such index exists, use -1. Equal values do not qualify, and the array does not wrap around.

For every qualifying match, its index gap is j - i. Find the maximum of these gaps, or 0 if no position has a qualifying match.

Return an integer matrix with exactly two rows:

  • Row 0 contains the nearest-greater index for each input position, in order.
  • Row 1 contains exactly one integer: the maximum qualifying index gap.

For an empty input, return [[],[0]].

Function

nextGreaterIndicesAndMaxGap(nums: int[]) → int[][]

Examples

Example 1

nums = [2,1,2,4,3]return = [[3,2,3,-1,-1],[3]]

Index0 skips the equal value at2 and matches index3, giving gap3. The other matches are1→2 and2→3. The maximum gap is3.

Example 2

nums = [1,3,2,4]return = [[1,3,3,-1],[2]]

Index0 matches the nearest greater value at index1, not the farther value at3. Index1 matches3, so the maximum gap is2.

Example 3

nums = []return = [[],[0]]

The index row is empty and there are no qualifying gaps.

Constraints

  • 0 <= nums.length <= 2000.
  • -10^9 <= nums[i] <= 10^9.

More TikTok problems

See TikTok hiring insights
Saved
public int[][] nextGreaterIndicesAndMaxGap(int[] nums) {
    // Write your code here.
}
nums[2,1,2,4,3]
expected[[3,2,3,-1,-1],[3]]
Checking account…