1. Brute Force — Hash Set Deduplication
Intuition
Insert all elements into an ordered set / hash set to eliminate duplicates, then write unique values back into nums.
Algorithm
- Insert all elements of
numsinto an ordered setuniqueSet. - Let
k = 0. - For each value
valinuniqueSet: -
nums[k++] = val. - Return
k.
Hash Set Deduplication
2 of 2 questions left todayPhase 1 — Insert First Element: nums[0] is 0
Phase 1 — Insert First Element: nums[0] is 0. Insert into LinkedHashSet: seen = { 0 }.
#include <iostream>#include <set>#include <vector>using namespace std; // Brute Force: Set deduplication (O(N) space)int removeDuplicates(vector<int>& nums) { set<int> uniqueSet(nums.begin(), nums.end()); int k = 0; for (int val : uniqueSet) { nums[k++] = val; } return k;} int main() { vector<int> nums = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4}; int k = removeDuplicates(nums); cout << "k = " << k << ", nums = ["; for (int i = 0; i < k; i++) { cout << nums[i] << (i + 1 < k ? ", " : ""); } cout << "]" << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Approach 1: Brute Force — Hash Set Deduplication. - Space complexity:
O(1)— Space complexity for Approach 1: Brute Force — Hash Set Deduplication.
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.