33. Replace Elements with Greatest Element on Right

EasyArrayArray

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.

Input: An integer array arr of length n.

Output: The modified array where each element is the max of elements to its right, and last is -1.

Examples

Example 1
Input: [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
Explanation: idx0: max(18,5,4,6,1)=18. idx1: max(5,4,6,1)=6. idx2: max(4,6,1)=6. idx3: max(6,1)=6. idx4: max(1)=1. idx5: -1.
Example 2
Input: [400]
Output: [-1]
Explanation: Single element — no elements to the right. Replace with -1.
Example 3
Input: [1,2,3,4,5]
Output: [5,5,5,5,-1]
Explanation: Each element replaced by max to its right. Last always -1.

Constraints

Asked by

AmazonGoogleMeta
Solve this problem in the editor →