JavaScript function that generates all possible combinations of a string

We are required to write a JavaScript function that takes in a string as the only argument. The function should generate an array of strings that contains all possible combinations of characters from the string.

Understanding the Problem

The function uses a bitwise approach to generate all possible combinations. It first extracts individual characters, then uses binary representation to determine which characters to include in each combination.

Example

Following is the code ?

const str = 'Delhi';
const allCombinations = (str1 = '') => {
    const arr = [];
    for (let x = 0, y = 1; x < str1.length; x++, y++) {
        arr[x] = str1.substring(x, y);
    };
    const combination = [];
    let temp = "";
    let len = Math.pow(2, arr.length);
    for (let i = 0; i < len; i++) {
        temp = "";
        for (let j = 0; j < arr.length; j++) {
            if ((i & Math.pow(2, j))) {
                temp += arr[j];
            }
        };
        if (temp !== "") {
            combination.push(temp);
        }
    }
    return combination;
};
console.log(allCombinations(str));
[
  'D', 'e', 'De', 'l',
  'Dl', 'el', 'Del', 'h',
  'Dh', 'eh', 'Deh', 'lh',
  'Dlh', 'elh', 'Delh', 'i',
  'Di', 'ei', 'Dei', 'li',
  'Dli', 'eli', 'Deli', 'hi',
  'Dhi', 'ehi', 'Dehi', 'lhi',
  'Dlhi', 'elhi', 'Delhi'
]

How It Works

The function works in three steps:

  1. Character Extraction: Creates an array of individual characters
  2. Binary Generation: Uses powers of 2 to generate all possible binary combinations
  3. Combination Building: For each binary number, includes characters where the corresponding bit is 1

Simplified Alternative Approach

Here's a more readable recursive approach:

const generateCombinations = (str) => {
    const result = [];
    
    const backtrack = (index, current) => {
        if (index === str.length) {
            if (current.length > 0) {
                result.push(current);
            }
            return;
        }
        
        // Include current character
        backtrack(index + 1, current + str[index]);
        
        // Exclude current character
        backtrack(index + 1, current);
    };
    
    backtrack(0, '');
    return result;
};

console.log(generateCombinations('ABC'));
[ 'A', 'AB', 'ABC', 'AC', 'B', 'BC', 'C' ]

Conclusion

Both approaches generate all possible character combinations from a string. The bitwise method is more efficient for performance, while the recursive approach is easier to understand and maintain.

Updated on: 2026-03-15T23:19:00+05:30

841 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements