How To Permute A String - Generate All Permutations Of A String
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, print all permutations of the string and return an array of them. No duplicates are allowed. Whenever we work with problems like this, the fact that it is a string and that it is an array are interchangeable. We will permute an array the same way that we permute a string. Why is this a backtracking problem? Because we are placing an item and then exploring all possibilities from there. Whenever we have a problem that says "generate" or "compute" and it is an expression of several decision points that comprise a larger possibility set...WE HAVE BACKTRACKING. The 3 Keys To Backtracking Our Choice What character we place in a "slot" Our Constraints None really...but at each decision point we will have fewer characters to work with because of our previous decisions. Our Goal Let n be the string length. Place n characters. Complexities Time: O(n * n!) - There are n! permutations and it takes O(n) time to add each one to our result array Space: O(n) - We are not returning an array here so linear space because our recursion will go at maximum n elements deep since we make n choices of placement at maximum - If we did store and return an array our space complexity would be O(n * n!) since we would have n! permutations and each permutation would be of length n. If we consider the returned array of all permutation strings as NOT part of space, the call stack dominates space. We are back to O(n). ++++++++++++++++++++++++++++++++++++++++++++++++++ HackerRank: https://www.youtube.com/channel/UCOf7UPMHBjAavgD0Qw5q5ww Tuschar Roy: https://www.youtube.com/user/tusharroy2525 GeeksForGeeks: https://www.youtube.com/channel/UC0RhatS1pyxInC00YKjjBqQ Jarvis Johnson: https://www.youtube.com/user/VSympathyV Success In Tech: https://www.youtube.com/channel/UC-vYrOAmtrx9sBzJAf3x_xw ++++++++++++++++++++++++++++++++++++++++++++++++++ This question is number 16.3 in the fantastic book "Elements of Programming Interviews" by Adnan Aziz
Download
1 formatsVideo Formats
Right-click 'Download' and select 'Save Link As' if the file opens in a new tab.