In my approach, I first iterate through the array and check if two consecutive elements are equal. If they are, I double the value of the first element and set the second to zero. After applying all operations sequentially, I filter out non-zero elements and store them in a new list.
Finally, I append the necessary number of zeros to maintain the original array size.
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
result = [num for num in nums if num != 0]
result.extend([0] * (n - len(result)))
return result- Time: O(n)
- Space: O(n)