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 where, in the `i`<sup>th</sup> operation (**0-indexed**), you will apply the following on the `i`<sup>th</sup> 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 array. - For example, the array `[1,0,2,0,0,1]` after shifting all its `0`'s to the end, is `[1,2,1,0,0,0]`. Return *the resulting array*. **Note** that the operations are applied **sequentially**, not all at once.

30:00

Apply Operations to an Array
easy
Free written solution
Topics
Companies

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 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 array.

  • For example, the array [1,0,2,0,0,1] after shifting all its 0's to the end, is [1,2,1,0,0,0].

Return the resulting array.

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

Example 1:
Input: {"nums":[1,2,2,1,1,0]}
Output: [1,4,2,0,0,0]
Constraints:
  • 2≤nums.length≤20002 \leq \text{nums.length} \leq 2000

  • 0≤nums[i]≤10000 \leq \text{nums}[i] \leq 1000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,2,1,1,0]}

Pass 1 slides a window over each neighbor pair, left to right: equal neighbors merge, the left doubles and the right becomes 0. Pass 2 then pushes all zeros to the end.

Pass 1: merge equal neighbors
Pass 2: zeros to the end

original input

1
2
2
1
1
0

nums

0
1
1
2
2
2
3
1
4
1
5
0

merges

0

read

-

write

-

window i, i+1
doubled by a merge
zeroed by a merge
r = read
w = write
Variables
No variables to display
DepthFunction Call
Stack empty
0/13