1. Hash Set Tracking
Intuition
Iterate through nums. If x is in the set, remove it. Otherwise, add x. At the end of the array, the set contains only the single element.
When to apply: Basic demonstration of frequency tracking.
Algorithm
- Step 1: Create an empty set.
- Step 2: For each num: if in set, remove; else, add.
- Step 3: Return the only element remaining in the set.
#include <iostream>#include <vector>#include <unordered_set> using namespace std; int singleNumberSet(const vector<int>& nums) { unordered_set<int> s; for (int x : nums) { if (s.count(x)) s.erase(x); else s.insert(x); } return *s.begin();} int main() { vector<int> nums = {4, 1, 2, 1, 2}; cout << "Set: " << singleNumberSet(nums) << endl; // 4 return 0;}Time & Space Complexity
- Time complexity:
O(n) - Space complexity:
O(n)