1. Brute Force — Auxiliary Array
Intuition
Copy all non-zero elements into a new array, then copy them back to nums and fill the remaining spots with zeros.
Algorithm
- Initialize an empty list
temp. - For each number
xinnums: - If
x != 0, appendxtotemp. - Copy elements from
temptonums[0 ... temp.length - 1]. - Fill
nums[temp.length ... nums.length - 1]with0.
Bubble Adjacent Swaps (O(N^2) Time)
2 of 2 questions left todayZero bubbles one position to the right
Zero bubbles one position to the right.
#include <iostream>#include <vector>using namespace std; // Brute Force: Auxiliary array copy (O(N) space)void moveZeroes(vector<int>& nums) { vector<int> temp; for (int num : nums) { if (num != 0) { temp.push_back(num); } } for (size_t i = 0; i < temp.size(); i++) { nums[i] = temp[i]; } for (size_t i = temp.size(); i < nums.size(); i++) { nums[i] = 0; }} int main() { vector<int> nums = {0, 1, 0, 3, 12}; moveZeroes(nums); cout << "Output: ["; for (size_t i = 0; i < nums.size(); i++) { cout << nums[i] << (i + 1 < nums.size() ? ", " : ""); } cout << "]" << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Approach 1: Brute Force — Auxiliary Array. - Space complexity:
O(1)— Space complexity for Approach 1: Brute Force — Auxiliary Array.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.