Extra Space solution
Time Complexity: O(n)
First loop: Iterates through all n elements of the input array once
Second loop: Iterates through all n elements to copy back to the original array
Total: O(n) + O(n) = O(n)
Space Complexity: O(n)
Creates a new array newArray of size n (same as input array)
Uses constant extra space for variables i and j
Total: O(n) auxiliary space
-
class Solution {
public void moveZeroes(int[] nums) {
int[] newArray = new int[nums.length];
int j = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0)
continue;
newArray[j] = nums[i];
j++;
}
for (int i = 0; i < newArray.length; i++) {
nums[i] = newArray[i];
}
}
}
-
In-place solution
Time Complexity: O(n)
First loop: Iterates through all n elements once - O(n)
Second loop: In worst case, fills remaining positions with zeros
Maximum iterations: n - (number of non-zeros)
Still bounded by O(n)
Total: O(n) + O(n) = O(n)
Space Complexity: O(1)
No auxiliary data structures created
Only uses a constant amount of extra variables:
overwrite (integer)
i (loop counter integer)
class Solution {
public void moveZeroes(int[] nums) {
int overwrite = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[overwrite] = nums[i];
overwrite++;
}
}
while (overwrite < nums.length) {
nums[overwrite] = 0;
overwrite++;
}
}
}
Top comments (0)