Determine winner in stack-merging game
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of combinatorial game theory, impartial game analysis, state-space encoding, and efficient state-space search techniques.
Constraints
- 1 <= len(colors) <= 12
- Each colors[i] is one of 'Y', 'W', 'G', 'B'
- All stacks initially have height 1
Examples
Input: ['Y']
Expected Output: False
Explanation: With only one stack, there are no two different stacks to merge, so the first player loses immediately.
Input: ['Y', 'W']
Expected Output: True
Explanation: The two stacks have equal height, so one legal merge exists. After that, only one stack remains and the second player has no move.
Input: ['Y', 'W', 'G']
Expected Output: True
Explanation: The first player can merge 'Y' onto 'W', leaving stacks (2, 'Y') and (1, 'G'). These have different heights and different top colors, so the second player has no legal move.
Input: ['Y', 'Y', 'Y']
Expected Output: False
Explanation: Any first move leaves two stacks: (2, 'Y') and (1, 'Y'). The second player can merge them because the top colors match, making the last move.
Input: ['Y', 'Y', 'W']
Expected Output: True
Explanation: The first player can merge one 'Y' onto the other 'Y', leaving (2, 'Y') and (1, 'W'). Different heights and different top colors mean no move for the second player.
Input: ['Y', 'Y', 'Y', 'Y', 'Y']
Expected Output: False
Explanation: All stacks always share the same top color, so a merge is always possible until one stack remains. That means exactly 4 moves occur, so the second player makes the last move.
Input: ['Y', 'W', 'G', 'B']
Expected Output: True
Explanation: The first player can create a stack of height 2 with a color different from the two remaining single stacks, for example merge 'Y' onto 'W'. Then the second player is forced to merge the two height-1 stacks, creating two height-2 stacks, and the first player makes the final merge.
Hints
- Only the current height and top color of each stack matter. The deeper contents of a stack never affect future moves.
- Since the order of stacks does not matter, memoize game states using a canonical sorted representation of (height, color) pairs.