KatInterview

Complete the Run: Find the Gap in a Five-Card Sequence

Arrays & HashingAuto-graded · 20 test cases
EasyAuto-gradedArrays & Hashingarraysstringsenumeration

Last updated

Tests ability to handle encoded card ranks, Ace-as-low/high semantics, ambiguous endpoints, and missing-element logic in a fixed consecutive sequence.

Complete the Run: Find the Gap in a Five-Card Sequence

You receive 4 distinct characters, each representing a playing card rank. Together they form an incomplete 5-card run — five consecutive ranks — with exactly one rank absent. Your task is to identify and return that missing rank.

Rank Encoding

Every rank is represented as a single character using this scheme:

CharacterRank
'0'Ace
'2' – '9'2 through 9
'T'10
'J'Jack
'Q'Queen
'K'King

What Counts as a Run

A run is any five consecutive ranks from the ordering below:

A – 2 – 3 – 4 – 5 – 6 – 7 – 8 – 9 – 10 – J – Q – K – A

Ace may appear at the bottom of a run (A-2-3-4-5) or at the top (10-J-Q-K-A). Wrap-around sequences such as Q-K-A-2-3 are not valid runs.

This gives exactly 10 valid runs:

#Run
1A-2-3-4-5
22-3-4-5-6
33-4-5-6-7
44-5-6-7-8
55-6-7-8-9
66-7-8-9-10
77-8-9-10-J
88-9-10-J-Q
99-10-J-Q-K
1010-J-Q-K-A

Tie-Breaking Rule

Some sets of four cards fit inside more than one valid run (for example, 3-4-5-6 sits inside both run 2 and run 3). When this occurs, choose the lowest-numbered run from the table above. In other words, prefer the run whose lowest card has the smallest rank value.

Return Value

Return the missing rank as a single character using the same encoding described above (return '0' if the missing card is an Ace).

Raise ValueError if the four input cards cannot all be found in any single valid run.

Constraints

  • The input list always contains exactly 4 elements.
  • All 4 characters are distinct.
  • Each character belongs to {'0','2','3','4','5','6','7','8','9','T','J','Q','K'}.
  • Input order is arbitrary; the ranks may appear in any sequence.
  • When multiple runs are valid for a given input, return the missing card from the lowest valid run.

Examples

Example 1

Input: complete_the_run(['3', '4', '5', '6'])

Output: '2'

Example 2

Input: complete_the_run(['0', '2', '3', '5'])

Output: '4'

Hints

Hint 1

There are only 10 possible valid runs in total. Consider writing them all out explicitly rather than computing them on the fly.

Hint 2

Convert the input list to a set, then check each run in order from lowest to highest. The first run that fully contains all four input cards is your answer.

Hint 3

When you find a matching run, the missing card is simply the one element in that run's set that is not present in the input set. The ordering of runs from lowest to highest automatically handles tie-breaking.