Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Permutations of a String

A Closer Look at Functionshard

Course · Section 10: A Closer Look at Functions · Lecture 137: First-Class and Higher-Order Functions

Implement `permutations(str)` that returns an array of **all unique permutations** of `str` in any order. Example: `permutations('ab')` → `['ab', 'ba']`.

Sample tests

Input: permutations("a")
Output: ["a"]
Input: permutations("ab")
Output: ["ab","ba"]
Input: permutations("abc")
Output: ["abc","acb","bac","bca","cab","cba"]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Duplicate characters can produce repeated permutations.
  • Building permutations without a clear base case.

Learning resources

  • MDN: Recursion (glossary)
Approach & explanation (try first)

Choosing each character in turn and permuting the remainder generates all orderings recursively.

Loading...
⌘/Ctrl + Enter

Run your code to see results.