Leetcode 1299. Replace Elements with Greatest Element on Right Side
Given an array arr
, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1
.
To solve this problem efficiently, we can traverse the array from right to left. By keeping track of the greatest element we have seen so far, we can replace each element with the maximum of the elements to its right:
Here’s the implementation in Java:
public class Solution {
public void replaceElements(int[] arr) {
// Initialize the greatest element as -1 (the replacement for the last element)
int greatest = -1;
// Traverse the array from right to left
for (int i = arr.length - 1; i >= 0; i--) {
// Temporarily store the current element
int current = arr[i];
// Replace current element with the greatest element seen so far
arr[i] = greatest;
// Update greatest element seen so far
greatest = Math.max(greatest, current);
}
}
}
This solution efficiently processes the array in a single pass with minimal additional space utilization.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?