LeetCode solutions

2551. Apply Operations to an Array

My accepted JavaScript solution to LeetCode problem 2551, Apply Operations to an Array, running in 1ms.

  • Difficulty: Easy
  • JavaScript
  • Runtime 1ms
  • Memory 57.9MB

Read the problem on LeetCode View on GitHub

JavaScript

Accepted on LeetCode — runtime 1ms, memory 57.9MB, accepted 2025-12-29.

javascript
/**
* @param {number[]} nums
* @return {number[]}
*/
var applyOperations = function(nums) {
    const n = nums.length;
    for (let i = 0; i < n - 1; i++) {
        if (nums[i] === nums[i + 1]) {
            nums[i] *= 2;
            nums[i + 1] = 0;
        }
    }
    const result = nums.filter(x => x !== 0);
    while (result.length < n) result.push(0);
    return result;
};

Source