Permutations of a String

Asked atExpediaPhonePe
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given a string s, return all unique permutations of its characters in sorted order.

  • The output should be a list of strings, where each string is a valid permutation of s.
  • If the string contains duplicate characters, each permutation should appear only once.
  • The list should be sorted lexicographically.

You must return a list of strings, where each string is a valid permutation of s.

Input: s = "abc" Output: ["abc","acb","bac","bca","cab","cba"] **Explanation: **All 6 permutations of 3 distinct characters.

**Input: **s = "aab" Output: ["aab","aba","baa"] Explanation: Only 3 unique permutations due to duplicate 'a'.

Input: s = "aa"

  • 1 <= s.length <= 8
  • s consists of lowercase English letters (a to z)
  • Return only unique permutations if the input string has duplicate characters

cpp

class Solution {
public:
    vector<string> permuteUnique(string s) {
        // Your code goes here
    }
};

java

class Solution {
    public List<String> permuteUnique(String s) {
        // Your code goes here
    }
}

python

class Solution:
    def permuteUnique(self, s: str) -> list:
        # Your code goes here

javascript

class Solution {
    permuteUnique(s) {
        // Your code goes here
    }
}

csharp

class Solution {
    public IList<string> PermuteUnique(string s) {
        // Your code goes here
    }
}

go

func permuteUnique(s string) []string {
    // Your code goes here
}
Stuck? Show a way to structure it+
  1. 01Sort the characters first.
  2. 02Track which indices are currently used.
  3. 03Build one permutation left to right.
  4. 04Skip an equal character when its previous equal copy was not used.
  5. 05Emit a copy when the path reaches the string length.

Reference answer

Then expect these follow-ups

  • How would you implement this by repeatedly calling next permutation?

    Tests: implementation extension

  • What is the output count for character frequencies c1, c2, and so on?

    Tests: follow-up reasoning

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question