KatInterview

Sliding Tokens: Valid String Transformation

StringsAuto-graded · 31 test cases
MediumAuto-gradedStringstwo-pointersgreedyinvariants

Last updated

Tests two-pointer traversal, sequence invariants, and directional movement constraints with O(n) time and O(1) space.

You are given two strings initial and final of equal length n. Each string contains only the characters 'L', 'R', '.', and 'X'.

  • '.' represents an empty position
  • 'X' represents a fixed obstacle
  • 'L' and 'R' are movable tokens

Tokens can slide into adjacent empty positions according to these movement rules:

  1. An 'L' token can slide left any number of positions into empty slots ('.'), but cannot move right
  2. An 'R' token can slide right any number of positions into empty slots ('.'), but cannot move left
  3. No token can move through another token, through an obstacle ('X'), or occupy the same position as another token

Return true if final can be obtained from initial through a sequence of valid token moves, otherwise return false.

Your solution should run in O(n) time and use O(1) extra space.

Constraints

  • 1 <= len(initial) == len(final) <= 10^5
  • Both strings contain only 'L', 'R', '.', and 'X'

Examples

Example 1

Input: is_transformation_valid('R.L', 'R.L')

Output: True

Example 2

Input: is_transformation_valid('R.L', 'RL.')

Output: True

Example 3

Input: is_transformation_valid('L.X', 'XL.')

Output: False

Hints

Hint 1

Token movements never change the relative order of non-empty characters. Think about what this means for comparing the two strings.

Hint 2

An L token can only decrease its position (move left), and an R token can only increase its position (move right). Use two pointers to match up corresponding tokens.

Hint 3

Skip over all dots and compare the sequences of tokens and obstacles directly. Each token type has a direction constraint on how far it can have moved.