Similar String Groups
Problem Statement
You get a list of words. Every word has the same length, and every word is an anagram of the others, so they all use the same letters.
Two words are similar when they are equal, or when swapping one pair of letters in one of them turns it into the other. Similar words are linked, and a group is a set of words that can reach each other through similar pairs. A word that is similar to nothing is a group on its own.
Return the number of groups.
strs: a list of words.
The number of groups.
tars and rats are similar, and rats and arts are similar, so those three form one group. star is not similar to any of them, so it is a second group.
Swapping the last two letters of omv gives ovm, so they are similar.
All three are anagrams, but every pair differs in three positions. No pair is similar, so each word is its own group.
acb and bac are not similar to each other, but both are similar to abc. The chain through abc puts all three in one group.
- • 1 <= strs.length <= 300
- • 1 <= strs[i].length <= 300
- • strs[i] consists of lowercase letters only
- • All words in strs have the same length and are anagrams of each other
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Repeat passes over the groups, merging any two groups that have a similar pair across them
Check each pair of words once; union the similar ones and count the groups left
Start with one group per word. Each pass compares pairs of groups, and merges two groups when some word in one is similar to some word in the other. Stop when a full pass merges nothing. The number of groups left is the answer.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Union-Find (DSU) translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.