Sponsored
Sponsored
This approach uses two pointers: one to track the position for the next non-zero element and the other to iterate through the array. We move all non-zero elements to the beginning of the array using these two pointers and fill the remaining positions with zeroes.
Time Complexity: O(n), where n is the length of the array. We make a single pass through the array.
Space Complexity: O(1), as we perform the operation in place.
1public class Solution {
2 public void MoveZeroes(int[] nums) {
3 int lastNonZeroFoundAt = 0;
4 for (int i = 0; i < nums.Length; i++) {
5 if (nums[i] != 0) {
6 nums[lastNonZeroFoundAt++] = nums[i];
7 }
8 }
9 for (int i = lastNonZeroFoundAt; i < nums.Length; i++) {
10 nums[i] = 0;
11 }
12 }
13}In this C# solution, we use the same two-pointer method. The variable lastNonZeroFoundAt keeps track of the position at which the next non-zero element should be placed.
This method uses a two-pointer technique where we place one pointer at the beginning of the array and the other to iterate through the array. Whenever we encounter a non-zero element, we swap it with the first pointer's position, allowing us to effectively move zeroes to the end by swapping.
Time Complexity: O(n), single iteration with swaps.
Space Complexity: O(1), in-place swaps.
1publicThis implementation uses a similar swap approach, where we only swap elements when a non-zero is found, using a secondary pointer j to track swap positions.