Word-Set Jaccard Index of Two Strings

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Write a function jaccard_similarity(a: str, b: str) -> float that quantifies the lexical overlap between two strings a and b using the Jaccard index over their distinct alphabetic words.

To extract the word set from a string: 1. Lowercase every alphabetic letter so capitalization does not distinguish words. 2. Treat any non-alphabetic character (not ch.isalpha() — including whitespace, digits, punctuation, underscores, hyphens, and apostrophes) as a word boundary. 3. Ignore empty substrings between consecutive boundaries, and collapse repeated occurrences so each string produces a mathematical set of unique words.

Given word set W_a from a and word set W_b from b, return their Jaccard index as a float: - When W_a and W_b are both empty, return 1.0. - Otherwise, return |W_a ∩ W_b| / |W_a ∪ W_b| — the count of words appearing in both sets divided by the count of distinct words appearing in at least one set.

Examples

Example 1

Input:
  a = "Red_apple, green APPLE!"
  b = "Green pear & red2plum"

Output:
  0.4

Walk-through: - Splitting on non-letters (_, ,, spaces, !, &, 2) and lowercasing gives W_a = {"red", "apple", "green"} (the second "apple" is deduplicated) and W_b = {"green", "pear", "red", "plum"}. - W_a ∩ W_b = {"red", "green"} has 2 words, and W_a ∪ W_b = {"red", "apple", "green", "pear", "plum"} has 5 words, yielding 2 / 5 = 0.4.

Example 2

Input:
  a = "2026 -- ??"
  b = "   ...   "

Output:
  1.0

Walk-through: - Neither input contains any alphabetic characters, so W_a = set() and W_b = set(). Two empty word sets have similarity 1.0 by definition.

Constraints

  • 0 <= len(a), len(b) <= 10^5
  • a and b may contain uppercase and lowercase letters, digits, whitespace, and punctuation/symbols.

Step-by-step walkthrough

  1. Understand the goal and word-extraction rules

    We receive two strings a and b and want to measure what fraction of their combined vocabulary appears in both strings, on a scale from 0.0 to 1.0.

    First, each string is turned into a set of unique words (tokenization):

    1. Lowercase all letters so "APPLE" and "apple" match.
    2. Cut the string at every non-alphabetic character — spaces, commas, digits, underscores, hyphens, and apostrophes all separate words.
    3. Drop empty pieces and deduplicate repeated words.

    Then we compute the Jaccard index: the count of words present in both sets divided by the count of distinct words present in either set:

    a = "Red_apple, green APPLE!"  -->  tokens_a = {"red", "apple", "green"}
    b = "Green pear & red2plum"    -->  tokens_b = {"green", "pear", "red", "plum"}
    
    Shared words (intersection):  {"red", "green"}                        -> 2 words
    All distinct words (union):   {"red", "apple", "green", "pear", "plum"} -> 5 words
    Jaccard index:                2 / 5 = 0.4
    

    When neither input contains any letters at all (as in Example 2: "2026 -- ??" and " ... "), both sets are empty. Dividing 0 / 0 would raise an error, so two empty word sets are defined to have similarity 1.0.

  2. Why quick splitting shortcuts fail

    It is tempting to reach for text.lower().split() or a regex like \w+, but both violate the word-boundary specification:

    • text.split() splits only on whitespace. Punctuation stays attached to neighboring letters, turning "apple," and "apple!" into distinct tokens.
    • Regex \w+ and str.isalnum() keep digits and underscores. On "Red_apple" or "red2plum", \w+ leaves everything glued into one token instead of breaking on '_' and '2'.

    Scanning the lowercased string one character at a time and testing ch.isalpha() handles spaces, punctuation, digits, and symbols with one uniform rule: letters extend the current word, and any other character finishes it.

  3. Build the character-by-character tokenizer

    As we iterate over text.lower(), we maintain a list current_chars holding the letters of the word currently being assembled:

    • When ch.isalpha() is True, append ch to current_chars.
    • When ch.isalpha() is False, we reached a delimiter. If current_chars is non-empty, join its letters into a word, insert it into tokens, and reset current_chars = []. If current_chars is already empty (for instance across consecutive delimiters like ", "), do nothing — skipping empty tokens automatically.
    • After the loop finishes, flush current_chars one last time if the string ended with a letter rather than a delimiter.
    Trace on text = "Hi, go" (lowercased to "hi, go"):
    
      ch    isalpha?   action                        current_chars   tokens
      ---   --------   ---------------------------   -------------   ------------
      'h'   True       append 'h'                    ['h']           set()
      'i'   True       append 'i'                    ['h', 'i']      set()
      ','   False      flush "hi", reset list        []              {'hi'}
      ' '   False      current_chars empty -> skip   []              {'hi'}
      'g'   True       append 'g'                    ['g']           {'hi'}
      'o'   True       append 'o'                    ['g', 'o']      {'hi'}
      end   ---        post-loop flush "go"          []              {'hi', 'go'}
    

    Here is the helper function:

    def tokenize(text: str) -> Set[str]:
        """Extract the set of unique lowercase alphabetic words from text."""
        # tokens: set of unique lowercase words seen so far, e.g. {"red", "apple", "green"}
        tokens: Set[str] = set()
        # current_chars: letters of the word currently being scanned, e.g. ["r", "e", "d"]
        current_chars: List[str] = []
    
        # Phase 1: Scan character by character so every non-letter acts as a separator.
        for ch in text.lower():
            if ch.isalpha():
                current_chars.append(ch)
            elif current_chars:
                # Checking `elif current_chars` skips empty tokens when multiple
                # separators appear in a row (like ", ") or at the start of the string.
                tokens.add("".join(current_chars))
                current_chars = []
    
        # Phase 2: Flush the final word if the string ended with a letter (no trailing separator).
        if current_chars:
            tokens.add("".join(current_chars))
    
        return tokens
    
  4. Compute the ratio with Python set operations

    Once tokens_a and tokens_b are set objects, check the empty-both-sides guard first: if not tokens_a and not tokens_b, return 1.0 right away.

    Otherwise, at least one set contains a word, so their union has size at least 1 and division cannot fail:

    • tokens_a & tokens_b computes the intersection (words in both sets).
    • tokens_a | tokens_b computes the union (distinct words in either set).
    • Python 3's / operator always returns a float, so 2 / 5 evaluates to 0.4, and 0 / len(all_tokens) returns 0.0 whenever only one side has words or the sets are disjoint.
    def jaccard_similarity(a: str, b: str) -> float:
        # Phase 1: Convert both input strings into sets of unique lowercase tokens.
        tokens_a = tokenize(a)
        tokens_b = tokenize(b)
    
        # Edge case: both sets are empty -> 0 / 0 is undefined, and the rule defines this as 1.0.
        if not tokens_a and not tokens_b:
            return 1.0
    
        # Phase 2: Compute intersection (words in both) and union (words in either).
        common_tokens = tokens_a & tokens_b
        all_tokens = tokens_a | tokens_b
    
        return len(common_tokens) / len(all_tokens)
    
  5. Trace Example 1 and Example 2

    Let's verify both statement examples step by step:

    Example 1: Mixed case, duplicates, underscore, punctuation, and digits
      a = "Red_apple, green APPLE!"  -->  tokens_a = {"red", "apple", "green"}
      b = "Green pear & red2plum"    -->  tokens_b = {"green", "pear", "red", "plum"}
      common_tokens                  -->  {"red", "green"}                       (size 2)
      all_tokens                     -->  {"red", "apple", "green", "pear", "plum"} (size 5)
      similarity                     -->  2 / 5 = 0.4
    
    Example 2: Digits, spaces, and punctuation only (zero letters)
      a = "2026 -- ??"               -->  tokens_a = set()
      b = "   ...   "                -->  tokens_b = set()
      both empty                     -->  returns 1.0 immediately
    
  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def tokenize(text: str) -> Set[str]:
        """Extract the set of unique lowercase alphabetic words from text."""
        # tokens: set of unique lowercase words seen so far, e.g. {"red", "apple", "green"}
        tokens: Set[str] = set()
        # current_chars: letters of the word currently being scanned, e.g. ["r", "e", "d"]
        current_chars: List[str] = []
    
        # Phase 1: Scan character by character so every non-letter acts as a separator.
        for ch in text.lower():
            if ch.isalpha():
                current_chars.append(ch)
            elif current_chars:
                # Checking `elif current_chars` skips empty tokens when multiple
                # separators appear in a row (like ", ") or at the start of the string.
                tokens.add("".join(current_chars))
                current_chars = []
    
        # Phase 2: Flush the final word if the string ended with a letter (no trailing separator).
        if current_chars:
            tokens.add("".join(current_chars))
    
        return tokens
    
    
    def jaccard_similarity(a: str, b: str) -> float:
        # Phase 1: Convert both input strings into sets of unique lowercase tokens.
        tokens_a = tokenize(a)
        tokens_b = tokenize(b)
    
        # Edge case: both sets are empty -> 0 / 0 is undefined, and the rule defines this as 1.0.
        if not tokens_a and not tokens_b:
            return 1.0
    
        # Phase 2: Compute intersection (words in both) and union (words in either).
        common_tokens = tokens_a & tokens_b
        all_tokens = tokens_a | tokens_b
    
        return len(common_tokens) / len(all_tokens)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine comparing two grocery lists to see how much overlap they share. Even if one list repeats "APPLE!" in all caps with messy punctuation, you would first normalize each list down to unique lowercase words and then ask: out of all distinct words appearing on either list, what fraction appear on both? That ratio is Jaccard similarity — a set-overlap metric ranging from 0.0 (disjoint sets) to 1.0 (identical sets). To compute it cleanly, we perform tokenization (chopping raw text into normalized word units called tokens) and store each string's words in a hash set (an unordered collection of unique items backed by a hash table so membership lookups run in O(1) average time). Then we divide the size of the set intersection (items present in both sets) by the size of the set union (distinct items present in at least one set).

Why do quick one-line splitting tricks fail? Calling text.split() splits only on whitespace, leaving punctuation glued to letters so "apple," and "apple!" look like different words. Using a regex like \w+ or str.isalnum() treats digits and underscores as word characters instead of boundaries, failing to break "Red_apple" or "red2plum" at '_' and '2'. Finally, storing words in plain lists instead of hash sets both double-counts duplicates and slows overlap checks to quadratic scans.

Let's trace Example 1 (a = "Red_apple, green APPLE!" and b = "Green pear & red2plum") step by step:

1. Lowercase and scan alphabetic runs in `a`:
   "red_apple, green apple!"  -->  words: "red", "apple", "green", "apple"
   Deduplicate in set         -->  tokens_a = {"red", "apple", "green"}

2. Lowercase and scan alphabetic runs in `b`:
   "green pear & red2plum"    -->  tokens_b = {"green", "pear", "red", "plum"}

3. Intersect and unite:
   common_tokens = tokens_a & tokens_b = {"red", "green"}                       (2 words)
   all_tokens    = tokens_a | tokens_b = {"red", "apple", "green", "pear", "plum"} (5 words)

4. Divide sizes:
   2 / 5 = 0.4

Complexity

Let n be the length of a and m be the length of b.

  • Time: O(n + m) expected. We scan the n characters of a and m characters of b once to lowercase each character, test isalpha(), and append letters to current_chars. Each completed word is joined and hashed once, so the total character work across all tokens is at most n + m. Finally, & and | perform one O(1) expected-time hash lookup per unique word (Python caches each string's hash value when created, so hashes are not recomputed during set operations).
  • Space: O(n + m). The lowercased strings, current_chars, and the sets tokens_a, tokens_b, common_tokens, and all_tokens together hold at most O(n + m) characters.

Edge cases

  • No letters in either string ("", "2026 -- ??", " ... "): both tokens_a and tokens_b are empty, and the early guard returns 1.0 instead of dividing 0 by 0.
  • No letters on one side only ("hello" vs "42"): the union is non-empty while the intersection is empty, so len(common_tokens) / len(all_tokens) cleanly returns 0.0.
  • Repeated words and mixed case ("Hello hello HELLO"): lowercasing and storing tokens in a set collapses all copies into the single word "hello".
  • Digits, underscores, hyphens, and apostrophes: none of these satisfy isalpha(), so "don't" splits into {"don", "t"} and "e-mail" splits into {"e", "mail"} (which shares zero words with {"email"}).
  • Leading, trailing, or consecutive separators (",,a,,b,,"): elif current_chars ensures we only emit a word when at least one letter has been collected, skipping empty pieces.
  • Accented Unicode letters: str.isalpha() returns True for Unicode letters such as 'é', keeping accented words intact. In an interview, confirm whether inputs are ASCII-only ('a'–'z') or general Unicode text.

Common mistakes

  • Splitting only on whitespace (text.split()): punctuation stays attached to neighboring words, so "APPLE!" in Example 1 becomes "apple!" instead of "apple", and "Red_apple," stays one token "red_apple,".
  • Using \w+ or str.isalnum(): \w matches digits and '_', and isalnum() matches digits, so neither splits "Red_apple" at '_' or "red2plum" at '2'.
  • Forgetting to flush after the loop: if you only add "".join(current_chars) when hitting a non-letter, any string ending with a letter silently loses its last word.
  • Forgetting the empty-both-sides guard: computing len(common_tokens) / len(all_tokens) directly raises ZeroDivisionError on ("", "") or Example 2.
  • Counting list overlaps instead of set overlaps: duplicate words inflate the numerator or denominator and break the set semantics.

Alternative approaches

  • Replace non-letters with spaces, then .split(): map every character where not ch.isalpha() to " " and run set("".join(...).split()). This has the same O(n + m) time and space and is concise, though it allocates one extra intermediate character list and joined string before splitting.
  • ASCII regular expression (re.findall(r"[a-z]+", text.lower())): compact when inputs are strictly ASCII English letters, though unlike str.isalpha() it treats accented letters like 'é' as delimiters.
  • Avoid allocating the union set via inclusion-exclusion: by the inclusion-exclusion principle (a counting identity stating that |A ∪ B| = |A| + |B| - |A ∩ B| because shared items were counted once in each set), we can compute union_size = len(tokens_a) + len(tokens_b) - len(common_tokens) and iterate over the smaller set to count common_tokens with zero extra set allocations.

Follow-up questions

  • How would you adapt the metric if word frequency matters rather than just presence or absence? Switch to weighted (multiset) Jaccard similarity, where a multiset tracks how many times each word occurs (for example with Python's collections.Counter). Across every distinct word in either string, sum min(count_a[w], count_b[w]) for the numerator and max(count_a[w], count_b[w]) for the denominator; on "apple apple pear" vs "apple pear pear", this produces (1 + 1) / (2 + 2) = 0.5 instead of 1.0.
  • How could you find pairs with high Jaccard overlap across millions of documents without comparing every pair? Checking every document pair takes O(N^2) comparisons, which is infeasible at N = 1,000,000. Instead, compress each document's word set into a short fixed-length signature using MinHash (a randomized hashing scheme where applying k independent hash functions and keeping each function's minimum hash value produces k integers whose agreement rate equals the two sets' Jaccard index in expectation), then index signatures with Locality-Sensitive Hashing (LSH) (a bucketing technique that hashes similar signatures into the same bucket with high probability so exact set comparisons run only on candidate pairs sharing a bucket).
  • What tokenization change would make the score resilient to minor typos? Whole-word tokens score "planet" and "plnaet" at 0.0 because the misspelled strings differ. Instead, represent text with character n-grams — overlapping windows of n consecutive letters such as 3-grams {"pla", "lan", "ane", "net"} vs {"pln", "lna", "nae", "aet"} or padded 2-grams — so a single character edit alters only a couple of windows while preserving strong partial overlap.

Follow-up questions

Similar questions

More Moveworks interview questions

All 3 Moveworks questions →