Skip to main content
Back to problems
#1299
Easy Algorithms

Replace elements with greatest element on right side

Array
72.0% acceptance
Feb 25, 2026
2844
267
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. After doing so, return the array.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn replace_elements(mut arr: Vec<i32>) -> Vec<i32> {
    let n = arr.len();
    let mut max_right = -1i32;
    for i in (0..n).rev() {
      let cur = arr[i];
      arr[i] = max_right;
      max_right = max_right.max(cur);
    }
    arr
  }
}