WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Coding Interview Essentials · Recursion and Dynamic Programming Problems · question 75 of 120

Can you write a recursive function to generate all permutations of a string?

📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

Generating permutations of a string is a classical problem that employs the method of recursion in a crucial way. Here is a simple Python function that generates all the permutations of a string:

def permutations(string, step = 0):

    # if we've reached the end, print the permutation
    if step == len(string):
        print("".join(string))

    # everything to the right of step has not been swapped yet
    for i in range(step, len(string)):

        # copy the string (store as list)
        string_copy = [c for c in string]

        # swap the current index with the step
        string_copy[step], string_copy[i] = string_copy[i], string_copy[step]

        # recurse on the portion of the string that has not been swapped yet (now it's index will begin with step + 1)
        permutations(string_copy, step + 1)

Explanation for this Python function:

1. If we’re at the end of the string, we print the permutation.

2. We iterate from our progress in the function so far to the end of the string. Currently, our progress is denoted by ’step’.

3. We copy the string and swap the current character with the character at the position of our current progress.

4. We recursively call the function on this copy with the progress incremented.

Consider an example:

permutations("ABC")

It will generate the output:

ABC
ACB
BAC
BCA
CBA
CAB

Note: The recursion tree follows the Depth-First Search (DFS) approach, thus generating all possible permutations. Each level of recursion considers swapping a fixed character of the string with all the other characters that follows it. Consequently, the recursion explores all options for each position (from left to right) in the string and generates all the permutations.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Coding Interview Essentials interview — then scores it.
📞 Practice Coding Interview Essentials — free 15 min
📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

All 120 Coding Interview Essentials questions · All topics