Problem solution · C++

Isscramble

Isscramble: a C++ solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Depth-first search
Source
Kamyu LeetCode Solutions
Length
42 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Isscramble, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 42 lines of C++ from the credited upstream file isScramble.cpp.
  • The implementation visibly relies on ordered lookup.
  • 2 loop blocks detected.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeIsscramble · C++C++
Use this to learn the idea, then write your own version.
// Time Complexity: O(n^4),  due to enumeration of n, i, j, k in (f[n][i][j] and k)// Space Complexity: O(n^3), due to hash of f[n][i][j] class Solution {    public:        bool isScramble(string s1, string s2) {            if(s1.size() != s2.size())                return false;            return isScramble(s1.size(), s1.begin(), s2.begin());        }    private:        typedef string::const_iterator Iterator;        map<tuple<int, Iterator, Iterator>, bool> hash;         bool isScramble(int n, Iterator s1, Iterator s2) {            // hash            if( hash.find(make_tuple(n, s1, s2)) != hash.end()) return hash[make_tuple(n, s1, s2)];             if(n == 1) return *s1 == *s2;             // pruning            int value1 = 0, value2=0;            for (auto it1 = s1, it2 = s2; it1 != s1 + n; ++it1, ++it2) {                value1 += (*it1-'a');                value2 += (*it2-'a');            }            if (value1 != value2)                return hash[make_tuple(n, s1, s2)] = false;              // recursive            for(int k = 1; k < n; ++k) {                if((isScramble(k, s1, s2) && isScramble(n - k, s1 + k, s2 + k))                        || (isScramble(k, s1, s2 + n - k) && isScramble(n - k, s1 + k, s2)) ) {                    return hash[make_tuple(n, s1, s2)] = true;                }            }             return hash[make_tuple(n, s1, s2)] = false;        } }; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