Duplicate Zeros LeetCode solution in Java

1
class Solution {
2

3
// Time Complexity = O(n)
4
// Space Complexity = O(1)
5

6
public void duplicateZeros(int[] arr) {
7

8
// Loop through the array
9
for (int i = 0; i < arr.length; i++) {
10

11
// Trigger Condition
12
if (arr[i] == 0) {
13
int j; // auxilliary variable for swapping
14
for (j = arr.length - 2; j >= i + 1; j--) {
15
arr[j + 1] = arr[j]; // Shift each element by one space
16
}
17
arr[j + 1] = 0; // Duplicating the zero on the consecutive index of i
18
i++; // Skipping the duplicated zero index in the array
19
}
20
}
21
}
22
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0