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:

  1. Apply Operations: Go through the array from left to right. For each element at position i, if it equals the next element at position i+1, then:
    • Double the current element: nums[i] *= 2
    • Set the next element to zero: nums[i+1] = 0
  2. 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
๐Ÿฌ Candy Factory Assembly LinePhase 1: Merge Adjacent Identical Candies22โ†’4โˆ…Same candies merge!Phase 2: Collect & Reorganize with Two Workers1โˆ…41๐Ÿ‘ท Collector๐Ÿ‘ท ScannerFinal Result: All Real Candies First, Empty Spaces Last141โˆ…โˆ…โœจ Organized & Efficient!
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

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using two pointer variables and constant extra space

n
2n
โœ“ 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
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
24.7K Views
Medium Frequency
~15 min Avg. Time
842 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen