Apply Operations to an Array

Easy Topics Company Tags

Visit adjacent pairs of nums from left to right, starting with indices 0 and 1. If the two current values are equal, double the left value and replace the right value with 0; otherwise leave them unchanged. Each later pair uses the array as changed by earlier operations.

After this single pass, move all zeros to the end while preserving the relative order of the nonzero values. Return the resulting array, with the same length as the input.

Example 1:

Input: nums = [2,2,2,2]

Output: [4,4,0,0]

Explanation: The left-to-right pass produces [4,0,4,0]. Moving its zeros to the end gives [4,4,0,0]; the two 4s are not merged again.

Example 2:

Input: nums = [0,3,3,0]

Output: [6,0,0,0]

Explanation: The middle equal pair becomes 6 and 0, producing [0,6,0,0]. Moving the leading zero to the end gives [6,0,0,0].

Example 3:

Input: nums = [1,2,3]

Output: [1,2,3]

Explanation: No adjacent pair is equal and there are no zeros to move, so the array stays [1,2,3].

Constraints:

  • 2 <= nums.length <= 2000
  • 0 <= nums[i] <= 1000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.