Apply Operations to an Array - Problem
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 multiplynums[i]by 2 and setnums[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.
Input & Output
Example 1 — Basic Doubling
$
Input:
nums = [2,2,1,1,0]
›
Output:
[4,2,0,0,0]
💡 Note:
First operation: nums[0] == nums[1] so 2*2=4, nums becomes [4,0,1,1,0]. Second operation: nums[2] == nums[3] so 1*2=2, nums becomes [4,0,2,0,0]. After shifting zeros: [4,2,0,0,0]
Example 2 — No Matching Pairs
$
Input:
nums = [0,1]
›
Output:
[1,0]
💡 Note:
First operation: nums[0] != nums[1] (0 != 1), so no change. Array remains [0,1]. After shifting zeros to end: [1,0]
Example 3 — Multiple Operations
$
Input:
nums = [1,2,2,1,1,0]
›
Output:
[1,4,2,0,0,0]
💡 Note:
Operation at index 1: nums[1] == nums[2] so 2*2=4, becomes [1,4,0,1,1,0]. Operation at index 3: nums[3] == nums[4] so 1*2=2, becomes [1,4,0,2,0,0]. After shifting zeros: [1,4,2,0,0,0]
Constraints
- 2 ≤ nums.length ≤ 2000
- 0 ≤ nums[i] ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
[2,2,1,1,0] - array with adjacent equal pairs
2
Apply Operations
Double equal adjacent pairs: 2,2→4,0 and 1,1→2,0
3
Move Zeros
[4,2,0,0,0] - all zeros moved to end
Key Takeaway
🎯 Key Insight: Sequential operations create zeros that need to be moved to the end efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code