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 Β· Array and String Problems Β· question 32 of 120

Can you find all the permutations of a given string?

πŸ“• Buy this interview preparation book: 120 Coding Interview Essentials questions & answers β€” PDF + EPUB for $5

Finding all the permutations of a given string is a common problem in computer programming and can be solved using recursion and backtracking.

Here is a Python code snippet that accomplishes this:

def permute(data, i, length): 
    if i==length: 
        print(''.join(data))
    else: 
        for j in range(i, length): 
            data[i], data[j] = data[j], data[i] 
            permute(data, i+1, length) 
            data[i], data[j] = data[j], data[i]
            
string = 'ABC'
n = len(string)
data = list(string)
permute(data, 0, n)

The function β€˜permuteβ€˜ generates all the permutations of a string. This is done by swapping each character in the string with every other character (including itself). For each swap, β€˜permuteβ€˜ is called recursively with the next character, until all characters have been used. The swapped characters are then swapped back to their original positions before the next iteration.

This process can be better understood with the following tree diagram:

ABC
/ | \
A BC ACB
/ \ / \
AB C AC B
/ \ / \
ABC ACB ABC ACB

In the diagram above, each level of the tree corresponds to a character position in the string. Each node represents a string permutation. When the tree is fully expanded, all possible permutations are printed.

There are n! permutations in a string of length n. This is because there are n choices for the first character, n-1 choices for the second character, n-2 choices for the third character, and so on, until only 1 choice is left for the last character. This can be represented mathematically as:


n! = nβ€…*β€…(nβ€…βˆ’β€…1)β€…*β€…(nβ€…βˆ’β€…2)β€…*β€…...β€…*β€…2β€…*β€…1.

Also, for each permutation, there are n*(n-1) swaps made, so the time complexity of this algorithm is O(n2β€…*β€…n!).

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