1. Nested Scanning (Brute Force)
Intuition
For each index i from 0 to n - 1, compare s[i] with every other character s[j] where j != i. If no match is found, s[i] is unique and we return i immediately. If all characters repeat, return -1.
When to apply: Exploratory concept only.
Algorithm
- Loop
ifrom0ton - 1: - Set
isUnique = true. - Loop
jfrom0ton - 1: - If
i != jands[i] == s[j]:isUnique = false; break. - If
isUniqueis true, returni. - Return -1.
Nested Scanning All Pairs Comparison Trace
2 of 2 questions left todayObservation: Fix outer pointer at candidate i = 0 ('l')
Observation: Fix outer pointer at candidate i = 0 ('l').
Decision: Scan remaining characters j = 1 through 7.
Invariant: If no s[j] == s[0], index 0 is the first non-repeating character.
#include <iostream>#include <string> class Solution {public: int firstUniqChar(std::string s) { int n = s.size(); for (int i = 0; i < n; ++i) { bool unique = true; for (int j = 0; j < n; ++j) { if (i != j && s[i] == s[j]) { unique = false; break; } } if (unique) return i; } return -1; }}; int main() { Solution sol; std::cout << sol.firstUniqChar("leetcode") << std::endl; // 0 std::cout << sol.firstUniqChar("loveleetcode") << std::endl; // 2 return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Nested loops examine all pairs of characters. - Space complexity:
O(1)
Why Brute Force Doesn't Scale:
Using a direct integer array index (char - 'a') eliminates hash table lookup overhead.
Only 26 integers of stack memory are used (O(1) space).