Apply Operations to an Array

Here is a Python solution that implements this behavior. It iterates over the array and applies the operations as described. After that, it moves all zeros to the end of the array.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
    def applyOperations(self, nums: List[int]) -> List[int]:
        n = len(nums)
        # Perform operations
        for i in range(n - 1):
            if nums[i] == nums[i + 1]:
                nums[i] *= 2
                nums[i + 1] = 0

        # Move zeros to the end
        result = [num for num in nums if num != 0]  # Filter out non-zero numbers
        result.extend([0] * (n - len(result)))  # Add the necessary number of zeros at the end
        return result

In this solution, we iterate through the list of numbers. If the current number is the same as the next one, we double the current number and set the next number to 0. After performing all these operations, we filter out all non-zero numbers and create a new list. The remaining slots in the list are filled with zeros. This effectively moves all zeros to the end of the list.

Readable Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
    def applyOperations(self, nums: List[int]) -> List[int]:
        for i in range(len(nums) - 1):
            if nums[i] == nums[i+1]:
                nums[i] = 2 * nums[i]
                nums[i+1] = 0

        i = 0
        for n in nums:
            if n != 0:
                nums[i] = n
                i += 1

        while i < len(nums):
            nums[i] = 0
            i += 1

        return nums

This code first updates the array based on the condition that if two consecutive numbers are equal, then it multiplies the first number by 2 and sets the second number to 0. Then it collects all non-zero values at the front and sets remaining values to zero. The final array is then returned.