Apply Operations to an Array

easy array simulation two pointers

Problem

You are given a 0-indexed array nums of size n. Apply n − 1 operations in order, where the i-th operation looks at the pair at positions i and i + 1: if nums[i] equals nums[i + 1], double nums[i] and set nums[i + 1] to 0; otherwise leave the pair unchanged. After all operations, shift every 0 to the end of the array while keeping the relative order of the non-zero values, and return the result.

Inputnums = [1, 2, 2, 1, 1, 0]
Output[1, 4, 2, 0, 0, 0]
The 2 & 2 pair merges into 4, and the 1 & 1 pair merges into 2. After the pass the array is [1, 4, 0, 2, 0, 0]; sliding the zeros to the back gives [1, 4, 2, 0, 0, 0].

def apply_operations(nums):
    n = len(nums)
    for i in range(n - 1):
        if nums[i] == nums[i + 1]:
            nums[i] *= 2
            nums[i + 1] = 0
    j = 0
    for x in nums:
        if x != 0:
            nums[j] = x
            j += 1
    while j < n:
        nums[j] = 0
        j += 1
    return nums
function applyOperations(nums) {
  const n = nums.length;
  for (let i = 0; i < n - 1; i++) {
    if (nums[i] === nums[i + 1]) {
      nums[i] *= 2;
      nums[i + 1] = 0;
    }
  }
  let j = 0;
  for (const x of nums) {
    if (x !== 0) nums[j++] = x;
  }
  while (j < n) nums[j++] = 0;
  return nums;
}
class Solution {
    public int[] applyOperations(int[] nums) {
        int n = nums.length;
        for (int i = 0; i < n - 1; i++) {
            if (nums[i] == nums[i + 1]) {
                nums[i] *= 2;
                nums[i + 1] = 0;
            }
        }
        int j = 0;
        for (int x : nums) {
            if (x != 0) nums[j++] = x;
        }
        while (j < n) nums[j++] = 0;
        return nums;
    }
}
vector<int> applyOperations(vector<int>& nums) {
    int n = (int)nums.size();
    for (int i = 0; i < n - 1; i++) {
        if (nums[i] == nums[i + 1]) {
            nums[i] *= 2;
            nums[i + 1] = 0;
        }
    }
    int j = 0;
    for (int x : nums) {
        if (x != 0) nums[j++] = x;
    }
    while (j < n) nums[j++] = 0;
    return nums;
}
Time: O(n) Space: O(1)