Problem 1299 · LeetCode 1299(opens in a new tab)
Replace Elements with Greatest Element on Right Side
EasyArrays
You are given an array of positive whole numbers, arr. Change every element into the largest value that sits somewhere to its right. The last element has nothing to its right, so it becomes -1.
Return the changed array.
Example 1
Input: arr = [7, 3, 9, 2, 4] Output: [9, 9, 4, 4, -1] Why: 9 is the biggest after 7 and after 3; after 9 only 2 and 4 are left
2 more examples and the constraints
Example 2
Input: arr = [12] Output: [-1] Why: a single element has nothing to its right
Example 3
Input: arr = [1, 2, 3] Output: [3, 3, -1] Why: the last value 3 is the largest for everyone before it
Constraints
- 1 ≤ length of arr ≤ 10,000
- 1 ≤ arr[i] ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Scan the right sideO(n²)
- Right-to-left running maxO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 elements | Verdict |
|---|---|---|---|
| Scan the right side | O(n²) | Mention it, then move on | |
| Right-to-left running max | O(n) | Best; one pass, in place |
n = length of arr.
Edge cases to test
- One element. [12] becomes [-1].
- Increasing values. [1, 2, 3] gives [3, 3, -1]: the last value wins for everyone.
- Decreasing values. [5, 4, 3] gives [4, 3, -1]: each cell takes its right neighbour.
- Repeated maximum. [6, 6, 6] gives [6, 6, -1]; equal values are fine.
Common mistakes
- Updating best before writing the cell, so a cell counts its own value.
- Overwriting in place while walking left to right, which destroys values still needed.
- Forgetting that the last element must become -1.
How to talk through it
- 1Clarify. Can I change the input array? Are all values positive, so -1 is never a real value?
- 2Give the brute force. Scan right of each position; O(n²) because the scans overlap.
- 3Flip the direction. From the right, the maximum so far is the answer for the next cell to the left.
- 4Mind the order. Save, write best, then update best. O(n) time, O(1) extra space.
- 5Test out loud. Run [12], an increasing array and a decreasing one.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?