Similar String Groups solution explained

Similar String Groups gives you a list of strings that are all rearrangements of the same letters and calls two strings similar if they are equal or one swap of two positions turns one into the other. Groups form by chaining similar pairs, and you must count the groups. Compare every pair, link similar ones with union-find, and count the roots: O(n² × m) time for n strings of length m.

By Published 8 min read

The problem in plain words

You get n strings, each of length m, and every string uses exactly the same multiset of letters in some order. Call two strings similar if they are identical, or if exchanging the letters at two positions in one of them produces the other. A group is a set of strings where each one can reach every other through a chain of similar pairs, even if two members are not similar to each other directly. Return how many groups there are.

Word lists written for this page
StringsGroupsWhy
"abcd", "bacd", "bcad", "dcba"2abcd and bacd swap the first two letters, bacd and bcad swap the middle two. dcba differs from each of them in three or four places
"lemon", "melon", "lemon"1lemon and melon swap the l and the m. The two copies of lemon are equal, so they are similar too
"abc", "bca", "cab"3Every pair differs in all three positions, which one swap cannot fix
"aabb", "abab", "bbaa"1aabb and bbaa differ in four places, but abab is one swap from each, so the chain joins them
"xyz"1One string is one group
Word lists written for this page. Scroll sideways on a small screen.

What the interviewer is checking

Two separate skills are tested. First, can you write the similarity test correctly and cheaply: count mismatched positions and stop early once there are more than two. Second, do you recognize that groups are connected components of an implied graph, where you never build the edges up front? The interviewer also likes to hear you weigh the n² pairwise approach against generating neighbours, because which is faster depends on whether you have many short strings or a few long ones.

The similarity test

Walk both strings and record the positions where they differ. Zero differences means equal, so similar. Exactly two differences at positions i and j means similar if a[i] equals b[j] and a[j] equals b[i]. Any other count means not similar. When every string is a rearrangement of the same letters, two mismatches are always crossed, so many solutions skip that last check. Keeping it costs almost nothing and makes the function correct for any pair of equal-length strings.

Brute force: literally try every swap

The definition says "one swap turns one into the other", so the most direct test swaps every pair of positions in the first string and compares the result with the second. That costs O(m²) swaps, each with an O(m) comparison, for every pair of strings. Then a breadth-first search over string indices counts the groups. It is correct and easy to trust, which makes it a good checker.

from collections import deque

def count_groups_slow(words):
    def one_swap_apart(a, b):
        if a == b:
            return True
        letters = list(a)
        for i in range(len(a)):
            for j in range(i + 1, len(a)):
                letters[i], letters[j] = letters[j], letters[i]
                if "".join(letters) == b:
                    return True
                letters[i], letters[j] = letters[j], letters[i]
        return False

    n = len(words)
    seen = [False] * n
    groups = 0
    for s in range(n):
        if seen[s]:
            continue
        groups += 1
        seen[s] = True
        queue = deque([s])
        while queue:
            cur = queue.popleft()
            for other in range(n):
                if not seen[other] and one_swap_apart(words[cur], words[other]):
                    seen[other] = True
                    queue.append(other)
    return groups
Python: similarity by trying every swap, then BFS. O(n² × m³), for checking.

Optimal: union-find with a linear similarity test

Replace the swap loop with a single scan that counts mismatches and exits early. Then, for every pair of strings i < j, if they are already in the same group skip the comparison, otherwise test similarity and merge on success. Each merge lowers the group count by one. The early skip does not change the worst case, but in practice it avoids many comparisons once large groups have formed.

def count_groups(words):
    def similar(a, b):
        diff = []
        for i, (x, y) in enumerate(zip(a, b)):
            if x != y:
                diff.append(i)
                if len(diff) > 2:
                    return False
        if not diff:
            return True
        if len(diff) != 2:
            return False
        i, j = diff
        return a[i] == b[j] and a[j] == b[i]

    n = len(words)
    link = list(range(n))

    def find(x):
        while link[x] != x:
            link[x], x = link[link[x]], link[x]   # path splitting
        return x

    groups = n
    for i in range(n):
        for j in range(i + 1, n):
            ri, rj = find(i), find(j)
            if ri != rj and similar(words[i], words[j]):
                link[rj] = ri
                groups -= 1
    return groups
Python: union-find over indices, early-exit similarity test

Checking find(i) != find(j) before calling similar is the cheap test first and the expensive test second. Duplicates are handled by the zero-mismatch branch, so two copies of a word always land in the same group.

