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
UPDATE
I tried the code and some test case is working fine and long one is not working correctly..
fun main() {
// val nums = intArrayOf(1, 0, 2, 3, 0, 4, 5, 0)
// val nums = intArrayOf(0, 0, 0, 0, 0, 0, 0)
// val nums = intArrayOf(8, 4, 5, 0, 0, 0, 0, 7)
val nums = longTestCase()
var extraSpace = 0
var temp = nums.lastIndex
for (i in nums.indices) {
if (nums[i] == 0) {
if (i < nums.lastIndex - extraSpace) {
extraSpace++
}
}
}
while (temp >= 0) {
if (nums[temp - extraSpace] == 0 && extraSpace > 0) {
nums[temp] = 0
extraSpace--
temp--
if (temp >= 0) {
nums[temp] = 0
}
} else {
nums[temp] = nums[temp - extraSpace]
}
temp--
}
nums.forEach { print("$it ") }
}
private fun longTestCase(): IntArray {
return intArrayOf(
9,
9,
9,
4,
8,
0,
0,
3,
7,
2,
0,
0,
0,
0,
9,
1,
0,
0,
1,
1,
0,
5,
6,
3,
1,
6,
0,
0,
2,
3,
4,
7,
0,
3,
9,
3,
6,
5,
8,
9,
1,
1,
3,
2,
0,
0,
7,
3,
3,
0,
5,
7,
0,
8,
1,
9,
6,
3,
0,
8,
8,
8,
8,
0,
0,
5,
0,
0,
0,
3,
7,
7,
7,
7,
5,
1,
0,
0,
8,
0,
0
)
}
Actual Output
[9,9,9,4,8,0,0,0,3,7,2,0,0,0,0,0,0,0,0,9,1,0,0,0,0,1,1,0,0,5,6,3,1,6,0,0,0,0,2,3,4,7,0,0,3,9,3,6,5,8,9,1,1,3,2,0,0,0,0,7,3,3,0,0,5,7,0,0,8,1,9,6,3,0,0,8,8,8,8,0,0]
Expected output
[9,9,9,4,8,0,0,0,0,3,7,2,0,0,0,0,0,0,0,0,9,1,0,0,0,0,1,1,0,0,5,6,3,1,6,0,0,0,0,2,3,4,7,0,0,3,9,3,6,5,8,9,1,1,3,2,0,0,0,0,7,3,3,0,0,5,7,0,0,8,1,9,6,3,0,0,8,8,8,8,0]