Skip to content

Commit e7c5461

Browse files
committed
Commit
1 parent 10873a1 commit e7c5461

File tree

2 files changed

+277
-0
lines changed

2 files changed

+277
-0
lines changed
Lines changed: 277 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,277 @@
1+
---
2+
id: BFS-traversal-of-graph
3+
title: BFS Traversal of Graph (Geeks for Geeks)
4+
sidebar_label: BFS Traversal of Graph
5+
tags:
6+
- Intermediate
7+
- Graph
8+
- Breadth-First Search
9+
- Geeks for Geeks
10+
- CPP
11+
- Python
12+
- DSA
13+
description: "This is a solution to the BFS Traversal of Graph problem on Geeks for Geeks."
14+
---
15+
16+
## Problem Description
17+
18+
Given two strings S1 and S2 of equal length, the task is to determine if S2 is a scrambled form of S1.
19+
20+
Scrambled string: Given string str, we can represent it as a binary tree by partitioning it into two non-empty substrings recursively.
21+
Below is one possible representation of str = coder:
22+
![alt text](image.png)
23+
To scramble the string, we may choose any non-leaf node and swap its two children.
24+
Suppose, we choose the node co and swap its two children, it produces a scrambled string ocder.
25+
Similarly, if we continue to swap the children of nodes der and er, it produces a scrambled string ocred.
26+
27+
Note: Scrambled string is not the same as an Anagram.
28+
Print "Yes" if S2 is a scrambled form of S1 otherwise print "No".
29+
30+
31+
## Examples
32+
33+
**Example:**
34+
35+
Consider the following graph:
36+
37+
```
38+
ocder
39+
/ \
40+
oc der
41+
/ \
42+
o c
43+
```
44+
**Input:** S1="coder", S2="ocder"
45+
**Explanation:** ocder is a scrambled
46+
form of coder.
47+
**Output:** Yes
48+
49+
## Your Task
50+
51+
You don't need to read input or print anything. You only need to complete the function isScramble() which takes two strings S1 and S2 as input and returns a boolean value.
52+
53+
Expected Time Complexity: $O(N2)$.
54+
Expected Auxiliary Space: $O(N2)$.
55+
56+
## Constraints
57+
58+
- S1.length = S2.length
59+
- S1.length<=31
60+
- S1 and S2 consist of lower-case English letters.
61+
62+
## Problem Explanation
63+
64+
Here's the step-by-step breakdown of the Scrambled String process:
65+
66+
**Step 1 :** A scrambled string is defined based on recursive partitioning and swapping of substrings. Here’s a more detailed explanation:
67+
68+
**Step 2 :** Binary Tree Representation:Given a string str, you can represent it as a binary tree by recursively partitioning it into two non-empty substrings.
69+
**Step 3 :** For example, for the string "coder": You can split it into "co" and "der".
70+
Each of these can be further split recursively, forming a binary tree structure.
71+
**Step 4 :**Scrambling: A string S2 is a scrambled form of string S1 if S2 can be obtained by swapping the left and right children of some non-leaf nodes in the binary tree representation of S1.
72+
For instance, "coder" can be scrambled to "ocder" by swapping "co" and "der", then further scrambling "co" to "oc".
73+
74+
### Code Implementation
75+
76+
<Tabs>
77+
<TabItem value="Python" label="Python" default>
78+
<SolutionAuthor name="@ngmuraqrdd"/>
79+
```python
80+
class Solution(object):
81+
def isScramble(self, s1, s2):
82+
"""
83+
:type s1: str
84+
:type s2: str
85+
:rtype: bool
86+
"""
87+
# Base cases
88+
89+
n = len(s1)
90+
91+
# If both strings are not equal in size
92+
if len(s2) != n:
93+
return False
94+
95+
# If both strings are equal
96+
if s1 == s2:
97+
return True
98+
99+
# If code is reached to this condition then following this are sure:
100+
# 1. size of both string is equal
101+
# 2. string are not equal
102+
# so size is equal (where size==1) and they are not equal then obviously false
103+
# example 'a' and 'b' size is equal, string are not equal
104+
if n == 1:
105+
return False
106+
107+
key = s1 + " " + s2
108+
109+
# Check if this problem has already been solved
110+
if key in self.mp:
111+
return self.mp[key]
112+
113+
# For every iteration it can two condition
114+
# 1. We should proceed without swapping
115+
# 2. We should swap before looking next
116+
for i in range(1, n):
117+
# ex of without swap: gr|eat and rg|eat
118+
without_swap = (
119+
# Left part of first and second string
120+
self.isScramble(s1[:i], s2[:i])
121+
and
122+
# Right part of first and second string;
123+
self.isScramble(s1[i:], s2[i:])
124+
)
125+
126+
# If without swap gives us the right answer then we do not need
127+
# to call the recursion with swap
128+
if without_swap:
129+
return True
130+
131+
# ex of with swap: gr|eat rge|at
132+
# here we compare "gr" with "at" and "eat" with "rge"
133+
with_swap = (
134+
# Left part of first and right part of second
135+
self.isScramble(s1[:i], s2[n-i:])
136+
and
137+
# Right part of first and left part of second
138+
self.isScramble(s1[i:], s2[:n-i])
139+
)
140+
141+
# If with swap gives us the right answer then we return True
142+
# otherwise, the for loop does its work
143+
if with_swap:
144+
return True
145+
146+
self.mp[key] = False
147+
return False
148+
149+
# for storing already solved problems
150+
mp = {}
151+
```
152+
</TabItem>
153+
154+
<TabItem value="C++" label="C++" default>
155+
<SolutionAuthor name="@ngmuraqrdd"/>
156+
```cpp
157+
class Solution {
158+
public:
159+
//for storing already solved problems
160+
unordered_map<string,bool> mp;
161+
162+
163+
bool isScramble(string s1, string s2) {
164+
//base cases
165+
166+
int n = s1.size();
167+
168+
//if both string are not equal in size
169+
if(s2.size()!=n)
170+
return false;
171+
172+
//if both string are equal
173+
if(s1==s2)
174+
return true;
175+
176+
177+
178+
//if code is reached to this condition then following this are sure:
179+
//1. size of both string is equal
180+
//2. string are not equal
181+
//so size is equal (where size==1) and they are not equal then obviously false
182+
//example 'a' and 'b' size is equal ,string are not equal
183+
if(n==1)
184+
return false;
185+
186+
string key = s1+" "+s2;
187+
188+
//check if this problem has already been solved
189+
if(mp.find(key)!=mp.end())
190+
return mp[key];
191+
192+
//for every iteration it can two condition
193+
//1.we should proceed without swapping
194+
//2.we should swap before looking next
195+
for(int i=1;i<n;i++)
196+
{
197+
198+
//ex of without swap: gr|eat and rg|eat
199+
bool withoutswap = (
200+
//left part of first and second string
201+
isScramble(s1.substr(0,i),s2.substr(0,i))
202+
203+
&&
204+
205+
//right part of first and second string;
206+
isScramble(s1.substr(i),s2.substr(i))
207+
);
208+
209+
210+
211+
//if without swap give us right answer then we do not need
212+
//to call the recursion withswap
213+
if(withoutswap)
214+
return true;
215+
216+
//ex of withswap: gr|eat rge|at
217+
//here we compare "gr" with "at" and "eat" with "rge"
218+
bool withswap = (
219+
//left part of first and right part of second
220+
isScramble(s1.substr(0,i),s2.substr(n-i))
221+
222+
&&
223+
224+
//right part of first and left part of second
225+
isScramble(s1.substr(i),s2.substr(0,n-i))
226+
);
227+
228+
229+
230+
//if withswap give us right answer then we return true
231+
//otherwise the for loop do it work
232+
if(withswap)
233+
return true;
234+
//we are not returning false in else case
235+
//because we want to check further cases with the for loop
236+
}
237+
238+
239+
return mp[key] = false;
240+
241+
}
242+
};
243+
```
244+
</TabItem>
245+
</Tabs>
246+
247+
## Solution Logic
248+
249+
**1.Base Cases:**If the lengths of the two strings are not equal, they cannot be scrambled forms of each other, so return false.
250+
If the two strings are identical, they are trivially scrambled forms of each other, so return true.
251+
If the length of the string is 1 and the strings are not equal, return false.
252+
**2.Memoization:** Use a map mp to store already solved subproblems to avoid redundant computations.
253+
The key for the map is a combination of the two strings, represented as s1 + " " + s2.
254+
**3.Recursive Check:** Iterate over possible split points of the strings.
255+
For each split point, there are two cases to consider:
256+
1.Without swapping:
257+
Compare the left part of s1 with the left part of s2 and the right part of s1 with the right part of s2.
258+
2.With swapping:
259+
Compare the left part of s1 with the right part of s2 and the right part of s1 with the left part of s2.
260+
**4.Return Result:** If either of the conditions (with or without swapping) is satisfied, return true.
261+
If none of the conditions are satisfied after checking all possible split points, store the result as false in the memoization map and return false.1.
262+
263+
## Time Complexity
264+
265+
$O(N2)$.
266+
267+
## Space Complexity
268+
269+
$O(N2)$.
270+
271+
## Resources
272+
273+
- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/problems/scrambled-string/1)
274+
- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/scramble-string/description/)
275+
- **Author's Geeks for Geeks Profile:** | [DaminiChachane](https://leetcode.com/u/divcxl15/) |
276+
277+
This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow.
Loading

0 commit comments

Comments
 (0)