Skip to main content
Back to problems
#2460
Easy Algorithms

Apply operations to an array

Array Two Pointers Simulation
74.7% acceptance
Feb 25, 2026
1129
66
You are given a 0-indexed array nums of size n consisting of non-negative int egers. * You need to apply n - 1 operations to this array where, in the ith operation (0-indexed), you will apply the following on the ith element of nums: * If nums[i] == nums[i + 1], then multiply nums[i] by 2 and set nums[i + 1] to 0. Otherwise, you skip this operation. * After performing all the operations, shift all the 0's to the end of the arra y. * For example, the array [1,0,2,0,0,1] after shifting all its 0's to the end, i s [1,2,1,0,0,0]. * Return the resulting array. Note that the operations are applied sequentially, not all at once.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn apply_operations(nums: Vec<i32>) -> Vec<i32> {
    let mut nums = nums;
    let n = nums.len();
    for i in 0..n - 1 {
      if nums[i] == nums[i + 1] {
        nums[i] *= 2;
        nums[i + 1] = 0;
      }
    }
    let mut result: Vec<i32> = nums.iter().filter(|&&x| x != 0).cloned().collect();
    while result.len() < n { result.push(0); }
    result
  }
}