Apply Operations to an Array — LeetCode 2460 Python Solution

EasyArrayTwo PointersSimulation
Problem
#2460
Reading time
3 min

The problem

You are given a 0-indexed array nums of size n consisting of non-negative integers. You need to apply n - 1 operations to this array where, in the ith operation (0-indexed), you will apply the following on the ith element of nums: If nums[i] == nums[i + 1], then multiply nums[i] by 2 and set nums[i + 1] to 0.

Example

Input
nums = [1,2,2,1,1,0]
Output
[1,4,2,0,0,0]
Explanation
We do the following operations:

Python solution

Python
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] <<= 1
                nums[i + 1] = 0
        ans = [0] * n
        i = 0
        for x in nums:
            if x:
                ans[i] = x
                i += 1
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array nums
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2460. Apply Operations to an Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2460. Apply Operations to an Array?
LeetCode 2460. Apply Operations to an Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 2460. Apply Operations to an Array?
The Python solution on this page runs in O(n), where n is the length of the array nums.
What is the space complexity of LeetCode 2460. Apply Operations to an Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2460. Apply Operations to an Array cover?
LeetCode 2460. Apply Operations to an Array is tagged Array, Two Pointers and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview