#2460
Apply Operations to an Array
EasyArrayTwo PointersSimulationArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a single pass to apply operations and another pass to shift zeros. This reduces the number of iterations and avoids unnecessary array creation.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a pointer j to 0 to track the position of the next non-zero element.
- 2Step 2: Iterate through the array with index i. If nums[i] equals nums[i + 1], multiply nums[i] by 2 and set nums[i + 1] to 0. Increment j for the next non-zero element.
- 3Step 3: If nums[i] is not zero, place it at index j and increment j.
- 4Step 4: After processing, fill the rest of the array from index j to n-1 with zeros.
solution.py14 lines
1def apply_operations(nums):
2 n = len(nums)
3 j = 0
4 for i in range(n - 1):
5 if nums[i] == nums[i + 1]:
6 nums[i] *= 2
7 nums[i + 1] = 0
8 for i in range(n):
9 if nums[i] != 0:
10 nums[j] = nums[i]
11 j += 1
12 for i in range(j, n):
13 nums[i] = 0
14 return numsℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the array to apply operations and another pass to shift zeros. The space complexity is O(1) since we modify the array in place without using extra space.
- 1Operations are applied sequentially, not all at once.
- 2Shifting zeros to the end requires careful management of indices.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.