Home > other >  Duplicate Zeros in Kotlin
Duplicate Zeros in Kotlin

Time:07-31

I am solving a array question.

Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.

Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.

Example 1:

Input: arr = [1,0,2,3,0,4,5,0]
Output: [1,0,0,2,3,0,0,4]

Example 2:

Input: arr = [1,2,3]
Output: [1,2,3]

I tried this solution but I am getting wrong output

class Solution {
    fun duplicateZeros(arr: IntArray): Unit {
        arr.forEachIndexed { index, value ->
            if(value == 0 && ((arr.size - 1) != index)) {
                arr[index   1] = 0
            }
        }
    }
}

Actual Output

[1,0,0,0,0,0,0,0]

Expected Output

[1,0,0,2,3,0,0,4]

Note please don't make copy of array. I want to solve in same array. Can someone guide me where is my logic is wrong and how can I fix the problem?

Thanks

CodePudding user response:

I tried this solution

fun main() {
    val nums = intArrayOf(1, 0, 2, 3, 0, 4, 5, 0)
    var extraSpace = 0
    var startingPoint = nums.lastIndex
    for (i in 0..nums.lastIndex) {
        if (nums[i] == 0) {
            if (i < nums.lastIndex - extraSpace)
                extraSpace  
        }
    }
    var tempIndex = startingPoint
    while (tempIndex >= 0) {
        if (nums[tempIndex - extraSpace] == 0) {
            nums[tempIndex] = 0
            extraSpace--
            tempIndex--
            nums[tempIndex] = 0
        } else {
            nums[tempIndex] = nums[tempIndex - extraSpace]
        }

        tempIndex--
    }
    
    nums.forEach { print("$it ") }
}

CodePudding user response:

Just for the fun of it, will the below code be accepted as a valid answer by your learning institution (I'm assuming that you're doing some homework)? It meets the requirements, but is of course in the grey-zone because of the temporary accumulator. Please do not accept this answer or upvote it.

given("a StackOverflow issue") {

    val expectedArray = arrayOf(1, 0, 0, 2, 3, 0, 0, 4)

    `when`("duplicating") {

        val arr = intArrayOf(1, 0, 2, 3, 0, 4, 5, 0)

        arr.fold(mutableListOf<Int>()) { accumulator, item ->
            accumulator.also { innerAcc -> repeat(if (item == 0) 2 else 1) { innerAcc.add(item) } }
        }.also { it.take(arr.size).toIntArray().copyInto(arr) }

        then("result should be as expected") {
            arr shouldBe expectedArray
        }
    }
}
  • Related