Tutorialspoint
Problem
Solution
Submissions

All Combinations of a String

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a JavaScript program to generate all possible combinations of a given string. A combination includes all possible subsets of characters from the string, including the empty combination and the full string. Return an array containing all unique combinations.

Example 1
  • Input: str = "abc"
  • Output: ["", "a", "b", "c", "ab", "ac", "bc", "abc"]
  • Explanation:
    • Empty combination gives us "".
    • Single character combinations give us "a", "b", "c".
    • Two character combinations give us "ab", "ac", "bc".
    • Full string combination gives us "abc".
    • Total of 8 combinations (2^3) are generated.
Example 2
  • Input: str = "ab"
  • Output: ["", "a", "b", "ab"]
  • Explanation:
    • Empty combination is "".
    • Single character combinations are "a" and "b".
    • Two character combination is "ab".
    • Total of 4 combinations (2^2) are possible.
Constraints
  • 1 ≤ str.length ≤ 10
  • str consists of unique lowercase English letters
  • Time Complexity: O(2^n * n) where n is length of string
  • Space Complexity: O(2^n * n) for storing all combinations
  • The order of combinations in output array doesn't matter
RecursionBacktracking ShopifyArctwist
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use recursive backtracking to generate combinations
  • For each character, decide whether to include it or not
  • Use two recursive calls - one including current character, one excluding it
  • Build combinations by concatenating characters as you recurse
  • Base case occurs when you've processed all characters
  • Alternative approach: use bit manipulation to generate all 2^n combinations

Steps to solve by this approach:

 Step 1: Create a result array to store all combinations.

 Step 2: Define a recursive backtracking function with index and current combination parameters.
 Step 3: Set base case - when index equals string length, add current combination to result.
 Step 4: Make first recursive call excluding the current character (don't add to combination).
 Step 5: Make second recursive call including the current character (add to combination).
 Step 6: The recursion explores all 2^n possibilities by including/excluding each character.
 Step 7: Return the result array containing all generated combinations.

Submitted Code :