function countGroups(words) {
  const similar = (a, b) => {
    let first = -1, second = -1, count = 0;
    for (let i = 0; i < a.length; i++) {
      if (a[i] !== b[i]) {
        count++;
        if (count > 2) return false;
        if (first === -1) first = i; else second = i;
      }
    }
    if (count === 0) return true;
    return count === 2 && a[first] === b[second] && a[second] === b[first];
  };

  const n = words.length;
  const seen = new Uint8Array(n);
  let groups = 0;
  for (let s = 0; s < n; s++) {
    if (seen[s]) continue;
    groups++;
    seen[s] = 1;
    const queue = [s];
    for (let head = 0; head < queue.length; head++) {
      const cur = queue[head];
      for (let other = 0; other < n; other++) {
        if (!seen[other] && similar(words[cur], words[other])) {
          seen[other] = 1;
          queue.push(other);
        }
      }
    }
  }
  return groups;
}
JavaScript: the same components, found with BFS and the same similarity test

The breadth-first version keeps a head index instead of calling shift, which would make each dequeue O(n). It compares each newly reached string with every unvisited one, so it does at most n² similarity tests, the same bound as union-find.

When the strings are short: generate neighbours

If there are very many strings but each is short, n² pairs is the bottleneck. Flip it around: put all distinct strings in a hash set, and for each string generate every single-swap variant (m² / 2 of them, each built in O(m)) and look it up. Any hit is an edge. That costs about O(n × m³) instead of O(n² × m), which is better when m² is much smaller than n. Mentioning this trade-off, even without coding it, usually impresses.

Complexity

n strings, each of length m
ApproachTimeExtra space
Try every swap for every pair, then BFSO(n² × m³)O(n + m)
Pairwise early-exit test with union-find or BFSO(n² × m)O(n)
Generate every swap of each string and look it upO(n × m³)O(n × m) for the set
n strings, each of length m. Scroll sideways on a small screen.

Edge cases

  • Duplicate strings: equal means similar, so they share a group.
  • A single string: one group.
  • Strings of length one: all equal (since they are rearrangements of one letter), so one group.
  • Strings with repeated letters, such as aabb: a swap of two identical letters changes nothing, and the mismatch count still works.
  • Two strings that differ in exactly two places without crossing (only possible if they are not rearrangements of each other): the crossed-letter check rejects them.

Common mistakes

  • Treating similarity as transitive and grouping only direct pairs, which misses chains like aabb, abab, bbaa.
  • Counting mismatches without an early exit, which wastes time on long strings.
  • Forgetting that equal strings are similar, which splits duplicates into separate groups.
  • Using the generate-neighbours approach without removing duplicates, so a string finds itself or its copy and miscounts.
  • Calling shift on a JavaScript array as a queue inside the nested loop, adding hidden O(n) work.

Follow-up questions

  • Return the groups, not just the count. Collect indices by their root after union-find.
  • Two swaps are allowed. The mismatch count can now be up to four, and the check becomes whether the mismatched letters can be fixed with two exchanges.
  • Strings arrive one at a time. Union-find absorbs each new string, but comparing it with one representative per group is not enough, because similarity is not transitive. Compare it with every earlier string, or generate its swaps and look them up in a set of the strings seen so far.
  • Which approach for 10,000 strings of length 5? Neighbour generation: 10 swaps per string beats 50 million pairs.

How to explain it out loud

Fictional example

Components of a graph you never build
Candidate
Each string is a node, and there's an edge if two strings are equal or one swap apart. The answer is the number of connected components.
Candidate
To test an edge I walk both strings, note where they differ, and stop if it's more than two. Two differences have to be crossed letters.
Interviewer
What if aabb and bbaa aren't similar directly?
Candidate
They can still be in one group through abab. That's why I use union-find over all pairs instead of grouping direct matches.
Candidate
That's n squared pairs times m. If there were tons of short strings I'd generate swaps and use a hash set instead.

Satisfiability of Equality Equations groups items with union-find when the links are given directly. Number of Operations to Make Network Connected also counts components and then reasons about them. For a component count where neighbours come from a grid, try Regions Cut by Slashes.

Practicing it with Natively

The pairwise versus neighbour-generation trade-off is the part candidates forget to raise. While you rehearse on a Mac or Windows PC, Natively can read the word list from a screenshot, suggest the early-exit similarity test and the union-find plan, and keep a transcript of your explanation so you can confirm you discussed the chained-group case. See the AI interview assistant page for how practice sessions work.

Questions people ask

How do you solve Similar String Groups?

Compare every pair of strings. Two are similar if they are equal or differ in exactly two crossed positions. Link similar pairs with union-find and count the remaining roots.

Why are groups not just pairs of similar strings?

Similarity is not transitive, but groups are formed by chains. Two strings that differ in four places can still share a group through a third string one swap from each.

What is the time complexity of Similar String Groups?

O(n² × m) for n strings of length m with pairwise comparison, and O(n) extra space for union-find.

When is generating swaps faster?

When there are many short strings. Generating every swap of each string and looking it up in a set costs about O(n × m³), which beats n² pairs when m is small.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP