KatInterview

Score a Guess Against a Hidden Word with Exact and Shifted Hits

StringsAuto-graded · 23 test cases
MediumAuto-gradedStringsstringshashingfrequency-counting

Last updated

Compute exact-position and misplaced letter counts between a guess and a secret using leftover letter counts, with a sentinel for guesses missing from the word list.

You are building the scoring routine for a word-guessing game.

You are given:

  • word_list: a list of distinct lowercase words, all of the same length.
  • secret: the hidden word.
  • guess: the player's attempted word.

Return a two-element list [exact, shifted] describing how well the guess matches the secret.

Scoring rules

  1. Validity check. If guess does not appear in word_list, return [-1, -1].
  2. Exact hits. exact is the number of indices i where secret[i] == guess[i].
  3. Shifted hits. Ignore every index that counted as an exact hit. Among the remaining indices, gather the letters of secret and the letters of guess separately. For each letter c, let a be how many times c occurs in the remaining part of secret and b how many times it occurs in the remaining part of guess. Then shifted is the sum of min(a, b) over all letters c.

Every letter occurrence can be used for at most one pairing, so nothing is counted twice, and a letter already consumed by an exact hit cannot be reused as a shifted hit.

Output

A list of two integers [exact, shifted], or [-1, -1] when the guess is not in word_list.

Constraints

  • 1 <= len(word_list) <= 10^5
  • Every word in word_list, as well as secret and guess, has the same length L, where 1 <= L <= 20.
  • All words contain only lowercase English letters a to z.
  • secret is one of the words in word_list.

Examples

Example 1

Input: score_guess(['apple', 'angle', 'ample', 'alley'], 'apple', 'alley')

Output: [1, 2]

Example 2

Input: score_guess(['abbey', 'babbb', 'bbbaa'], 'abbey', 'babbb')

Output: [1, 2]

Example 3

Input: score_guess(['abc', 'bca', 'cab'], 'abc', 'cab')

Output: [0, 3]

Hints

Hint 1

Handle the invalid-guess case first; a set gives fast membership checks.

Hint 2

Count exact positional matches first, and only record the letters from the non-matching positions.

Hint 3

Keep one letter-count table for the secret's leftover letters and one for the guess's leftover letters, then add up the per-letter minimums.