Google questions

Mahjong Winning Hand

GoogleOnsiteMedium

A mahjong hand is 14 tiles. Each tile is a string such as "3m", "7p" or "1s": a rank from 1 to 9 followed by a suit letter m, p or s. There are four copies of each tile, so a hand never holds more than four of the same tile. A hand wins when its 14 tiles can be split into one pair (two identical tiles) and four melds. A meld is either a triplet (three identical tiles) or a run (three tiles of the same suit with consecutive ranks, such as 4p 5p 6p). A run does not wrap around, so 8m 9m 1m is not a run. No other winning shape counts, including seven pairs.

Part 1: Winning hand check

You are given a list of 14 mahjong tile strings tiles, in any order. Return True if the tiles can be split into one pair of two identical tiles and four melds, where each meld is a triplet of three identical tiles or a run of three tiles of the same suit with consecutive ranks. Return False otherwise.

  1. Example 1
    tiles
    ["1m","1m","1m","2m","3m","4m","5p","6p","7p","9s","9s","9s","3p","3p"]
    Output
    true

    Why: The pair is 3p 3p; the rest split into the triplet 1m 1m 1m, the runs 2m 3m 4m and 5p 6p 7p, and the triplet 9s 9s 9s.

  2. Example 2
    tiles
    ["1m","1m","1m","2m","3m","4m","5p","6p","7p","9s","9s","9s","3p","4p"]
    Output
    false

    Why: The stray tiles 3p 4p fit no pair and no meld, so no split into one pair and four melds exists.

Constraints

  • len(tiles) == 14
  • Every tile is a rank 1 to 9 followed by m, p or s
  • Each distinct tile appears at most 4 times in tiles
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Mahjong Winning Hand: Google interview question | LoopCoach