0
votes

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

This seems like a good time to learn how to debug your programs. For example by stepping through it statement by statement in a debugger while monitoring variables and their values. - Some programmer dude