Crack a 4-digit code from exact-match counts

0
Sign in

A server holds a secret 4-character code. Each character is a digit from '0' to '9'. Digits may repeat, and the code may start with zeros.

You can only learn about the code through one call:

class GuessServer:
    def guess_number(self, guess: str) -> int: ...

guess_number takes any 4-digit string and returns how many positions hold the correct digit. It does not tell you about correct digits in the wrong position.

Implement crack(server: GuessServer) -> str, which returns the secret code. Use as few calls as you can, and state the worst-case number of calls your method needs.

Constraints

  • The code length is 4 and the alphabet is 0-9.
  • The server is deterministic and the secret does not change.
  • Brute force over all 10,000 codes is correct but too slow; aim for a small fixed bound.

Example 1

Secret "3071" (hidden from you).

  • guess_number("3000") returns 2 (the 3 in position 0 and the 0 in position 1 match).
  • guess_number("1111") returns 1 (only position 3 matches).
  • crack(server) returns "3071".

Example 2

Secret "0505".

  • guess_number("5555") returns 2.
  • guess_number("0000") returns 2, so the code uses only the digits 0 and 5, twice each.
  • crack(server) returns "0505".
AirbnbCodingHard

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.