1. Pairwise Anagram Comparison
Intuition
Maintain a boolean visited array. For each unvisited string strs[i], start a new group with strs[i]. Iterate j from i + 1 to n - 1: if strs[j] is unvisited and is an anagram of strs[i], add it to the current group and mark visited[j] = true. Append the group to the final result.
When to apply: Exploratory naive baseline.
Algorithm
- Initialize
visited = [false] * nandresult = []. - Loop
ifrom 0 ton - 1: - If
visited[i]is true, continue. - Create
group = [strs[i]]and markvisited[i] = true. - Loop
jfromi + 1ton - 1: - If
!visited[j]andisAnagram(strs[i], strs[j]), addstrs[j]togroupand markvisited[j] = true. - Add
grouptoresult. - Return
result.
Pairwise Anagram Comparison
2 of 2 questions left todayObservation: Track visited array of size 6
Observation: Track visited array of size 6. First unvisited word is strs[0] = 'eat'.
Decision: Create Group 1 with 'eat'. Now scan all subsequent unvisited words.
Invariant: Words assigned to a group are marked visited to prevent duplicate grouping.
#include <iostream>#include <string>#include <vector> class Solution { bool isAnagram(const std::string& a, const std::string& b) { if (a.size() != b.size()) return false; int count[26] = {0}; for (char c : a) count[c - 'a']++; for (char c : b) { if (--count[c - 'a'] < 0) return false; } return true; }public: std::vector<std::vector<std::string>> groupAnagrams(std::vector<std::string>& strs) { int n = strs.size(); std::vector<bool> visited(n, false); std::vector<std::vector<std::string>> result; for (int i = 0; i < n; ++i) { if (visited[i]) continue; std::vector<std::string> group; group.push_back(strs[i]); visited[i] = true; for (int j = i + 1; j < n; ++j) { if (!visited[j] && isAnagram(strs[i], strs[j])) { group.push_back(strs[j]); visited[j] = true; } } result.push_back(group); } return result; }}; int main() { Solution sol; std::vector<std::string> strs = {"eat","tea","tan","ate","nat","bat"}; auto ans = sol.groupAnagrams(strs); for (const auto& grp : ans) { std::cout << "[ "; for (const auto& w : grp) std::cout << w << " "; std::cout << "] "; } std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2 * K)— Takes O(N2) pairwise comparisons, each taking O(K) time. - Space complexity:
O(N * K)
Why Brute Force Doesn't Scale:
Using a 26-tuple / count string bypasses comparison sorting entirely, dropping time from O(N * K log K) to O(N * K).
Reusing a single 26-element buffer for count generation minimizes GC pressure.