Move Zeroes

Move Zeroes

Move Zeroes

Problem Statement:

Given an array of integers, move all zeroes to the end of the array while maintaining the relative order of non-zero elements.

Input Example:

nums = [0, 1, 0, 3, 12]

Output Example:

[1, 3, 12, 0, 0]

Solution:

fun main() {
    val arr = arrayOf(0, 1, 0, 3, 12)

    var nonZeroIndex = 0

    for (i in arr.indices) {
        if (arr[i] != 0) {
            arr[nonZeroIndex] = arr[i]
            nonZeroIndex++
        }
    }

    for (i in nonZeroIndex until arr.size) {
        arr[i] = 0
    }

    println(arr.contentToString())
}