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:
"green"whenguess[i]equalsanswer[i]at that exact index."yellow"whenguess[i]differs fromanswer[i]at indexi, yetguess[i]occurs at least once somewhere insideanswer."red"whenguess[i]does not occur anywhere insideanswer.
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
answerandguessconsist solely of lowercase ASCII letters ('a'–'z').
Step-by-step walkthrough
Understand the three colors and the duplicate-letter rule
Given two equal-length strings
answerandguess(up to100,000lowercase letters), we return one color per indexi:"green"ifguess[i] == answer[i](right letter, right spot),"yellow"ifguess[i] != answer[i]andguess[i]appears anywhere inanswer(right letter, wrong spot),"red"ifguess[i]never appears inanswerat 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
1matched the answer's single'o'as"green", indices0,2, and3still ask "does'o'exist anywhere inanswer?" — the answer is yes, so all three become"yellow".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 colorsChecking
guess[i] in answeron a plainstrscansanswercharacter by character. Whenn = 100,000andguessconsists of letters absent fromanswer(say"zzzz..."against"aaaa..."), each of the100,000positions scans all100,000characters ofanswer— up to10^10character comparisons, or O(n^2) time.Precompute a hash set of answer letters in O(n)
Notice that "does letter
cappear anywhere inanswer?" is a yes/no question that never changes as we move acrossguess, and does not depend on how many copies ofcexist. We can precompute the set of unique letters inansweronce 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 everyguess_char in answer_letterscheck inside the loop drops from O(n) to O(1) average time. Because matches are never depleted, we never remove anything fromanswer_letters.Check positional match before set membership
The order of
ifandelifis critical! Any character that matches at the exact same position (guess_char == answer_char) is also insideanswer_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_charfirst guarantees exact matches become"green", leavingelif 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")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"]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 thencharacters inansweronce with O(1) average hash insertion, and thezip(answer, guess)loop visits each of thenpositions 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
colorslist requiresnstrings;answer_lettersitself holds at most 26 unique lowercase English letters, which is constant O(1) extra memory regardless ofn.
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 inanswerwhere the letter could appear. - Identical strings (
answer == guess): every index hits the firstifbranch and returns all"green". - Disjoint alphabets (
"abc"vs"xyz"): every index falls through toelseand returns all"red". - Derangement / permutation (
"abcd"vs"bcda"): every character is inanswer_lettersand 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_lettersbeforeguess_char == answer_char: because every exact match is also a member ofanswer_letters, testing presence first turns every"green"into"yellow". - Checking
guess_char in answeron the raw string: hides an O(n) linear scan inside an O(n) loop, degrading worst-case runtime to O(n^2) atn = 100,000. - Calling
set(answer)inside theforloop: rebuilds the setntimes 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 replaceset(answer)with a fixed boolean listpresent = [False] * 26indexed byord(ch) - ord('a'). This gives strict worst-case O(1) array indexing without hashing, though in Pythonset(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 ofanswerin a dictionaryremaining_counts; in Pass 2, scan non-green positions left to right, awarding"yellow"and decrementingremaining_counts[guess[i]]only whileremaining_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 = answerand precomputesself.answer_letters = set(answer)once in__init__, avoiding rebuilding the set on every guess. Scoring each individual guess of lengthnstill takes O(n) time — which is optimal because you must inspect allncharacters ofguessand outputncolors. - 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, exceptanswer_letterscan hold up tondistinct 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
- How would the scoring logic change if each character copy in the secret word could satisfy at most one match, as in standard Wordle?
- If the same target word is evaluated against thousands of guesses in a single game session, what work can be reused across calls?
- What adjustments are needed to support uppercase characters or full Unicode strings?
Similar questions
- Exact String Lookup with Uniform Random Sampling
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One