Generate All Palindromic Decompositions Of A String ("Palindrome Partitioning" on Leetcode)

Back To Back SWE · Beginner ·⚡ Algorithms & Data Structures ·7y ago

Key Takeaways

This video teaches how to generate all palindromic decompositions of a string using the Palindrome Partitioning algorithm on LeetCode

Full Transcript

LICO dream continues another day another question alright so I have a little secret slash surprise for this video we're not going to learn anything new today we are just going to do something we already know how to do so I've covered a lot of backtracking videos and kind of the thing that I want from this channel is for you to internalize the patterns between these questions many questions will have tiny little like heuristics slash leg tricks you can use to solve that but whenever we're tackling these software engineering questions there's I think 15 key like large buckets that these questions fit into which I like delineate in my how to get a job at Google video although I've never worked at Google but these are just the patterns of these questions today we're going to do a backtracking question that fits right into the pattern of string decomposition and it's going to be approached exactly how we tackle other problems like n-queens decomposition of an IP address and many other backtracking problems I've done we're not going to learn anything new today we're just going to apply what we already know and let's see how we apply that right today's question is generate all palindromic decompositions of a string this sounds very intimidating but it is not intimidating we're gonna get output as a string and we're going to decompose that string break it up chop it into pieces each of those pieces are going to be a palindrome this is a palindrome a single letter is a palindrome and mirrors on itself because it's just a single letter it's basically like a base case single letter palindrome single letters all decompositions all these decompositions take away the commas collapse them back together and there are our original string so I want you to notice in the problem giving a string return all decompositions of that string what do you notice the key terms are in this question return all and anytime it's a problem with dealing with decompositions we are going to be exploring a space of decisions exploring a space of possibilities of ways we could go cutting the string up if we explore all those ways and keep our constraints in mind we will be able to answer this question effectively another thing to keep in mind is array and strings these are kind of inserting interchangeable string is just an abstraction of an array characters just keep this in mind so we literally could decompose an array doing backtracking you can decompose a string the reason I said this is something we already know how to do is because we've already covered questions like this we've already done backtracking questions like this so the approach is not going to be any different we're going to advance through this string try different decompositions make choices backtrack on those choices and collect all possibilities when we reach our goal so now let's look at the approaches as well as the three keys to backtracking for this problem for this problem we have two major choices we have the brute force choice where we can generate all decompositions and what we do is we have all these decompositions some are palindromic some are not palindromic we need to validate every single string in that decomposition to check if it's a palindrome and therefore we only add the palindromic decompositions or answer this is brute force what is the problem with this why is this a problem first off we're going to be doing unnecessary work and generating all of these decompositions and second off if we add a non palindrome to our decomposition we instantly disqualify the answer we're going to follow a search tree of decomposition on a decomposition that cannot even be an answer that is a waste of time and that is not the track that we want to go so the key is we need to direct our recursion and we need to choose paths that will yield us an answer we already know this we know the three keys to recursion that I've covered in other videos the three keys to our backtracking are going to be what is our choice we are going to choose a substring to recurse on we're going to have a pointer we're going to take a snippet of the string so I take a significance is ero so then I take a snippet from index 0 to 1 so then I take a snippet of index 0 to 2 and this is the top of our recursion this is our first choice and then what we do is we're going to recurse into that toys and what we need to do is we need to make Evert shirt every sniff we recurse on must be a palindrome or else we are generating an invalid decomposition we're doing unnecessary work we do not want to follow path on a decomposition a decomposed piece that is not a palindrome every piece must be a palindrome our constraints this is simple this is a formula our constraint is that every snippet must be a palindrome we're going to choose a snippet or curse chooses if it recurs and every one of those snippets must be a palindrome when are we finished number three our goal what is our goal our goal is to decompose the whole string our goal is to get our decomposition points are out of bounds when it is out of bounds and equals the length of the string which is indexed to 1 out of bounds we're going to note we have decomposed the whole string we have expressed a potentiality and we can backtrack and express more potential answers this is the key to backtracking these are the three keys so now let's look at the code for this answer and walk through how it does this and again we are not learning anything new we are seeing the patterns we were seeing how patterns apply to other questions all right so a quick thank you to Alex loom at up the hell only code that is a very interesting name um thank you to him for this code and I just adapted it the code is below in github all I did is reformat it I added a ton of comments so that you can understand this but I'm gonna walk through here on the whiteboard so you can see a walk through as well okay we're just going through the same pattern this is the same format we applied to these backtracking problems we understand our choice we understand our constraints or understand or goal up here we have a driver function our driver function creates our list for all of the valid e compositions and creates a list for the decomposition we are working on at the moment through our recursion we hit the play button on our recursion we go into our recursion and our goal is going to be we want to advance our pointer our builds pointer past the array once we are at the arrays length once it builds pointer is at the arrays length then we know we have a value decomposition because up to the points of the base case we were only adding palindromes what we have in our base case is now a palindromic decomposition every one of our choices was within the constraints when we get through the base case we have stayed within the constraints and we have an answer our goal is what crafts our base case and we know that our answer is going to be valid when we reach that base case what we do is we make a decision we start from our builds pointer to the end of the string we take sniffing sniffing sniffing sniffing cut pieces and we validate each of those pieces is that piece of palindrome I don't have to help her here but you can see it in github it's a simple palindrome validation function we see is the snippet that I took a palindrome if it is added to add it to our progress and continue and continue our recursion with our builds points are now pointing at one after the position of the end of our snippet so now we are going to be able to take our snippet and then move on express all the possibilities move on so this is the key and what we do is when this search is over after we have finished exploring all of our options we are going to return to this stack frame each one of these calls is a policy it is a stack frame that expresses potential once that potential is expressed we return to where we were and we're going to hit this line when we come to this line we remove the snippet we just explored on and we choose another significant for example if I have the string AAV I can choose pain and then what I do is my top-level stack frame has three choices it can choose the string of just a or a a or a a B if I choose just a then now I can recurse and I can choose from the rest of the string and then after all that searching is done I return to this top stack frame and now my next top level choice can be a a that is also a palindrome and then i recurse and then that exploring she finishes I come back upwards my next choice is a a B and what happens is then we go to the bottom aap would not even be a path followed because it is not a palindrome now this is our code this is how we do it this is the same pattern and when I told you at the start of this video we wouldn't learn anything new today we have not learned anything new today we just reapplied what we know we reapplied our three keys our choice constraints and gold choice constraints goal we reapplied how we know to do backtracking to solve this problem within the constraints given we have not learned anything new we reapplied what we know and this is the key this is what I want to get at through this channel through these videos I want us to see the patterns so that we can be flexible in answering these questions so now let's look at the time complexities for this solution okay and now let us consider the worst case time and space complexity let us bound the time and space of this of this operation so what is the worst case the worst case we can have is n repetitions and I forgot to do a key thing a key thing is always defined what n is what are the variables in these functions that you're bounding along and is the length of the string and we have and the repetitions of a single character every single decomposition of this string is going to be palindrome and therefore we are going to be yielded the two to the N minus 1 total decompositions all of them will be answers we are going to spend that time computing all of them because they are all decompositions that consists of only palindromes therefore the upper bound we can put on our time is 2 to the N and we spent in linear time in each of the calls we spend linear time and each of the calls so we do many times 2 to the N that is how we bound our time so the way we bound our space is the worst case space complexity is going to be controlled by our call stack we are using recursion we are going to make at max and death on the call stack and what does that look like and we take a snippet a if we take a simple sip a from the overall stream hey we're going to have a depth of three on the call stack what is n n is three that means we are going to use open space as our string increases linearly in length or space is going to increase in a linear fashion as well constants do not matter you are we worried about tail behavior this is the time and space complexity for this problem and this is how we are going to bound it so if you liked this video hit the like button and subscribe to the channel I want to do videos like this every day I have so many topics to cover I have no idea whether I'm going to be able to do all of them this year because it's just hundreds of questions but I want to try my best to establish these patterns I think I've gotten a solid basis in the backtracking front in terms of problem type but there's so many other problem types to explore and see these patterns in my goal is to establish a pattern you can see in all the property types so you can enter the interview and have all the tools you need to succeed so this is what this is all about [Music]

