Open In App

JavaScript Program to Find Power Set in Lexicographic Order

Last Updated : 19 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Power set P(S) of a set S is the set of all subsets of S. For example S = {1, 2, 3} then P(s) = {{}, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}}.

This JavaScript code generates and sorts the power set of an input string in lexicographic order, listing all possible subsets from the empty set to the full set. It uses a binary representation approach for efficient subset generation.

Examples:

Input: 123
Output : 1 12 123 13 2 23 3

Method 1: Recursive Approach:

The approach involves initially sorting an array. Following the sorting, and recursively generates all possible subsets beginning with each of them. After each recursive step, the last character is removed to facilitate the generation of the next permutation.

Steps:

  • The code defines a function generatePowerSet that recursively generates and prints the power set of an input string, by using backtracking for subset visit.
  • Another function, powerSetLexicographicOrder, sorts the input string, converts it into a character array, and initiates the generation process using generatePowerSet.
  • In the driver code, the powerSetLexicographicOrder function is called with an input string, resulting in the printing of the power set in lexicographic order.

Example: In this code we print the power set in lexicographical order with recursion mrthod by using JavaScript.

JavaScript
function generatePowerSet(
    inputStr, strLength, currentIndex, currentSubset) {
 
    console.log(currentSubset + " ");

    // Loop through the characters in the input string
    for (let i = currentIndex + 1; i < strLength; i++) {
        currentSubset += inputStr[i];
        generatePowerSet(inputStr, strLength, i, currentSubset);

        // Backtrack to remove the last 
        // character for the next permutation
        currentSubset = 
            currentSubset.substring(0, currentSubset.length - 1);
    }
}

function powerSetLexicographicOrder(inputStr) {
    // Convert the input string into an array of 
    // characters and sort them for lexicographic order
    
    let charArray = inputStr.split("");
    charArray.sort();
    
    // Initiate the generation of the power set
    generatePowerSet(charArray, inputStr.length, -1, "");
}

let inputStr = "123";
powerSetLexicographicOrder(inputStr);

Output
 
1 
12 
123 
13 
2 
23 
3 

Method 2: Iterative Approach:

The concept involves utilizing binary numbers to systematically generate the power set of a provided set of elements in a lexicographically ordered manner.

Steps:

  • The string is sorted in lexicographic order by converting it into an array, sorting it, and joining it back into a string.
  • Now generates all possible binary representations of subsets by looping integers from 0 to 2^n - 1, where n is the length of the string.
  • For each binary representation, it creates the corresponding subset, where '1's indicate character inclusion, and '0's indicate exclusion.
  • The subsets are sorted in lexicographic order and then printed to the console.

Example: In this code we print the power set in lexicographical order with iterative approach by using JavaScript.

JavaScript
function generatePowerSet(s) {

    // Sort the string in lexicographical order
    s = s.split('').sort().join('');
    
    const n = s.length;
    const subsets = [];
    
    // Generate all possible binary strings of 
    // length n
    for (let i = 0; i < 2 ** n; i++) {
    
        // Convert the integer i to a binary 
        // string of length n
        let binary = i.toString(2).padStart(n, '0');
        let subset = '';
        
        // Generate the subset based on the 
        // binary string
        for (let j = 0; j < n; j++) {
            if (binary[j] === '1') {
                subset += s[j];
            }
        }
        
        subsets.push(subset);
    }
    
    // Sort the subsets in lexicographically order
    subsets.sort();
    
    // Print the subsets in sorted order
    
    for (let subset of subsets) {
        console.log(subset);
    }
}

const s = '123';
generatePowerSet(s);

Output
1
12
123
13
2
23
3

Method 3: Bit manipulation:

First, generate all possible binary representations of numbers from 0 to 2^n - 1, where n is the length of the input string. These binary representations will correspond to including or excluding each character from the input string.

Steps:

  • First initialize an empty array powerSet to store the subsets and determines the length 'n' of the input string.
  • The code generates all possible binary representations by looping through integers from 0 to 2^n - 1. For each integer 'i', it constructs a subset by checking each bit position in 'i' (from 0 to n-1). If the bit is set to '1' in 'i', it includes the corresponding character from string in the subset.
  • All generated subsets are stored in the powerSet array.
  • The code sorts the subsets in lexicographical order and returns the sorted power set.

Example: In this Example, we will print the power set in lexicographical order with bit manipulation technique by using JavaScript.

JavaScript
function generatePowerSet(input) {
  const n = input.length;
  const powerSet = [];

  // Generate all possible binary 
  // representations from 0 to 2^n - 1
  for (let i = 0; i < (1 << n); i++) {
    let subset = '';
    for (let j = 0; j < n; j++) {
      if (i & (1 << j)) {
        subset += input[j];
      }
    }
    powerSet.push(subset);
  }

  // Sort the subsets lexicographically
  powerSet.sort();

  return powerSet;
}

const input = '123';
const result = generatePowerSet(input);
console.log(result);

Output
[
  '',    '1',  '12',
  '123', '13', '2',
  '23',  '3'
]

Method 4: DFS with Stack Approach:

This approach involves using a stack to simulate the Depth-First Search (DFS) recursion for generating subsets. It ensures that the subsets are generated in lexicographic order by using a sorted array of characters from the input string.

Example: In this code, we generate the power set in lexicographic order using the DFS with a stack approach in JavaScript.

JavaScript
function generatePowerSetDFS(input) {
    let charArray = input.split("");
    charArray.sort();

    const powerSet = [];
    const stack = [{ subset: "", index: 0 }];

    while (stack.length > 0) {
        const { subset, index } = stack.pop();
        powerSet.push(subset);

        for (let i = index; i < charArray.length; i++) {
            stack.push({ subset: subset + charArray[i], index: i + 1 });
        }
    }
    powerSet.sort();
    for (let subset of powerSet) {
        console.log(subset);
    }
}

const input = '123';
generatePowerSetDFS(input);

Output
1
12
123
13
2
23
3

Method 5: Combination Generation Approach

This approach involves directly generating all combinations of the input string using the mathematical concept of combinations. We iterate over all possible lengths of the subsets from 0 to the length of the input string, and for each length, we generate all possible combinations of that length.

Steps:

  • Sort the input string to ensure lexicographic order.
  • Use a helper function to generate combinations of a given length.
  • Collect all combinations and sort them to ensure they are in lexicographic order (though they should already be due to the sorting step).
  • Print the sorted subsets.

Example: In this example, we will print the power set in lexicographic order by generating combinations directly using JavaScript.

JavaScript
function generateCombinations(chars, start, length, current, results) {
    if (current.length === length) {
        results.push(current);
        return;
    }

    for (let i = start; i < chars.length; i++) {
        generateCombinations(chars, i + 1, length, current + chars[i], results);
    }
}

function generatePowerSetCombinations(input) {
    let charArray = input.split("");
    charArray.sort();

    const powerSet = [];

    for (let length = 0; length <= charArray.length; length++) {
        generateCombinations(charArray, 0, length, "", powerSet);
    }

    powerSet.sort();

    for (let subset of powerSet) {
        console.log(subset);
    }
}

const input = '123';
generatePowerSetCombinations(input);

Output
1
12
123
13
2
23
3

Next Article

Similar Reads