Can left and right pieces slide into a target string
I was asked this
No reports yet. Sign in to say where you were asked it.
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—Falseif 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
Lmust not end to the right of where it started, anRmust not end to its left, and anXmust 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 andLs 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
kcells 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
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
