Replace Elements with Greatest Element on Right Side

Given an array arr, replace every element with the greatest element among the elements to its right, and replace the last element with -1. Return the array after doing so.

30:00

Replace Elements with Greatest Element on Right Side
easy
Free written solution
Topics
Companies

Given an array arr, replace every element with the greatest element among the elements to its right, and replace the last element with -1. Return the array after doing so.

Example 1:
Input: {"arr":[17,18,5,4,6,1]}
Output: [18,6,6,6,1,-1]
Constraints:
  • 1≤arr.length≤1041 \leq \text{arr.length} \leq 10^4

  • 1≤arr[i]≤1051 \leq \text{arr}[i] \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"arr":[17,18,5,4,6,1]}

Walk from the right end. mx holds the largest value seen to the right; nothing is to the right of the last element yet, so mx starts at -1.

walk right to left, carrying the tallest value seen

17

0

18

1

5

2

4

3

6

4

1

5

bars = original values, green boxes = what each slot now holds, dashed line = mx

mx = -1
replaced 0 of 6
Variables
VariableValue
mx-1
n6
DepthFunction Call
Stack empty
0/13