Letter-Grid Feedback for a Hidden Word Guess
StringsAuto-graded · 21 test casesLast updated
Score a guess against a hidden word with exact, misplaced, and absent marks, handling repeated letters correctly and rejecting invalid input.
Letter-Grid Feedback for a Hidden Word Guess
You are building the scoring step of a word-guessing game. Given a hidden word target and a player's attempt of the same length, produce a list of integer marks, one per position, describing how well each letter of the attempt fits.
Marks
For each index i:
- 2 (exact):
attempt[i] == target[i]. - 1 (misplaced): the letter is not an exact match at
i, but the target still has an unused copy of that letter at some other position (see the rules below). - 0 (absent): neither of the above. The letter does not appear in the target, or every relevant copy has already been used.
How copies are used up
Each letter of the target can justify at most one non-zero mark in the attempt:
- First, every exact match (mark 2) uses up the target letter at that same position.
- Every target letter at a position that was not an exact match forms a pool of available copies, counted per letter.
- Then scan the attempt from left to right over the positions that are not exact matches. If the pool still holds a copy of
attempt[i], give that position mark 1 and remove one copy from the pool. Otherwise give mark 0.
So when an attempt has more leftover copies of a letter than the target can supply, the leftmost ones receive mark 1 and the rest receive 0.
Input validation
Raise a ValueError if any of the following hold:
targetorattemptis not a string (this includesNone),- either string is empty,
- the two strings have different lengths,
- either string contains a character outside
'a'to'z'(uppercase letters, digits, spaces, and non-ASCII characters are all invalid).
Validation must happen before any scoring.
Task
Implement the function that returns the list of marks.
- Input:
target: str,attempt: str - Output: a list of integers, each in
{0, 1, 2}, with the same length as the inputs.
Constraints
- Valid inputs consist only of lowercase English letters
a-z. - Valid inputs are non-empty and both have the same length
n. - Invalid inputs must raise
ValueError. - The solution should run in O(n) time.
Examples
Example 1
Input: score_attempt('hello', 'abcde')
Output: [0, 0, 0, 0, 1]
Example 2
Input: score_attempt('hello', 'eabcd')
Output: [1, 0, 0, 0, 0]
Example 3
Input: score_attempt('aabb', 'bbba')
Output: [1, 0, 2, 1]
Hints
Hint 1
Think about what goes wrong if you mark a letter as misplaced just because it appears somewhere in the target. A single target letter should only justify one mark.
Hint 2
Do two passes. First lock in all exact matches, and count the target letters at the remaining positions. Only then decide which other positions get a misplaced mark.
Hint 3
In the second pass, walk left to right over non-exact positions, and whenever the count for that attempt letter is positive, give mark 1 and decrement the count. Do all validation up front.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The only subtle part is repeated letters. Marking a letter as misplaced whenever it occurs somewhere in the target over-counts, because each target letter can justify only one non-zero mark.
The solution uses two passes after validation:
- Exact pass. For every index where
target[i] == attempt[i], set the mark to 2. For every other index, addtarget[i]to a counter of available letters. - Misplaced pass. Walk the attempt left to right. For each position that is not already 2, if the counter has a positive count for
attempt[i], set the mark to 1 and decrement that count. Otherwise leave it at 0.
Why it is correct
- Exact matches are never stolen. They are fixed first, and their target letters never enter the pool, so a misplaced mark can't consume a letter an exact match needs.
- Multiplicity is respected. Each non-exact target letter adds one unit to the pool and each misplaced mark removes one. For a letter
c, the number of misplaced marks ismin(non-exact c in attempt, non-exact c in target). - Ties are deterministic. Scanning left to right means the leftmost surplus letters get mark 1, as the rules require.
For target = "aabb", attempt = "bbba": index 2 is exact. The pool is {a: 2, b: 1}. Index 0 (b) takes the one b, index 1 (b) finds none and gets 0, index 3 (a) gets 1. The result is [1, 0, 2, 1].
Complexity
- Time: O(n), with one validation scan and two linear passes.
- Space: O(n) for the output; the counter holds at most 26 keys.
Reference solution
from typing import List
from collections import Counter
def score_attempt(target: str, attempt: str) -> List[int]:
if not isinstance(target, str) or not isinstance(attempt, str):
raise ValueError("target and attempt must be strings")
if not target or not attempt:
raise ValueError("target and attempt must be non-empty")
if len(target) != len(attempt):
raise ValueError("target and attempt must have equal lengths")
if any(not ('a' <= ch <= 'z') for ch in target + attempt):
raise ValueError("only lowercase English letters are allowed")
marks = [0] * len(target)
pool = Counter()
# Pass 1: exact matches; pool the unmatched target letters.
for i, (t, a) in enumerate(zip(target, attempt)):
if t == a:
marks[i] = 2
else:
pool[t] += 1
# Pass 2: misplaced letters, limited by remaining copies, left to right.
for i, a in enumerate(attempt):
if marks[i] == 0 and pool[a] > 0:
marks[i] = 1
pool[a] -= 1
return marks