KatInterview

Corridor Run With Matching Keys and Locked Doors

StringsAuto-graded · 27 test cases
MediumAuto-gradedStringsbfsbitmaskstring-scan

Last updated

Find the fewest moves along a 1D corridor with walls, keys and doors, and notice that the state space collapses to a simple prefix scan.

Corridor Run With Matching Keys and Locked Doors

A corridor is described by a string corridor of length n. Each character is one cell:

  • '.' is an open cell.
  • '#' is a wall and can never be entered.
  • A lowercase letter 'a'-'z' is a key. Entering the cell picks it up, and you keep it for the rest of the trip.
  • An uppercase letter 'A'-'Z' is a locked door. You may enter it only if you already hold the key with the same letter in lowercase (door 'C' needs key 'c'). Doors are not consumed, and keys are not used up.

You begin at index 0. In one move you step to the cell directly to the left or right, and each move costs 1 unit of time. You may revisit cells and move in either direction.

Some rules for the starting cell:

  • You are already standing on index 0, so whatever it contains does not block you at the start.
  • If index 0 holds a key, you pick it up immediately.

Return the minimum time needed to stand on index n - 1. Return 0 if n == 1, and return -1 if the last cell cannot be reached.

The last cell follows the same entry rules as any other cell. If it is a wall, or a door whose key you cannot hold, the answer is -1.

Constraints

  • 1 <= n <= 2000
  • corridor contains only '.', '#', and letters 'a'-'z' / 'A'-'Z'.
  • The same key letter may appear several times. Holding one copy is the same as holding several.
  • A door may have no matching key anywhere in the corridor.

Examples

Example 1

Input: min_time_to_exit('.a.A.b.B.')

Output: 8

Example 2

Input: min_time_to_exit('.A.a.')

Output: -1

Hints

Hint 1

Think of your state as (position, set of keys held). Can you write a BFS over it? Then ask how many different key sets can actually occur at a given position.

Hint 2

To reach the last cell you must step on every cell between the start and it. What does that imply about which keys you hold when you first arrive at index i?

Hint 3

If walking right without ever turning back is allowed by the rules, it is also optimal. So the answer is either n - 1 or -1, and a single left-to-right scan that tracks collected keys decides which.