FastPrepNext Taller Building to the Right

Next Taller Building to the Right

Temu logoTemu● EasyFULLTIMEPHONE SCREEN

Problem statement

You are given an integer array heights. heights[i] is the height of building i in a row, from left to right.

For each building, find the first building to its right that is strictly taller. Return an array answer of the same length, where answer[i] is the height of that taller building, or -1 if no building to the right of building i is taller.

A building with the same height is not taller.

Function

nextTallerHeights(heights: int[]) → int[]

Examples

Example 1

heights = [3,1,4,1,5,9,2,6]return = [4,4,5,5,9,-1,6,-1]

The first building to the right of 3 that is taller is 4, and the 1 right after 3 sees that same 4. The 4 and the second 1 both see 5 next, and 5 sees 9. Nothing to the right of 9 is taller, so it gets -1. The 2 sees 6, and the last building always gets -1.

Example 2

heights = [5,5,3,5]return = [-1,-1,5,-1]

A building of the same height does not count. Neither of the first two 5s has a taller building to its right, so both get -1. The 3 sees the last 5, and the last building gets -1.

Example 3

heights = [2,7,4,8]return = [7,8,8,-1]

2 sees 7 right away. 7 skips the shorter 4 and sees 8. 4 also sees 8, and 8 is the last building.

Constraints

  • 1 <= heights.length <= 2000
  • 1 <= heights[i] <= 10^9

More Temu problems

See Temu hiring insights
Saved
public int[] nextTallerHeights(int[] heights) {
    // Write your code here.
}
Checking account…