Original Description

Free 5-Day Mini-Course: https://backtobackswe.com Try Our Full Platform: https://backtobackswe.com/pricing 📹 Intuitive Video Explanations 🏃 Run Code As You Learn 💾 Save Progress ❓New Unseen Questions 🔎 Get All Solutions Question: Given a string, return all decompositions of the string that consist of only palindromes. Example: Input: "aab" Output: [ ["aa","b"], ["a","a","b"] ] Why is this problem backtracking? It is backtracking because we will be expressing all of the possibilities of a search space given constraints. When we need to represent many decisions and possibilities, backtracking is the tool you should pull from your pocket. Approach 1 Generate all decompositions and then only add the palindromic decompositions to our answer. This is highly exponential in time since there are 2^(n - 1) palindromic decompositions. This wastes a lot of time since we will continue to build on a decomposition that immediately disqualifies as palindromic. Approach 2 We will take "snapshots" of snippets as we advance through the string and see if they can add to the decomposition that we want to build. The 3 Keys To Backtracking: Our Choice The start and the end of a "snapshot" that we want to add to a decomposition we are working on. Our Constraints Each piece of the decomposition must be a palindrome, we cannot choose and advance on a non-palindrome snippet. Our Goal Decompose the whole string. When our decomposition progress index is the length of the array then we know that we have achieved this. Complexities Time: O(n * (2^n)) Worst case, but much better than approach 1 since this is a rare worst case where all decompositions turn out to be palindromic (a string of all 1 character). Our best case becomes greatly improved. We are basically taking subsets so (2^n) and the O(n) time to copy array to our answer. Space: O(n) At worst we will always go n stack frames deep in our recursion since an all single character decomposition is a
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Back To Back SWE · Back To Back SWE · 19 of 60

