JavaScript Program to Find Power Set in Lexicographic Order
Last Updated :
19 Jul, 2024
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);
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);
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
Similar Reads
JavaScript Program to Find Lexicographically Next Permutation
Given an array of distinct integers, we want to find the lexicographically next permutation of those elements. In simple words, when all the possible permutations of an array are placed in a sorted order, it is the lexicographic order of those permutations. In this case, we have to find the next gre
5 min read
JavaScript Program to Illustrate Different Set Operations
This article illustrates the various operations that can be applied in a set. There are various operations that can be applied on a set that are listed below: Union of setsIntersection of setsSet differenceSet Subset OperationUnion of setsA union set is the combination of two elements. In mathematic
2 min read
JavaScript Program to Find Number Pairs (x, y) in an Array Such That x^y > y^x
Given two arrays A[] and B[] of sizes N and M respectively, we need to find the count of pairs (x, y) such that x^y > y^x. Here, x is an element of array A[] whereas y is an element of array B[]. Example: Input: X[] = {10, 19, 18}, Y[] = {11, 15, 9} Output: 2 Explanation: There are total 2 pairs
4 min read
JavaScript Program to Find Union and Intersection of Two Unsorted Arrays
In this article, we will learn how to find the Union and Intersection of two arrays. When an array contains all the elements that are present in both of the arrays, it is called a union. On the other hand, if an array has only those elements that are common in both of the arrays, then it is called a
13 min read
Java Program to Sort an Array of Strings in Lexicographical Order (Dictionary Order)
In Java, sorting an array in lexicographical (dictionary) order means elements will be arranged based on their alphabetical order from A to Z with case sensitivity.Example:We will use Arrays.sort() method with String.CASE_INSENSITIVE_ORDER to sort an array in lexicographical order. It is the most di
3 min read
Javascript Program for Pairs such that one is a power multiple of other
You are given an array A[] of n-elements and a positive integer k (k > 1). Now you have find the number of pairs Ai, Aj such that Ai = Aj*(kx) where x is an integer. Note: (Ai, Aj) and (Aj, Ai) must be count once.Examples : Input : A[] = {3, 6, 4, 2}, k = 2Output : 2Explanation : We have only two
3 min read
JavaScript Set Coding Practice Problems
Sets are an important data structure in JavaScript that store unique values of any type, whether primitive or object references. A Set is useful for scenarios where you want to eliminate duplicate values or check for membership efficiently. Sets are unordered collections, meaning the elements are no
2 min read
Java Program to Find Independent Sets in a Graph By Graph Coloring
Independent sets are set of vertices or edges in which the pair of any two vertices or edges are not adjacent to each other. Assuming that Independent sets mean Independent sets of vertices, we have to find a set of such vertices in which any two pairs of vertexes are not adjacent to each other. Usi
13 min read
How to Iterate LinkedHashMap in Reverse Order in Java?
The LinkedHashMap is used to maintain an order of elements inserted into it. It provides where the elements can be accessed in their insertion order. A LinkedHashMap contains values based on the key. It implements the Map interface and extends the HashMap class. It contains only unique elements or m
6 min read
Java Program to Find the Largest Independent Set in a Graph by Complements
In a graph with V vertices and E edges, the LIS (Largest Independent Set) is the set of all the vertices in the graph which are not connected to each other by the E edges. Approach :We create a HashMap that has a pair of Integers and an Integer as parameters.The pair represents two vertices and the
3 min read