KatInterview

Verify Validity of Piece Movement on a 1D Board

StringsModel answer
MediumModel answerStringsstringstwo-pointersinvariants

Last updated

Determine whether an initial 1D board configuration can reach a target configuration based on specific movement and jump rules.

You are analyzing a 1D puzzle board represented by a string of length $N$. The board contains two types of movable tokens, 'A' and 'B', along with empty spaces denoted by '.'.

The rules governing token movement are defined as follows:

  1. Token 'A' can slide into any adjacent empty space (i.e., "A." can become ".A", and ".A" can become "A.").
  2. Token 'B' can leap over a directly adjacent 'A' token if there is an empty space immediately behind that 'A' (e.g., "BA." can become ".AB" or ".AB" can become "BA.").
  3. Tokens can never jump over another token of the same type or over empty spaces.

Note that all movements are fully reversible.

Given a start configuration and an end configuration, return True if it is possible to reach end from start via a sequence of valid moves, and False otherwise. Both input strings are guaranteed to have identical counts of 'A', 'B', and '.'.

Function Signature

def can_transform(start: str, end: str) -> bool:

Constraints

  • $1 \le N \le 10^5$
  • start and end consist only of characters 'A', 'B', and '.'.
  • Your algorithm should run in $O(N)$ time complexity and use $O(1)$ auxiliary space beyond the input strings.

Examples

Example 1:

  • Input: start = "A.B", end = "B.A"
  • Output: False
  • Explanation: Pieces 'A' and 'B' cannot pass past each other under the movement rules.

Example 2:

  • Input: start = "BA..", end = "..AB"
  • Output: True
  • Explanation: "BA.." can be transformed to ".AB." by jumping 'B' over 'A', and then sliding 'A' and 'B' into their final positions.

Hints

Hint 1

Observe which operations preserve the relative order of non-empty characters.

Hint 2

Can an 'A' or 'B' token leap over another token of its own type, or can 'A' leap over 'B'?

Hint 3

Since 'A' can move left or right through empty spaces, and 'B' can leap past 'A' into empty spaces, analyze whether there are any actual positional restriction invariants.