Skip to content
Problem 777 · LeetCode 777(opens in a new tab)

Swap Adjacent in LR String

MediumStrings

You get two strings, start and result, of the same length, made of the letters L, R and X. One move rewrites a pair of neighbours: XL may become LX, or RX may become XR.

Return true if some sequence of moves turns start into result, and false otherwise.

Example 1

Input:  start = "RXXLX", result = "XRLXX"
Output: true
Why:    RXXLX → XRXLX → XRLXX; the R steps right, the L steps left
2 more examples and the constraints

Example 2

Input:  start = "RL", result = "LR"
Output: false
Why:    the L and the R would have to pass through each other

Example 3

Input:  start = "XXR", result = "RXX"
Output: false
Why:    an R can only move right, never left

Constraints

  • 1 ≤ start.length ≤ 10,000
  • result.length == start.length
  • Both strings use only the letters L, R and X.

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Strip the X's and compareO(n)
  2. Two pointers, no listsO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 10,000Verdict
Strip the X's and compareO(n)
Fine; builds two lists
Two pointers, no listsO(n)
Best; one pass, no extra memory

n = length of the strings.

Edge cases to test

  • Identical strings. Zero moves are needed: true.
  • Different piece counts. "X" against "L": a piece cannot appear from nowhere, so false.
  • Pieces would cross. "RL" against "LR": the letter order changed, so false.
  • Only X's. Both strings are all X: nothing to check, true.
  • Long slide. An L at the far right can slide all the way to index 0 through 9,999 X's.

Common mistakes

  • Comparing only the letter order and forgetting the direction rule, so "XXR" to "RXX" wrongly passes.
  • Mixing up the directions: L moves left (index may only drop), R moves right (index may only grow).
  • Stopping when one pointer reaches the end without checking that the other has no pieces left.

How to talk through it

  1. 1Clarify. Same length always? Only L, R and X? (Yes.)
  2. 2Reframe the moves. X is a blank. L slides left into blanks, R slides right, and they cannot pass each other.
  3. 3State the invariant. Non-X letters keep their order; each L ends at or left of its start, each R at or right.
  4. 4Check with two pointers. Skip X's in both strings and compare pieces pairwise, O(n) time and O(1) space.
  5. 5Test out loud. Try "RL" vs "LR" (false), "XXR" vs "RXX" (false), and Example 1 (true).
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?