Apply Operations to an Array - Problem
You're given an array of non-negative integers and need to perform a sequential transformation process followed by a cleanup operation.
The Process:
- Apply Operations: Go through the array from left to right. For each element at position
i, if it equals the next element at positioni+1, then:- Double the current element:
nums[i] *= 2 - Set the next element to zero:
nums[i+1] = 0
- Double the current element:
- Move Zeros: After all operations, shift all zeros to the end of the array while maintaining the relative order of non-zero elements.
Example: [1,0,2,2,1,0,0,1] becomes [1,0,4,1,1,0,0,0] after operations, then [1,4,1,1,0,0,0,0] after moving zeros.
Remember: Operations are applied sequentially, not simultaneously!
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1,0,2,2,1,0,0,1]
โบ
Output:
[1,4,1,1,0,0,0,0]
๐ก Note:
Apply operations: [1,0,2,2,1,0,0,1] โ [1,0,4,0,1,0,0,1] (2==2 becomes 4,0). Move zeros: [1,4,1,1,0,0,0,0]
example_2.py โ Multiple Operations
$
Input:
nums = [2,2,4,4,8,8]
โบ
Output:
[4,8,16,0,0,0]
๐ก Note:
Operations: [2,2,4,4,8,8] โ [4,0,8,0,16,0]. Move zeros to end: [4,8,16,0,0,0]
example_3.py โ No Operations
$
Input:
nums = [1,2,3,4,5]
โบ
Output:
[1,2,3,4,5]
๐ก Note:
No adjacent elements are equal, so no operations applied. No zeros to move, array stays the same.
Visualization
Tap to expand
Understanding the Visualization
1
Merge Phase
Identical adjacent candies get combined into double-sized candies, leaving empty spaces
2
Collection Phase
Use two workers (pointers) to efficiently collect all real candies and move empty spaces to the end
Key Takeaway
๐ฏ Key Insight: Two-phase processing is optimal - we must complete all merge operations before rearranging, and two pointers make the rearrangement efficient in O(n) time.
Time & Space Complexity
Time Complexity
O(n)
O(n) for applying operations + O(n) for moving zeros with two pointers
โ Linear Growth
Space Complexity
O(1)
Only using two pointer variables and constant extra space
โ Linear Space
Constraints
- 2 โค nums.length โค 2000
- 0 โค nums[i] โค 1000
- Operations are applied sequentially, not simultaneously
- Must maintain relative order of non-zero elements after moving zeros
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code