Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created March 1, 2025 22:32
Show Gist options
  • Select an option

  • Save Ifihan/ef30a6762e3f48ed2ad6e21e6acc0949 to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/ef30a6762e3f48ed2ad6e21e6acc0949 to your computer and use it in GitHub Desktop.

Question

Approach

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.

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
        
        result = [num for num in nums if num != 0]
        result.extend([0] * (n - len(result)))
        
        return result

Complexities

  • Time: O(n)
  • Space: O(n)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment