LeetCode in Kotlin

3940. Limit Occurrences in Sorted Array

Easy

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

Return an array such that each distinct element appears at most k times, while preserving the relative order of the elements in nums.

Note: If a distinct element appears at least k times, then it must appear exactly k times in the resulting array.

Example 1:

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

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

Explanation:

Each element can appear at most 2 times.

Thus, the resulting array is [1, 1, 2, 2, 3].

Example 2:

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

Output: [1,2,3]

Explanation:

All elements are distinct and already appear at most once, so the array remains unchanged.

Constraints:

Follow-up:

Solution

class Solution {
    fun limitOccurrences(nums: IntArray, k: Int): IntArray {
        val ls: MutableList<Int?> = ArrayList<Int?>()
        ls.add(nums[0])
        var freq = 1
        for (i in 1..<nums.size) {
            if (nums[i] == nums[i - 1]) {
                freq++
            } else {
                freq = 1
            }
            if (freq <= k) {
                ls.add(nums[i])
            }
        }
        val ans = IntArray(ls.size)
        for (i in ls.indices) {
            ans[i] = ls[i]!!
        }
        return ans
    }
}