A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.
Is there
First of all, sets have permutations, not strings or integers, so I'll just assume you mean "the set of characters in a string."
Note that a set of size n has n! n-permutations.
The following pseudocode (from Wikipedia), called with k = 1...n! will give all the permutations:
function permutation(k, s) {
for j = 2 to length(s) {
swap s[(k mod j) + 1] with s[j]; // note that our array is indexed starting at 1
k := k / j; // integer division cuts off the remainder
}
return s;
}
Here's the equivalent Python code (for 0-based array indexes):
def permutation(k, s):
r = s[:]
for j in range(2, len(s)+1):
r[j-1], r[k%j] = r[k%j], r[j-1]
k = k/j+1
return r