1. Hash Map Frequency Counting
Intuition
Count frequencies in a hash map. Iterate entries to locate the key with count == 1.
When to apply: Basic baseline.
Algorithm
- Step 1: Build frequency map.
- Step 2: Loop entries: if value == 1, return key.
#include <iostream>#include <vector>#include <unordered_map> using namespace std; int singleNumberBrute(const vector<int>& nums) { unordered_map<int, int> freq; for (int x : nums) freq[x]++; for (auto& p : freq) { if (p.second == 1) return p.first; } return -1;} int main() { vector<int> nums = {2, 2, 3, 2}; cout << "Brute: " << singleNumberBrute(nums) << endl; // 3 return 0;}Time & Space Complexity
- Time complexity:
O(n) - Space complexity:
O(n)