

Our loop for combinations will always start at a given index. Our loop for permutations always started at 0.We instead just keep track of/memoize our function's loop's current index and pass it to our our function when recurring.The removal of this condition greatly simplifies our algorithm, as we no longer need to keep track of if we have already used an element/if it needs skipping (at least, in the same way).The main difference is that there is not the length condition (remember that a subset/combination can be empty and/or have less elements than the input set - whereas a permutation must be equal in length to the input).This algorithm is very similar to the algorithm for generating permutations.Generating combinations with no duplicates (link to code).Combinations of a string in: Programming Interviews Exposed: Secrets to Landing Your Next Job, 3rd Edition.See FindNextPermutation() at the end of this post for the implementation.įinding all combinations/subsets of a string/integer array.This improved approach has a time complexity of O(n) and a space complexity of O(1) (as the operation is in-place).When this holds true, everything after input (the inversion point) cannot be rearranged to produce a larger permutation, since the elements are in descending order (elements right of inversion point).

We know we have reached the inversion point when input > input.

#WHEN TO USE COMBINATION VS PERMUTATION CODE#
As always, the code for these two variations is at the end of this post.As there are n! permutations our time complexity is O(n! n), and our space complexity is O(n!).The only difference is that we use a modified version of the input string (letters and their counts) and decrement the count of a letter when we have used it (when count = 0 we skip the letter). Once this is done, the algorithm looks almost identical.Sets are represented using the notation.This means every set has an empty subset. A subset is any combination of elements from a set.A set with no elements is still a set and is known as an empty set.Explanation of sets and subsets (slideshow).I encourage you to stick with each problem even if it doesn't click the first time around. It just happens that the best way to really learn this material was to solve some problems after covering theory. I don't expect to get back into this style of post again until I have finished the remaining curriculum. This post is longer than usual & very heavy on problem solving, instead of the usual "learning about a DS/Algo, then writing an example".