1 4 Tips To Learn Java Programming As Fast As Possible As A Beginner
4 Tips To Learn Java Programming As Fast As Possible As A Beginner
Back To Back SWE
2 3 Mistakes Beginners Make When First Learning Java and Android Development
3 Mistakes Beginners Make When First Learning Java and Android Development
Back To Back SWE
3 How To Get A Job At Google | The Ultimate Guide To Algorithmic/Coding Interviews
How To Get A Job At Google | The Ultimate Guide To Algorithmic/Coding Interviews
Back To Back SWE
4 The Ultimate Big O Notation Tutorial (Time & Space Complexity For Algorithms)
The Ultimate Big O Notation Tutorial (Time & Space Complexity For Algorithms)
Back To Back SWE
5 Total Occurrences Of K In A Sorted Array (Facebook Software Engineering Interview Question)
Total Occurrences Of K In A Sorted Array (Facebook Software Engineering Interview Question)
Back To Back SWE
6 The N Queens Problem using Backtracking/Recursion - Explained
The N Queens Problem using Backtracking/Recursion - Explained
Back To Back SWE
7 Compute All Mnemonics For A Phone Number (Recursion/Backtracking Problem)
Compute All Mnemonics For A Phone Number (Recursion/Backtracking Problem)
Back To Back SWE
8 How To Reverse A Singly Linked List | The Ultimate Explanation (Iteratively & Recursively)
How To Reverse A Singly Linked List | The Ultimate Explanation (Iteratively & Recursively)
Back To Back SWE
9 Depth First & Breadth First Graph Search - DFS & BFS Graph Searching Algorithms
Depth First & Breadth First Graph Search - DFS & BFS Graph Searching Algorithms
Back To Back SWE
10 The 0/1 Knapsack Problem (Demystifying Dynamic Programming)
The 0/1 Knapsack Problem (Demystifying Dynamic Programming)
Back To Back SWE
11 The Dutch National Flag Problem (The Quicksort "Band-Aid")
The Dutch National Flag Problem (The Quicksort "Band-Aid")
Back To Back SWE
12 Test If A Binary Tree Is Symmetric ("Symmetric Tree" on Leetcode)
Test If A Binary Tree Is Symmetric ("Symmetric Tree" on Leetcode)
Back To Back SWE
13 The IP Address Decomposition Problem - Compute All Valid IP Addresses From Raw IP String
The IP Address Decomposition Problem - Compute All Valid IP Addresses From Raw IP String
Back To Back SWE
14 How To Permute A String - Generate All Permutations Of A String
How To Permute A String - Generate All Permutations Of A String
Back To Back SWE
15 The Balanced Parentheses Problem - Classic Stack Problem ("Valid Parentheses" on Leetcode)
The Balanced Parentheses Problem - Classic Stack Problem ("Valid Parentheses" on Leetcode)
Back To Back SWE
16 Knuth–Morris–Pratt (KMP) Pattern Matching Substring Search -  First Occurrence Of Substring
Knuth–Morris–Pratt (KMP) Pattern Matching Substring Search - First Occurrence Of Substring
Back To Back SWE
17 Implement An LRU Cache - The LRU Cache Eviction Policy ("LRU Cache" on LeetCode)
Implement An LRU Cache - The LRU Cache Eviction Policy ("LRU Cache" on LeetCode)
Back To Back SWE
18 Find The Longest Increasing Subsequence - Dynamic Programming Fundamentals
Find The Longest Increasing Subsequence - Dynamic Programming Fundamentals
Back To Back SWE
Generate All Palindromic Decompositions Of A String ("Palindrome Partitioning" on Leetcode)
Generate All Palindromic Decompositions Of A String ("Palindrome Partitioning" on Leetcode)
Back To Back SWE
20 Implement A Sudoku Solver - Sudoku Solving Backtracking Algorithm ("Sudoku Solver" on LeetCode)
Implement A Sudoku Solver - Sudoku Solving Backtracking Algorithm ("Sudoku Solver" on LeetCode)
Back To Back SWE
21 Merge K Sorted Arrays - Min Heap Algorithm ("Merge K Sorted Lists" on LeetCode)
Merge K Sorted Arrays - Min Heap Algorithm ("Merge K Sorted Lists" on LeetCode)
Back To Back SWE
22 Partition To K Equal Sum Subsets From An Array of Integers - The Backtracking Approach
Partition To K Equal Sum Subsets From An Array of Integers - The Backtracking Approach
Back To Back SWE
23 Edit Distance Between 2 Strings - The Levenshtein Distance ("Edit Distance" on LeetCode)
Edit Distance Between 2 Strings - The Levenshtein Distance ("Edit Distance" on LeetCode)
Back To Back SWE
24 Total Ways To Decode A String - Recursive Dynamic Programming Approach ("Decode Ways" on LeetCode)
Total Ways To Decode A String - Recursive Dynamic Programming Approach ("Decode Ways" on LeetCode)
Back To Back SWE
25 The Change Making Problem - Fewest Coins To Make Change Dynamic Programming
The Change Making Problem - Fewest Coins To Make Change Dynamic Programming
Back To Back SWE
26 Compute The Next Permutation of A Numeric Sequence - Case Analysis ("Next Permutation" on Leetcode)
Compute The Next Permutation of A Numeric Sequence - Case Analysis ("Next Permutation" on Leetcode)
Back To Back SWE
27 Count Total Unique Binary Search Trees - The nth Catalan Number (Dynamic Programming)
Count Total Unique Binary Search Trees - The nth Catalan Number (Dynamic Programming)
Back To Back SWE
28 Generate All Strings With n Matched Parentheses - Backtracking ("Generate Parentheses" on LeetCode)
Generate All Strings With n Matched Parentheses - Backtracking ("Generate Parentheses" on LeetCode)
Back To Back SWE
29 Implement A Max Stack - A Stack With A .max() API (Similar To "Min Stack" on LeetCode)
Implement A Max Stack - A Stack With A .max() API (Similar To "Min Stack" on LeetCode)
Back To Back SWE
30 The Recursive Staircase - Top Down & Bottom Up Dynamic Programming ("Climbing Stairs" on LeetCode)
The Recursive Staircase - Top Down & Bottom Up Dynamic Programming ("Climbing Stairs" on LeetCode)
Back To Back SWE
31 Search A Maze For Any Path - Depth First Search Fundamentals (Similar To "The Maze" on Leetcode)
Search A Maze For Any Path - Depth First Search Fundamentals (Similar To "The Maze" on Leetcode)
Back To Back SWE
32 Total Unique Ways To Make Change - Dynamic Programming ("Coin Change 2" on LeetCode)
Total Unique Ways To Make Change - Dynamic Programming ("Coin Change 2" on LeetCode)
Back To Back SWE
33 Test If A Binary Tree Is Height Balanced ("Balanced Binary Tree" on LeetCode)
Test If A Binary Tree Is Height Balanced ("Balanced Binary Tree" on LeetCode)
Back To Back SWE
34 Find The Second Largest Item - Heap & Tracking Approach (Beginner Big N Interview Question)
Find The Second Largest Item - Heap & Tracking Approach (Beginner Big N Interview Question)
Back To Back SWE
35 Increment An Integer Represented As An Array ("Plus One" on LeetCode)
Increment An Integer Represented As An Array ("Plus One" on LeetCode)
Back To Back SWE
36 Merge 2 Sorted Lists - A Fundamental Merge Sort Subroutine ("Merge Two Sorted Lists" on LeetCode)
Merge 2 Sorted Lists - A Fundamental Merge Sort Subroutine ("Merge Two Sorted Lists" on LeetCode)
Back To Back SWE
37 Clone An Undirected Graph - The Utility of Hashtable Mappings ("Clone Graph" on Leetcode)
Clone An Undirected Graph - The Utility of Hashtable Mappings ("Clone Graph" on Leetcode)
Back To Back SWE
38 Clone A Linked List (With Random Pointers) - Linear Space Solution & Tricky Constant Space Solution
Clone A Linked List (With Random Pointers) - Linear Space Solution & Tricky Constant Space Solution
Back To Back SWE
39 Deeply Understanding Logarithms In Time Complexities & Their Role In Computer Science
Deeply Understanding Logarithms In Time Complexities & Their Role In Computer Science
Back To Back SWE
40 Implement A Binary Heap - An Efficient Implementation of The Priority Queue ADT (Abstract Data Type)
Implement A Binary Heap - An Efficient Implementation of The Priority Queue ADT (Abstract Data Type)
Back To Back SWE
41 Max Contiguous Subarray Sum - Cubic Time To Kadane's Algorithm ("Maximum Subarray" on LeetCode)
Max Contiguous Subarray Sum - Cubic Time To Kadane's Algorithm ("Maximum Subarray" on LeetCode)
Back To Back SWE
42 Binary Tree Bootcamp: Full, Complete, & Perfect Trees. Preorder, Inorder, & Postorder Traversal.
Binary Tree Bootcamp: Full, Complete, & Perfect Trees. Preorder, Inorder, & Postorder Traversal.
Back To Back SWE
43 What Is Asymptotic Analysis? And Why Does It Matter? A Deeper Understanding of Asymptotic Notation.
What Is Asymptotic Analysis? And Why Does It Matter? A Deeper Understanding of Asymptotic Notation.
Back To Back SWE
44 An In-Depth Algorithmic Analysis of Bubble Sort. Best Case, Average Case, & Worst Case.
An In-Depth Algorithmic Analysis of Bubble Sort. Best Case, Average Case, & Worst Case.
Back To Back SWE
45 Maximum Sum Rectangle In A 2D Matrix - Kadane's Algorithm Applications (Dynamic Programming)
Maximum Sum Rectangle In A 2D Matrix - Kadane's Algorithm Applications (Dynamic Programming)
Back To Back SWE
46 A Detailed Algorithmic Analysis of Insertion Sort. Best Case & Worst Case.
A Detailed Algorithmic Analysis of Insertion Sort. Best Case & Worst Case.
Back To Back SWE
47 Binary Tree Level Order Traversal - Drawing The Parallel Between Trees & Graphs
Binary Tree Level Order Traversal - Drawing The Parallel Between Trees & Graphs
Back To Back SWE
48 Implement A Queue Using Stacks - The Queue ADT ("Implement Queue Using Stacks" on LeetCode)
Implement A Queue Using Stacks - The Queue ADT ("Implement Queue Using Stacks" on LeetCode)
Back To Back SWE
49 All Nodes Distance K In A Binary Tree - Performing Bidirectional Search On A Tree Using A Hashtable
All Nodes Distance K In A Binary Tree - Performing Bidirectional Search On A Tree Using A Hashtable
Back To Back SWE
50 Longest Common Subsequence (2 Strings) - Dynamic Programming & Competing Subproblems
Longest Common Subsequence (2 Strings) - Dynamic Programming & Competing Subproblems
Back To Back SWE
51 Egg Dropping Problem: Dynamic Programming Fundamentals & Understanding Subproblem Decomposition
Egg Dropping Problem: Dynamic Programming Fundamentals & Understanding Subproblem Decomposition
Back To Back SWE
52 Minimum Window Substring: Utilizing Two Pointers & Tracking Character Mappings With A Hashtable
Minimum Window Substring: Utilizing Two Pointers & Tracking Character Mappings With A Hashtable
Back To Back SWE
53 Reverse Polish Notation: Types of Mathematical Notations & Using A Stack To Solve RPN Expressions
Reverse Polish Notation: Types of Mathematical Notations & Using A Stack To Solve RPN Expressions
Back To Back SWE
54 Asymptotic Notations 101: Big O, Big Omega, & Theta (Asymptotic Analysis Bootcamp)
Asymptotic Notations 101: Big O, Big Omega, & Theta (Asymptotic Analysis Bootcamp)
Back To Back SWE
55 The Backtracking Blueprint: The Legendary 3 Keys To Backtracking Algorithms
The Backtracking Blueprint: The Legendary 3 Keys To Backtracking Algorithms
Back To Back SWE
56 Fast Multiplication: From Grade-School Multiplication To Karatsuba's Algorithm
Fast Multiplication: From Grade-School Multiplication To Karatsuba's Algorithm
Back To Back SWE
57 Search A 2D Sorted Matrix - Fundamentals of Search Space Reduction
Search A 2D Sorted Matrix - Fundamentals of Search Space Reduction
Back To Back SWE
58 The Quicksort Sorting Algorithm: Pick A Pivot, Partition, & Recurse
The Quicksort Sorting Algorithm: Pick A Pivot, Partition, & Recurse
Back To Back SWE
59 Lowest Common Ancestor Between 2 Binary Tree Nodes (A Recursive Approach)
Lowest Common Ancestor Between 2 Binary Tree Nodes (A Recursive Approach)
Back To Back SWE
60 Sort A K Sorted Array - Investigating Applications of Min/Max Heaps
Sort A K Sorted Array - Investigating Applications of Min/Max Heaps
Back To Back SWE

Related Reads

📰
Traversal, Linear Search, Swapping, Shifting & More (Leetcode Code example)
Learn array operations in Java and Scala through Leetcode code examples, enhancing your problem-solving skills
Medium · Data Science
📰
The Rain Knows the Shortest Path
Learn how the natural phenomenon of raindrops on a pond illustrates the concept of breadth-first search algorithm, making it easier to understand and visualize.
Medium · Programming
📰
Data Structures & Algorithms for Mobile App Developers
Learn essential data structures and algorithms for mobile app development to improve performance and efficiency
Medium · Programming
📰
Data Structures and Algorithms Deep‑Dive — Real-world Applications of Hash Tables (Chapter 3…
Learn how hash tables are used in real-world applications and improve your coding skills with practical examples
Medium · Programming
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →