Word Guess Color Scoring

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given a secret target word answer and a player's guess of identical length, compute a list of per-position color labels from left to right according to three rules:

  1. "green" when guess[i] equals answer[i] at that exact index.
  2. "yellow" when guess[i] differs from answer[i] at index i, yet guess[i] occurs at least once somewhere inside answer.
  3. "red" when guess[i] does not occur anywhere inside answer.

Positional equality ("green") always takes priority over general membership ("yellow"). Unlike frequency-capped word games, character occurrences in answer are never depleted: as long as a letter exists anywhere in answer, every non-matching index in guess containing that letter receives "yellow", regardless of how many "green" or "yellow" labels that letter has already produced.

Function Signature

def color_guess(answer: str, guess: str) -> list[str]:
    ...

Examples

Example 1

Input:  answer = "crane", guess = "trace"
Output: ["red", "green", "green", "yellow", "green"]

Walk-through: Index 0 ('t') is absent from "crane" ("red"). Indices 1 ('r'), 2 ('a'), and 4 ('e') match "crane" at the exact same positions ("green"). Index 3 ('c') differs from 'n' at index 3 but appears at index 0 of "crane" ("yellow").

Example 2

Input:  answer = "melon", guess = "lemon"
Output: ["yellow", "green", "yellow", "green", "green"]

Walk-through: Indices 0 ('l') and 2 ('m') swap places relative to "melon", so each receives "yellow", while 'e', 'o', and 'n' align at indices 1, 3, and 4 ("green").

Example 3

Input:  answer = "code", guess = "oooo"
Output: ["yellow", "green", "yellow", "yellow"]

Walk-through: Even though "code" contains only a single 'o' (matched "green" at index 1), membership is not consumed, so the misplaced 'o' characters at indices 0, 2, and 3 all receive "yellow".

Constraints

  • 1 <= len(answer) == len(guess) <= 100_000
  • Both answer and guess consist solely of lowercase ASCII letters ('a'–'z').

Step-by-step walkthrough

  1. Understand the three colors and the duplicate-letter rule

    Given two equal-length strings answer and guess (up to 100,000 lowercase letters), we return one color per index i:

    • "green" if guess[i] == answer[i] (right letter, right spot),
    • "yellow" if guess[i] != answer[i] and guess[i] appears anywhere in answer (right letter, wrong spot),
    • "red" if guess[i] never appears in answer at all.

    Pay close attention to how repeated letters behave in Example 3 — copies are not depleted:

    answer:   c       o       d       e      (only ONE 'o' in answer)
    guess:    o       o       o       o
              |       |       |       |
            yellow  green   yellow  yellow   <- all misplaced 'o's still get yellow!
    

    Even though index 1 matched the answer's single 'o' as "green", indices 0, 2, and 3 still ask "does 'o' exist anywhere in answer?" — the answer is yes, so all three become "yellow".

  2. Why scanning the `answer` string per character is too slow

    Translating the rules literally into a string search gives:

    def color_guess_naive(answer: str, guess: str) -> list[str]:
        colors = []
        for i in range(len(guess)):
            if guess[i] == answer[i]:
                colors.append("green")
            elif guess[i] in answer:  # scans up to len(answer) characters every time!
                colors.append("yellow")
            else:
                colors.append("red")
        return colors
    

    Checking guess[i] in answer on a plain str scans answer character by character. When n = 100,000 and guess consists of letters absent from answer (say "zzzz..." against "aaaa..."), each of the 100,000 positions scans all 100,000 characters of answer — up to 10^10 character comparisons, or O(n^2) time.

  3. Precompute a hash set of answer letters in O(n)

    Notice that "does letter c appear anywhere in answer?" is a yes/no question that never changes as we move across guess, and does not depend on how many copies of c exist. We can precompute the set of unique letters in answer once before the loop:

    answer = "crane"  --->  answer_letters = {"c", "r", "a", "n", "e"}
    answer = "code"   --->  answer_letters = {"c", "o", "d", "e"}
    

    Building set(answer) takes one O(n) pass (storing at most 26 lowercase English letters), and every guess_char in answer_letters check inside the loop drops from O(n) to O(1) average time. Because matches are never depleted, we never remove anything from answer_letters.

  4. Check positional match before set membership

    The order of if and elif is critical! Any character that matches at the exact same position (guess_char == answer_char) is also inside answer_letters:

    answer = "crane", guess = "trace", index 1 ('r' vs 'r'):
      1) Is guess_char == answer_char?  'r' == 'r' -> YES -> "green" (stop!)
      (If we checked 'r' in answer_letters first, index 1 would wrongly turn "yellow"!)
    

    Testing guess_char == answer_char first guarantees exact matches become "green", leaving elif guess_char in answer_letters: solely for misplaced letters.

        answer_letters = set(answer)
    
        colors: List[str] = []
        for answer_char, guess_char in zip(answer, guess):
            if guess_char == answer_char:
                colors.append("green")
            elif guess_char in answer_letters:
                colors.append("yellow")
            else:
                colors.append("red")
    
  5. Trace Example 1 and Example 3 step by step

    Let's trace how the loop scores Example 1 ("crane" vs "trace") and Example 3 ("code" vs "oooo"):

    Example 1: answer = "crane", guess = "trace", answer_letters = {'a','c','e','n','r'}
      i=0: 't' vs 'c' -> not equal; 't' not in set -> "red"
      i=1: 'r' vs 'r' -> equal                     -> "green"
      i=2: 'a' vs 'a' -> equal                     -> "green"
      i=3: 'c' vs 'n' -> not equal; 'c' in set     -> "yellow"
      i=4: 'e' vs 'e' -> equal                     -> "green"
      Output: ["red", "green", "green", "yellow", "green"]
    
    Example 3: answer = "code", guess = "oooo", answer_letters = {'c','d','e','o'}
      i=0: 'o' vs 'c' -> not equal; 'o' in set     -> "yellow"
      i=1: 'o' vs 'o' -> equal                     -> "green"
      i=2: 'o' vs 'd' -> not equal; 'o' in set     -> "yellow"
      i=3: 'o' vs 'e' -> not equal; 'o' in set     -> "yellow"
      Output: ["yellow", "green", "yellow", "yellow"]
    
  6. Full solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def color_guess(answer: str, guess: str) -> list[str]:
        # answer_letters: set of unique letters in answer, e.g. {"c", "o", "d", "e"} for "code".
        # Precomputing this once turns each "appears anywhere" check into an O(1) lookup.
        answer_letters = set(answer)
    
        colors: List[str] = []
        for answer_char, guess_char in zip(answer, guess):
            # Check exact positional equality FIRST: a green letter is also in answer_letters,
            # so checking set membership first would mislabel every green as yellow.
            if guess_char == answer_char:
                colors.append("green")
            # Simple presence rule: letters are never removed from answer_letters,
            # so every misplaced copy of a present letter receives "yellow".
            elif guess_char in answer_letters:
                colors.append("yellow")
            else:
                colors.append("red")
        return colors
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine grading a letter-by-letter guessing game with two simple tools: the exact answer key (answer) and an alphabet checklist of which letters appear anywhere in answer. Walking left to right across guess, if a guessed letter matches the exact same slot in answer, we award "green"; otherwise, if the letter is checked off on our alphabet checklist, we award "yellow"; otherwise, we award "red". Because misplaced letters do not deplete copies in answer, we only ever need yes/no membership rather than letter counts — making a hash set (an unordered collection of unique elements backed by a hash table for constant-time membership lookups) the ideal data structure for the checklist.

A naive solution checks guess[i] in answer directly on the answer string for every non-green index. Because checking membership in a plain string scans characters one by one from the start, guessing 100,000 absent letters against a 100,000-letter answer performs up to 100,000 * 100,000 = 10^10 comparisons (O(n^2) time). Building answer_letters = set(answer) once up front scans answer a single time and makes every subsequent membership lookup O(1) on average.

Walk through Example 3 with answer = "code" and guess = "oooo": 1. Build answer_letters = {"c", "o", "d", "e"} in one pass over "code". 2. Index 0 (guess_char = 'o', answer_char = 'c'): not equal, 'o' is in answer_letters -> "yellow". 3. Index 1 (guess_char = 'o', answer_char = 'o'): equal -> "green". 4. Indices 2 and 3 (guess_char = 'o' vs 'd' and 'e'): not equal, 'o' remains in answer_letters -> "yellow" for both, returning ["yellow", "green", "yellow", "yellow"].

Complexity

Let n = len(answer) = len(guess).

  • Time: O(n). Constructing set(answer) visits each of the n characters in answer once with O(1) average hash insertion, and the zip(answer, guess) loop visits each of the n positions once, doing one == character check and at most one O(1) average set lookup.
  • Space: O(n) total, or O(1) auxiliary space beyond the output. Returning the colors list requires n strings; answer_letters itself holds at most 26 unique lowercase English letters, which is constant O(1) extra memory regardless of n.

Edge cases

  • Single-character strings (n = 1): the lone character is either "green" ("a" vs "a") or "red" ("a" vs "b"); "yellow" is impossible because there is no other position in answer where the letter could appear.
  • Identical strings (answer == guess): every index hits the first if branch and returns all "green".
  • Disjoint alphabets ("abc" vs "xyz"): every index falls through to else and returns all "red".
  • Derangement / permutation ("abcd" vs "bcda"): every character is in answer_letters and none matches its own index, returning all "yellow".
  • Duplicate guessed letters ("ab" vs "aa", or "code" vs "oooo"): neither a "green" match nor an earlier "yellow" match consumes the letter, so every non-green occurrence of a present letter still gets "yellow".
  • Maximum length (n = 100,000): finishes in a few milliseconds in a single linear pass with no recursion.

Common mistakes

  • Implementing frequency-capped Wordle rules by habit: tracking remaining letter counts turns Example 3 (answer = "code", guess = "oooo") into ["red", "green", "red", "red"] instead of the required ["yellow", "green", "yellow", "yellow"].
  • Checking guess_char in answer_letters before guess_char == answer_char: because every exact match is also a member of answer_letters, testing presence first turns every "green" into "yellow".
  • Checking guess_char in answer on the raw string: hides an O(n) linear scan inside an O(n) loop, degrading worst-case runtime to O(n^2) at n = 100,000.
  • Calling set(answer) inside the for loop: rebuilds the set n times in O(n^2) total time instead of once before the loop.

Alternative approaches

  • 26-element boolean array: Since inputs are guaranteed to be lowercase ASCII letters 'a'–'z', you can replace set(answer) with a fixed boolean list present = [False] * 26 indexed by ord(ch) - ord('a'). This gives strict worst-case O(1) array indexing without hashing, though in Python set(answer) is shorter, clearer, and runs at C speed.

Follow-up questions

  • How would the scoring logic change if each character copy in the secret word could satisfy at most one match, as in standard Wordle? Use a two-pass frequency-counter approach so exact "green" matches never get stolen by earlier misplaced copies. In Pass 1, mark all "green" positions (guess[i] == answer[i]) and count only the unmatched characters of answer in a dictionary remaining_counts; in Pass 2, scan non-green positions left to right, awarding "yellow" and decrementing remaining_counts[guess[i]] only while remaining_counts.get(guess[i], 0) > 0 (and "red" otherwise).
  • If the same target word is evaluated against thousands of guesses in a single game session, what work can be reused across calls? Wrap the scorer in a class (or closure) that stores self.answer = answer and precomputes self.answer_letters = set(answer) once in __init__, avoiding rebuilding the set on every guess. Scoring each individual guess of length n still takes O(n) time — which is optimal because you must inspect all n characters of guess and output n colors.
  • What adjustments are needed to support uppercase characters or full Unicode strings? For case-sensitive Unicode characters, the exact same set(answer) code works unchanged, except answer_letters can hold up to n distinct characters (making auxiliary space O(min(n, alphabet_size)) instead of O(26)). For case-insensitive comparison, normalize characters consistently first, and clarify with the interviewer whether multi-character case-folding cases like German 'ß' -> 'ss' can occur or whether character-by-character .lower() is expected.

Follow-up questions

Similar questions

More Ngrok interview questions

All 2 Ngrok questions →