KatInterview

Collect Coins with Fixed-Jump Pieces

Greedy & IntervalsAuto-graded · 23 test cases
MediumAuto-gradedGreedy & Intervalsgreedymodular-arithmeticarrays

Last updated

Tests modular arithmetic insight and greedy reasoning to determine which resources are reachable under constrained movement rules.

You are given a one-dimensional board represented as an array of length n. Each cell contains one of three values:

  • "P" — a movable piece
  • "C" — a collectable coin
  • "." — an empty cell

You may perform any number of moves in any order. In each move, you select one piece currently on the board and attempt to shift it exactly 3 positions to the right (from index i to index i + 3).

A move from index i to i + 3 is valid only if all of the following conditions hold:

  1. i + 3 < n (the destination is within bounds)
  2. The destination cell at i + 3 does not currently contain another piece (pieces cannot overlap)

If a move is valid:

  • The piece moves from index i to index i + 3
  • If the destination cell was empty ("."), the piece now occupies it and the cell becomes a piece
  • If the destination cell contained a coin ("C"), the piece occupies it, you collect that coin, and the cell becomes a piece (the coin is removed)
  • The original cell at index i becomes empty (".")
  • The piece may jump over any cells between i and i + 3; the contents of cells i + 1 and i + 2 do not affect the move

Continue making moves until no valid moves remain or you choose to stop. Your goal is to collect as many coins as possible.

Return the maximum number of coins you can collect.

Constraints

  • 1 ≤ n ≤ 10⁵
  • Each cell contains exactly one of "P", "C", or "."
  • There may be zero or more pieces and zero or more coins

Examples

Example 1

Input: collect_coins(['P', '.', '.', 'C', '.', '.', 'C'])

Output: 2

Example 2

Input: collect_coins(['C', 'P', '.', 'C', 'P', 'C', '.', 'C'])

Output: 1

Example 3

Input: collect_coins(['.', '.', 'C', '.', 'P', '.', 'C'])

Output: 0

Hints

Hint 1

A piece at index i can only move to indices i+3, i+6, i+9, etc. What property do all these indices share?

Hint 2

Consider grouping cells by their index modulo 3. Pieces in different groups never interact.

Hint 3

Within a single modulo-3 group, which coins can actually be reached by the pieces in that group? Think about the leftmost piece.