← Questions

Can left and right pieces slide into a target string

0
GoogleCodingLast asked Jul 2025

A coding interview question asked in Google's first round (coding), last asked Jul 2025. It tests two pointers and strings.

Two strings of equal length use four characters: . is an empty slot, X is a wall that never moves, L is a piece that can slide left into empty slots, and R a piece that can slide right into empty slots. Pieces never pass through other pieces or walls, and one cell holds one thing at a time. Decide whether start can be turned into target by valid moves, in O(n) time and O(1) extra space.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • can_transform(start: str, target: str) -> bool — False if the lengths differ.

Example

can_transform("R...L", "RL...")   ->  True     # L slides from 4 to 1
can_transform(".R.X",  "..RX")    ->  True
can_transform("..L",   "L..")     ->  True
can_transform("L..",   "..L")     ->  False    # L can't move right
can_transform("R.X.L", "..XRL")   ->  False    # R would have to cross the wall
can_transform("R.L.",  "..LR")    ->  False    # R and L would have to pass each other
can_transform("RX..",  "X.R.")    ->  False    # walls never move

Constraints

  • 0 <= n <= 10^5.

Clarifying questions

  • Can a piece move several cells in one move, or one at a time? (It doesn't change the answer.)
  • Can pieces jump over each other or over walls?
  • Are walls in fixed positions in both strings?
  • Are the strings always the same length?

What a strong answer covers

  • Invariants: the sequence of non-dot characters (pieces and walls, in order) never changes, because nothing can pass anything else.
  • Then three position checks on the k-th non-dot character of each string: an L must not end to the right of where it started, an R must not end to its left, and an X must stay put. A wall between a piece's two positions is already ruled out by the order check.
  • Two pointers that skip dots and compare one pair at a time. O(n) time, O(1) space.
  • A short argument that the checks are also sufficient: process Rs from the right and Ls from the left and each can reach its target.
  • Tests: empty strings, no pieces, adjacent pieces with no gaps, blocks separated by walls.

Follow-ups

  • Return the minimum number of single-cell moves.
  • Pieces may move at most k cells in total.
  • Add a piece that can move in both directions.

Where it's asked

  • Google · First round: coding · Last asked Jul 202545 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI

What it tests

two pointers · strings

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding