NeetCode #192LC-2460EasyTwo Pointers
← Back to All Problems#192 · #2460 · Apply Operations to an Array(对数组执行操作)
📌 Problem Statement & Constraints
You are given a 0-indexed array
nums of non-negative integers. For each index i from 0 to n-2: if nums[i] == nums[i+1], multiply nums[i] by 2 and set nums[i+1] to 0. Then move all zeros to the end while keeping the relative order of the non-zero elements. Return the resulting array. Constraints: 1 <= nums.length <= 2000, 0 <= nums[i] <= 1000.💡 Core Algorithmic Approaches
- Perform the doubling pass first, comparing each element with its original successor before any modification.
- Then compact the array with a write pointer, exactly as in Move Zeroes.
- The order matters: doubling must complete before the compaction, since compaction changes the adjacency relationships.
- Note that
nums[i+1]is zeroed after a doubling, which prevents a cascading double-double.
💻 Benchmark Python3 Implementation
class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
n = len(nums)
for i in range(n - 1):
if nums[i] == nums[i + 1]:
nums[i] *= 2
nums[i + 1] = 0 # prevent cascading
k = 0
for i in range(n):
if nums[i] != 0:
nums[k] = nums[i]
k += 1
for i in range(k, n):
nums[i] = 0 # pad the tail
return nums⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): two passes.
💾 Space Complexity
O(1) extra: in place.
⚠️ Interview Pitfalls & Follow-ups
- Zeroing the left element instead of the right: the doubling applies to
nums[i]and the successor is zeroed. - Letting the doubled value cascade: after zeroing
nums[i+1], the next comparison uses 0, which prevents a further doubling. Without the zeroing,[2, 2, 4]would behave differently. - Compacting before doubling: the adjacency would be destroyed.
- Forgetting the padding pass: the tail would retain stale values.