LeetCode in Kotlin

2460. Apply Operations to an Array

Easy

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:

After performing all the operations, shift all the 0’s to the end of the array.

Return the resulting array.

Note that the operations are applied sequentially, not all at once.

Example 1:

Input: nums = [1,2,2,1,1,0]

Output: [1,4,2,0,0,0]

Explanation: We do the following operations:

After that, we shift the 0’s to the end, which gives the array [1,4,2,0,0,0].

Example 2:

Input: nums = [0,1]

Output: [1,0]

Explanation: No operation can be applied, we just shift the 0 to the end.

Constraints:

Solution

class Solution {
    fun applyOperations(nums: IntArray): IntArray {
        for (i in 0 until nums.size - 1) {
            if (nums[i] == nums[i + 1]) {
                nums[i] *= 2
                nums[i + 1] = 0
            }
        }
        var index = 0
        for (i in nums.indices) {
            if (nums[i] != 0) {
                nums[index] = nums[i]
                index++
            }
        }
        for (i in index until nums.size) {
            nums[i] = 0
        }
        return nums
    }
}