LeetCode in Kotlin

3819. Rotate Non Negative Elements

Medium

You are given an integer array nums and an integer k.

Rotate only the non-negative elements of the array to the left by k positions, in a cyclic manner.

All negative elements must stay in their original positions and must not move.

After rotation, place the non-negative elements back into the array in the new order, filling only the positions that originally contained non-negative values and skipping all negative positions.

Return the resulting array.

Example 1:

Input: nums = [1,-2,3,-4], k = 3

Output: [3,-2,1,-4]

Explanation:

Example 2:

Input: nums = [-3,-2,7], k = 1

Output: [-3,-2,7]

Explanation:

Example 3:

Input: nums = [5,4,-9,6], k = 2

Output: [6,5,-9,4]

Explanation:

Constraints:

Solution

class Solution {
    fun rotateElements(nums: IntArray, k: Int): IntArray {
        var k = k
        val n = nums.size
        var m = 0
        val a = IntArray(n)
        for (x in nums) {
            if (x >= 0) {
                a[m++] = x
            }
        }
        if (m == 0) {
            return nums
        }
        k %= m
        var j = 0
        for (i in 0..<n) {
            if (nums[i] >= 0) {
                val index = (j + k) % m
                nums[i] = a[index]
                j++
            }
        }
        return nums
    }
}