1. Hash Map Frequency Counting
Intuition
Populate frequency map. Loop through map keys and append values with count == 1 to the result array.
When to apply: Simplicity when extra memory is allowed.
Algorithm
- Step 1: Build frequency map of all elements.
- Step 2: Filter elements with frequency == 1.
- Step 3: Sort result array and return.
#include <iostream>#include <vector>#include <unordered_map>#include <algorithm> using namespace std; vector<int> findTwoNonRepeatingBrute(const vector<int>& nums) { unordered_map<int, int> freq; for (int x : nums) freq[x]++; vector<int> res; for (auto& p : freq) { if (p.second == 1) res.push_back(p.first); } sort(res.begin(), res.end()); return res;} int main() { vector<int> nums = {1, 2, 3, 2, 1, 4}; auto res = findTwoNonRepeatingBrute(nums); cout << "Brute: " << res[0] << ", " << res[1] << endl; // 3, 4 return 0;}Time & Space Complexity
- Time complexity:
O(n) - Space complexity:
O(n)