707514. Scrambled String
Scrambled String
Slug: scrambled-string
Difficulty: Hard
Id: 707514
Topic Tags: Strings, Recursion, Divide and Conquer, Tree, Data Structures, Algorithms
Company Tags: Nutanix
Summary
The Scrambled String problem involves finding the original string from a given scrambled string. The scrambled string is represented as a tree where each node contains a character and two child nodes representing the left and right subtrees. The goal is to find the original string by traversing this tree.
Detailed Explanation
To solve this problem, we can use a recursive approach. We start at the root of the tree and recursively traverse it. For each node, we append its character to our result string if it's not null or empty. If the left child is not null or empty, we recursively call ourselves on that subtree and then do the same for the right child.
Here's a step-by-step breakdown of the solution:
- Start at the root of the tree.
- Check if the node is null or empty. If it is, return an empty string.
- Append the character in the current node to our result string.
- Recursively call ourselves on the left child subtree and then do the same for the right child subtree.
- Return the resulting string.
Here's a simple ASCII art diagram of the tree:
*
/ \
- * / \ / \
Time complexity: O(n), where n is the number of nodes in the tree. Space complexity: O(n), where n is the length of the original string.
Optimized Solutions
Java
class Node {
char val;
Node left, right;
public Node(char v) {
val = v;
left = null;
right = null;
}
}
public class ScrambledString {
public String unscramble(Node root) {
StringBuilder result = new StringBuilder();
unscramble(root, result);
return result.toString();
}
private void unscramble(Node node, StringBuilder result) {
if (node == null) {
return;
}
result.append(node.val);
unscramble(node.left, result);
unscramble(node.right, result);
}
}