Problem 584740 · hard · Phase 05 Advanced Algorithms & Graphs

The Cipher Clerk's Cut-and-Swap

dynamic programming · interval DP · strings · memoization

A cipher clerk disguises a word with this procedure, applied to the whole word:

  • A piece of length 1 is left as it is.
  • A longer piece is cut into two non-empty parts at any place the clerk likes. She may swap the two parts or keep their order, and then applies the same procedure to each part separately.

Given the clerk's input original and a string received, return True if the procedure can turn original into received for some choice of cuts and swaps, and False otherwise. Two empty strings count as a match.

Examples

Input:  original = "baker", received = "kerba"
Output: True
Explanation: cut "ba|ker" and swap the parts.

Input:  original = "abcd", received = "bdac"
Output: False

Input:  original = "stone", received = "notes"
Output: True

Constraints

  • 0 <= len(original), len(received) <= 30
  • both strings contain lowercase letters only

Goals

  • Describe a recursive rearrangement by pairs of equal-length pieces
  • Index states by two start positions and a length
  • See why plain recursion explodes even with an anagram check
Starting Python…