Problem
Implement the feedback generation for a Wordle-like game.
Given:
target(the secret word)guess(the player's guess)
Return a feedback string of the same length:
*correct letter, correct position%correct letter, wrong position-letter not present
Example
Target: staff
Guess: world -> -----
Guess: worms -> ----%
Guess: fluff -> ---**
Guess: staff -> *****
Key Point
You must handle duplicates correctly (e.g., staff has two f). The common pattern is a two-pass solution.
Approach (two-pass)
- First pass: mark exact matches (
*) and remove those letters from remaining counts. - Second pass: for the rest, mark
%only if the letter still has remaining count.
Python (Counter-based)
from collections import Counter
def wordle_feedback(target: str, guess: str) -> str:
n = len(target)
res = ['-'] * n
remaining = Counter(target)
# exact matches
for i in range(n):
if guess[i] == target[i]:
res[i] = '*'
remaining[guess[i]] -= 1
# present but wrong position
for i in range(n):
if res[i] == '-' and remaining[guess[i]] > 0:
res[i] = '%'
remaining[guess[i]] -= 1
return ''.join(res)
Complexity
- Time:
O(n) - Space:
O(1)for fixed alphabet (orO(n)worst-case)
Need interview help? Contact OA VO Service
- 📧 Email: [email protected]
- 📱 Phone: +86 17863968105
Need real interview questions? Contact WeChat: Coding0201 to get the questions.