1. Brute Force — Prefix Re-Scan (O(N^2))
Intuition
Maintain character frequencies. For each index i, iterate from 0 to i and find the first character with freq == 1.
Algorithm
- Step 1: Iterate through each character
A[i]. - Step 2: Update frequency of
A[i]. - Step 3: Scan
A[0...i]to find the first character with count == 1. - Step 4: Append found character, or
#if none found.
#include <iostream>#include <string>#include <vector> using namespace std; class Solution {public: string FirstNonRepeating(string A) { string res = ""; vector<int> freq(26, 0); for (int i = 0; i < A.size(); ++i) { freq[A[i] - 'a']++; char nonRep = '#'; for (int j = 0; j <= i; ++j) { if (freq[A[j] - 'a'] == 1) { nonRep = A[j]; break; } } res += nonRep; } return res; }}; int main() { Solution sol; cout << sol.FirstNonRepeating("aabc") << endl; // a#bb cout << sol.FirstNonRepeating("zz") << endl; // z# return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— For each character, scans the entire prefix to find the first character with count 1. - Space complexity:
O(1)— Uses frequency array of size 26.
Why Brute Force Doesn't Scale:
A stream of 105 characters requires 5 x 109 operations.
Queue with frequency array processes 105 characters in 12ms.