Move All Zeros to End
C++
Hard
8 views
Problem Description
Shift all zero elements to the end while maintaining order of non-zero elements. This teaches two-pointer technique.
Logic: Use index to place non-zero elements, fill rest with zeros
Official Solution
void question12_move_zeros() {
int arr[] = {0, 5, 0, 3, 0, 1};
int size = 6;
int index = 0;
for(int i = 0; i < size; i++) {
if(arr[i] != 0) {
arr[index++] = arr[i];
}
}
while(index < size) {
arr[index++] = 0;
}
cout << "Array after moving zeros: ";
for(int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!