Apply Operations to an Array

You are given a 0-indexed array nums of size n consisting of non-negative integers.

You need to apply n - 1 operations to this array. In the i^th operation (0-indexed), apply the following to the i^th element of nums:

  • If nums[i] == nums[i + 1], multiply nums[i] by 2 and set nums[i + 1] to 0.
  • Otherwise, skip this operation.

After performing all the operations, shift all the 0's to the end of the array.

Return the resulting array.

Note that the operations are applied sequentially, not all at once.

Example 1
Inputnums = [1,2,2,1,1,0]
Output[1,4,2,0,0,0]
After applying the sequential operations, the array becomes [1,4,0,2,0,0], and shifting the 0's to the end gives [1,4,2,0,0,0].
Example 2
Inputnums = [0,1]
Output[1,0]
No operation can be applied, so we just shift the 0 to the end.

Constraints

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

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate