Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2460. Apply Operations to an Array

Explanation

To solve this problem, we can iterate through the array and apply the specified operations. For each pair of adjacent elements where the elements are equal, we update the first element by multiplying it by 2 and set the second element to 0. After performing all operations, we shift all zeros to the end of the array.

Here are the steps for the algorithm:

  1. Iterate through the array and apply the given operations.
  2. Shift all zeros to the end of the array.

The time complexity of this approach is O(n) where n is the number of elements in the array. The space complexity is O(1) as we are modifying the input array in place.

class Solution {
    public int[] applyOperations(int[] nums) {
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] == nums[i + 1]) {
                nums[i] *= 2;
                nums[i + 1] = 0;
            }
        }
        
        int k = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                nums[k++] = nums[i];
            }
        }
        
        while (k < nums.length) {
            nums[k++] = 0;
        }
        
        return nums;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.