[LeetCode] 2460. Apply Operations to an Array

Problem

https://leetcode.com/problems/apply-operations-to-an-array/description/

Leetcode - Apply Operations to an Array

Type - array, two pointers, sorting

Difficulty - Easy

Approach & Solution

This is Easy problem.

Just simply operate literally and shift it.

data structures & variables:

  • ans: storing shifted array after operations.

  • k: next index of ans to store element in nums such that greater than 0.

Shifting can be done with two-pointer approach.

  • Initialize k = 0.

  • By iterating nums,

    • if nums[i] is not zero, assign ans[k] from nums[i]. then increment k by 1.

Complexity

Time Complexity: O(n) - For operation and shifting.

Space Complexity: O(n) - ans is 1-D array.

Code (C++ | Go)

class Solution {
public:
    vector<int> applyOperations(vector<int>& nums) {
        int n = nums.size();

        for(int i = 0; i < n-1; i++) {
            if(nums[i] == nums[i+1]) {
                nums[i] *= 2;
                nums[i+1] = 0;
            }
        }

        vector<int> ans(n, 0);
        int k = 0;
        for(int i = 0; i < n; i++) {
            if(nums[i] != 0) {
                ans[k] = nums[i];
                k++;
            }
        }

        return ans;
    }
};
func applyOperations(nums []int) []int {
    n := len(nums);
    for i := 0; i < n-1; i++ {
        if nums[i] == nums[i+1] {
            nums[i] *= 2;
            nums[i+1] = 0;
        }
    }

    ans := make([]int, n)
    k := 0
    for i := 0; i < n; i++ {
        if nums[i] != 0 {
            ans[k] = nums[i];
            k++
        }
    }
    return ans
}