Skip to content

Commit c240e99

Browse files
committed
Two-Hundred-Eighty-Six Commit: Amend Tree_Depth_First_Search_Tutorial.txt in Tree Depth First Search section
1 parent be69358 commit c240e99

File tree

2 files changed

+315
-229
lines changed

2 files changed

+315
-229
lines changed

src/Tree_Breadth_First_Search/Tree_Breadth_First_Search_Pattern_Tutorial.txt renamed to src/Tree_Breadth_First_Search/Tree_Breadth_First_Search_Tutorial.txt

Lines changed: 78 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -167,108 +167,109 @@ Tree: Breadth-First Search (BFS)
167167
In summary, level-order traversal (BFS) is an important method for tree traversal that processes nodes level by level,
168168
ensuring that all nodes at a given level are visited before moving on to the next level.
169169

170-
Tree: Breadth-First Search Example LeetCode Question: 109. Convert Sorted List to Binary Search Tree
171-
=====================================================================================================
170+
Tree: Breadth-First Search Example LeetCode Question: 301. Remove Invalid Parentheses
171+
=====================================================================================
172172

173-
To convert a sorted singly linked list into a height-balanced binary search tree (BST), you can use a divide-and-conquer
174-
approach. This method ensures that the tree is balanced by recursively finding the middle element of the linked list to use
175-
as the root of the tree (or subtree). Here's how you can implement this in Java, along with the time and space complexity analysis
173+
To solve the problem of removing the minimum number of invalid parentheses to make the input string valid, you can use a
174+
breadth-first search (BFS) approach. This approach systematically tries to remove each parenthesis and checks if the resulting
175+
string is valid. BFS ensures that the first valid string(s) found will have the minimum number of removals
176176
(ChatGPT coded the solution 🤖).
177177

178-
1. Java Implementation
178+
* Here's a Java implementation of this approach:
179+
-----------------------------------------------
179180

180-
* ListNode and TreeNode Definitions:
181-
------------------------------------
181+
import java.util.*;
182182

183-
First, define the `ListNode` and `TreeNode` classes:
183+
public class Solution {
184+
public List<String> removeInvalidParentheses(String s) {
185+
List<String> result = new ArrayList<>();
186+
if (s == null) return result;
184187

185-
class ListNode {
186-
int val;
187-
ListNode next;
188-
ListNode(int x) {
189-
val = x;
190-
next = null;
191-
}
192-
}
188+
Set<String> visited = new HashSet<>();
189+
Queue<String> queue = new LinkedList<>();
193190

194-
class TreeNode {
195-
int val;
196-
TreeNode left;
197-
TreeNode right;
198-
TreeNode(int x) {
199-
val = x;
200-
left = null;
201-
right = null;
202-
}
203-
}
191+
// Initialize
192+
queue.add(s);
193+
visited.add(s);
194+
boolean found = false;
204195

205-
* Conversion Function:
206-
----------------------
196+
while (!queue.isEmpty()) {
197+
String str = queue.poll();
207198

208-
Now, write the function to convert the sorted linked list to a height-balanced BST:
199+
if (isValid(str)) {
200+
result.add(str);
201+
found = true;
202+
}
209203

210-
public class Solution {
211-
private ListNode current;
204+
if (found) continue;
212205

213-
public TreeNode sortedListToBST(ListNode head) {
214-
if (head == null) return null;
206+
for (int i = 0; i < str.length(); i++) {
207+
if (str.charAt(i) != '(' && str.charAt(i) != ')') continue;
208+
String t = str.substring(0, i) + str.substring(i + 1);
215209

216-
// Get the size of the linked list
217-
int size = getSize(head);
218-
current = head;
210+
if (!visited.contains(t)) {
211+
queue.add(t);
212+
visited.add(t);
213+
}
214+
}
215+
}
219216

220-
// Build the BST
221-
return sortedListToBSTHelper(size);
217+
return result;
222218
}
223219

224-
private int getSize(ListNode head) {
225-
int size = 0;
226-
while (head != null) {
227-
head = head.next;
228-
size++;
220+
private boolean isValid(String s) {
221+
int count = 0;
222+
for (char c : s.toCharArray()) {
223+
if (c == '(') count++;
224+
if (c == ')') {
225+
if (count == 0) return false;
226+
count--;
227+
}
229228
}
230-
return size;
229+
return count == 0;
231230
}
232231

233-
private TreeNode sortedListToBSTHelper(int size) {
234-
if (size <= 0) return null;
235-
236-
// Recursively form the left half
237-
TreeNode left = sortedListToBSTHelper(size / 2);
238-
239-
// The root node will be the current node
240-
TreeNode root = new TreeNode(current.val);
241-
root.left = left;
232+
public static void main(String[] args) {
233+
Solution solution = new Solution();
234+
String input = "()())()";
235+
List<String> result = solution.removeInvalidParentheses(input);
236+
for (String str : result) {
237+
System.out.println(str);
238+
}
239+
}
240+
}
242241

243-
// Move to the next element
244-
current = current.next;
242+
* Explanation:
243+
--------------
245244

246-
// Recursively form the right half and link it to the root
247-
root.right = sortedListToBSTHelper(size - 1 - size / 2);
245+
1. Initialization:
246+
- Use a queue to facilitate BFS.
247+
- Use a set to keep track of visited strings to avoid processing the same string multiple times.
248248

249-
return root;
250-
}
251-
}
249+
2. BFS:
250+
- Start with the original string in the queue.
251+
- For each string, if it's valid (checked by `isValid` function), add it to the result list and set the
252+
`found` flag to `true`.
253+
- If not found yet, generate all possible strings by removing one parenthesis at each position and add them
254+
to the queue if they haven't been visited.
252255

253-
* Explanation
256+
3. Validity Check:
257+
- The `isValid` function checks if a given string has balanced parentheses by counting the number of open
258+
and close parentheses.
254259

255-
1. Get the Size:
256-
- First, calculate the size of the linked list.
257-
2. Recursive Conversion:
258-
- Use a recursive helper function `sortedListToBSTHelper` to convert the list to a BST.
259-
- This function constructs the left subtree, then uses the current node as the root, and finally constructs
260-
the right subtree.
260+
4. Termination:
261+
- The BFS ensures that the first valid string(s) found will have the minimum number of removals. Once a valid
262+
string is found, only process strings of the same level to ensure minimum removals.
261263

262264
* Time and Space Complexity
263265

264-
- Time Complexity: O(N)
265-
- Each node in the list is processed exactly once, and each tree node is created exactly once. Thus, the overall
266-
time complexity is O(N), where N is the number of nodes in the linked list.
266+
- Time Complexity: O(N * 2^N)
267+
- Each level of BFS can have up to 2^N strings, where N is the length of the string. Each validity check
268+
takes O(N). Therefore, in the worst case, the time complexity is O(N * 2^N).
267269

268-
- Space Complexity: O(log N)
269-
- The space complexity is primarily due to the recursion stack used in the `sortedListToBSTHelper` function.
270-
Since the function is building a balanced BST, the height of the tree (and hence the depth of the recursion)
271-
will be O(log N). Therefore, the space complexity is O(log N).
270+
- Space Complexity: O(2^N)
271+
- The space complexity is dominated by the queue and the visited set, both of which can grow up to 2^N in size,
272+
where N is the length of the string.
272273

273-
This solution ensures that the resulting binary search tree is height-balanced and that the conversion is performed
274-
efficiently.
274+
This BFS-based solution is efficient for finding all valid strings with the minimum number of invalid parentheses removed,
275+
ensuring all unique solutions are returned.

0 commit comments

Comments
 (0)