Scramble String

Hard · Dynamic Programming · String · Dynamic Programming

Problem

You can scramble a string s like this:

Given two strings s1 and s2 of the same length, return true if s2 can be produced by scrambling s1, and false otherwise.

Examples

Input: s1 = "abcd", s2 = "cdba"
Output: true

Split into ab | cd and swap to get cdab, then split ab and swap it to get cdba.

Input: s1 = "abcd", s2 = "bdac"
Output: false

The letters match, but no sequence of splits and swaps turns abcd into bdac.

Input: s1 = "a", s2 = "a"
Output: true

A single letter cannot be split; the strings are already equal.

Constraints

Approaches

Follow-up

Bottom-up the DP has n³ states and n splits each, so n = 30 costs under a million steps. The letter-count check does not change the worst case, but it cuts most branches in practice, which is why the top-down version is usually much faster on real inputs.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…