Letter-Match Feedback Widget for a Five-Letter Word Game
StringsModel answerLast updated
Build a small browser widget that scores a typed guess of up to five letters against a fixed secret word, marking each letter exact, misplaced or absent, with sound input handling.
Task
Create a minimal browser component for a five-letter word-guessing game. The game holds one hidden word, and the player types a guess. Every letter of the guess gets one of three labels describing how it relates to the hidden word:
- Green: the letter occurs in the hidden word at the same position.
- Yellow: the letter occurs in the hidden word, but at another position.
- Red: the letter does not occur in the hidden word.
For testing, use the hidden word SPEND. The player may type at most five letters. Visual polish is not evaluated; the three states must simply be easy to tell apart. Spend your effort on correct feedback and a smooth input flow.
Constraints
- Time budget: about 45 minutes, including your own testing.
- Hidden word:
SPEND(five distinct uppercase letters). - Input: letters only, no more than five.
- Colors are required; styling beyond that is not.
Questions worth settling up front
- Is a framework mandatory, or is plain JavaScript fine?
- Should colors update while typing or only after submission?
- Must a guess be exactly five letters before it can be scored?
- Must the guess be a real dictionary word?
- Should earlier guesses stay visible, and is there an attempt limit?
State your assumptions explicitly in your answer.
Part 1: Scoring function
Write a pure function that takes the hidden word and a guess and returns one status per guessed letter. Example: against SPEND, the guess SNEAK yields green, yellow, green, red, red.
Decide and justify how to handle:
- A guess containing a letter more times than the hidden word does (for example
SPEEDagainstSPEND). Which copies are colored, and which become red? - Case differences.
- Guesses shorter than five letters, if you allow them.
Part 2: Input and rendering
Build the interface: an input restricted to at most five letters, and a row of tiles colored by the Part 1 statuses. Explain:
- How you restrict input to letters, cap its length, normalize case, and cope with pasted text.
- What you keep in state (current text, submitted guesses) and what you derive (statuses, whether the puzzle is solved).
- How a guess is submitted (button, Enter key, or both) and how statuses map to colors.
Hints
Hint 1
Compute the scoring in two passes: first mark exact-position matches, then handle the remaining letters. Doing both in one left-to-right pass is where duplicate-letter bugs creep in.
Hint 2
Keep a count of the hidden word's letters that were not consumed by an exact match. A non-exact guessed letter is yellow only if its remaining count is above zero (and you decrement it); otherwise it is red.
Hint 3
Store only the raw current input and the list of submitted guesses. Statuses and the solved flag can be recomputed from those during render. Sanitize input in one place: uppercase it and strip anything that is not A-Z, then slice to five characters.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
- Plain JavaScript (or a light framework such as React) is acceptable. The logic is framework-independent.
- Feedback appears on submit, not per keystroke, so the player sees a full guess at once. Showing it live is a small change, since scoring is a pure function.
- Only a five-letter guess can be submitted. While typing, shorter text is just buffered. If shorter guesses were allowed, the scorer would still work position by position over the guess length.
- No dictionary check, and multiple guesses are kept in a list with no attempt limit. Both are easy extensions.
- Matching is case-insensitive: everything is normalized to uppercase.
Scoring approach
Do it in two passes, with a count of "unclaimed" hidden letters.
- Pass 1 (exact matches): for each index
i, ifguess[i] === secret[i], mark green. Otherwise, addsecret[i]to a frequency map of unclaimed letters. - Pass 2 (misplaced letters): for each non-green index, if the guessed letter has a positive count in the map, mark yellow and decrement the count. Otherwise mark red.
Building the map only from non-green positions is what makes repeated letters correct: a letter already matched exactly cannot also be used to justify a yellow elsewhere.
Repeated-letter rule
A letter in the guess is colored (green or yellow) at most as many times as it occurs in the hidden word. Greens get priority; the remaining yellows are assigned left to right; the extra copies become red. For SPEND (one E), the guess SPEED gives:
- S green, P green, first E green? Check:
SPEND[2]isE, so index 2 is green. The second E at index 3 has no unclaimedEleft, so it is red. D at index 4 is not equal toSPEND[4]=D? It is equal, so green.
Result: green, green, green, red, green. The second E is red because the hidden word has just one.
Another check: guess EERIE against SPEND. No index matches exactly. Unclaimed map is {S, P, E, N, D}. The first E becomes yellow (count of E goes to 0), later Es are red.
Code
const GREEN = "green", YELLOW = "yellow", RED = "red";
function score(secret, guess) {
secret = secret.toUpperCase();
guess = guess.toUpperCase();
const result = new Array(guess.length).fill(RED);
const unclaimed = {};
for (let i = 0; i < guess.length; i++) {
if (guess[i] === secret[i]) {
result[i] = GREEN;
} else if (i < secret.length) {
unclaimed[secret[i]] = (unclaimed[secret[i]] || 0) + 1;
}
}
for (let i = 0; i < guess.length; i++) {
if (result[i] === GREEN) continue;
const c = guess[i];
if (unclaimed[c] > 0) {
result[i] = YELLOW;
unclaimed[c]--;
}
}
return result;
}
Quick checks against SPEND:
SNEAK-> green, yellow, green, red, redSPEND-> all green (solved)SPEED-> green, green, green, red, greenXYZQW-> all red
Complexity is O(n) time and O(alphabet) space per guess, with n at most 5.
Input handling
One sanitizer used everywhere (typing, paste, programmatic set):
const clean = s => s.toUpperCase().replace(/[^A-Z]/g, "").slice(0, 5);
Apply it in the input's onChange/input handler and set the field's value to the cleaned string, so pasted text such as "sp-end!!" becomes SPEND and over-long pastes are truncated. Also set maxLength=5 and autocomplete="off" as a convenience, but do not rely on them alone since paste and scripts can bypass them.
State model
- Stored:
current(string being typed) andguesses(array of submitted strings). - Derived: the statuses for each guess (
score(SECRET, g)) andsolved(guesses.includes(SECRET)or last guess all green).
Avoid storing statuses: it duplicates data and invites stale state if the secret changes.
Submit on Enter or button click only when current.length === 5; then append to guesses and clear current. Disable the input once solved.
Rendering
Render each guess as a row of five tiles. Map statuses to CSS classes (.green, .yellow, .red). For accessibility, color alone is insufficient: add a text label or aria-label per tile (for example "S, correct position", "N, wrong position", "K, not in word") or a small symbol, which also helps colorblind users.
Trade-offs and common mistakes
- Single-pass scoring: marking yellow before all greens are known leads to a letter being colored yellow even though a later exact match consumes it.
- Counting from the whole secret: building the unclaimed map from all hidden letters (not just non-green positions) over-awards yellows.
- Trusting
maxLengthonly: paste and script input can bypass it. - Mixing logic into the view: keeping
scorepure makes it trivially testable in the console and reusable. - Storing derived data: statuses and solved state should be recomputed.
- Unfinished work: in a 45-minute window, deliver a working input, scoring and display first; then add tests, labels and extras.
Possible follow-ups
- Dictionary validation and attempt limits.
- A keyboard that tracks the best-known status per letter.
- Picking the hidden word daily from a list.
- Unit tests covering repeated letters, case, and short guesses.