Bit Manipulation technique to replace boolean arrays of fixed size less than 64
Last Updated : 28 Jan, 2022
Space complexity is the most underestimated asset by programmers. One can barely see a Memory Limit Exceed (MLE) while submitting a solution. But, saving memory is the most important thing a programmer should take care about. If one needs to create an Application for a user, it should be made as memory efficient as one can.
Boolean arrays have been used as a container to solve different problems. This article focuses on discussing the alternatives to boolean arrays.
Integer Variable as a container
In general, the Integer variable has 4 bytes (C++ taken into consideration) resulting in having 32 boolean bits to represent a number. For example, to represent 10, the boolean bits can be written as:
int a = 10
In Memory-
00000000000000000000000000001010 (Binary of 10 in 32-bit integer)
This means one can use these bits as a boolean value inside a boolean array of size 32. A 64-bit integer can be used to increase the size if needed.
How to use Integer variable as a container?
Let's discuss in detail how to use the Integer variable as a container.
The first step is to initialize the integer variable as 0, to get the boolean container of size 32 with all bits initially false.
Set a bit to true:
Set any bit to true for any desired location by using bitwise operators such as AND, NOT, OR, and SHIFT operators. For, example, to set a bit to true at position 7-
Use shift and bitwise OR operator to make the ith bit to 1 (true)
int a = 0;
a |= (1 << 7);
Here a will become : 00000000000000000000000010000000
↑
0th bit
Step 1: First move 1 which is (..0001) in binary to 7 steps left to make it as (..10000000).
Step 2: Next, do bitwise or with the number.
Step 3: As 1 OR 0 = 1 and 1 OR 1 = 1, this will set the 7th bit to one without affecting other bits.
Set a bit to false:
For example, to reset a bit to false at position 7
Use shift and bitwise NOT and AND operator to make the ith bit to 0(false).
int a = 0;
a |= (1 << 7); // To set 7th bit
a &= ~(1 << 7); // To reset 7th bit
Step 1: First move our 1 which is (..0001) in binary to 7 steps left to make it as (..10000000).
Step 2: Invert the bits to look like (...1101111111).
Step 3: Perform AND operation with the number.
Step 4: As 1 AND 0 = 0, 0 AND 0 = 0, 1 AND 1 = 1, this will set the 7th bit to one without affecting other bits.
Get the value of ith bit:
For example, to get the value of the 7th bit-
Use AND operator to print.
int a = 0;
a |= (1<<7); // To set 7th bit
Print((a>>7)&1); // this will print 1(True)
a &= ~(1<<7); // To reset 7th bit
Print((a>>7)&1); // this will print 0(false)
Below is the implementation of the above approach:
C++ // C++ program to implement // the above approach #include<iostream> using namespace std; // Driver code int main() { // This is an integer variable // used as a container int myBoolContainer = 0; // 7th bit will be used for sample int workingBit = 7; // Setting ith bit cout << "Setting " << workingBit << "th bit to 1\n"; myBoolContainer |= (1 << workingBit); // Printing the ith bit cout << "Value at " << workingBit << "th bit = " << ((myBoolContainer >> workingBit) & 1) << "\n\n"; // Resetting the ith bit cout << "Resetting " << workingBit << "th bit to 0\n"; myBoolContainer &= ~(1 << 7); // Printing the ith bit cout << "Value at " << workingBit << "th bit = " << ((myBoolContainer >> workingBit) & 1); }
Java // Java program to implement // the above approach import java.io.*; // Driver code class GFG { public static void main (String[] args) { // This will be the integer variable // used as boolean container int myBoolContainer = 0; // 7th bit will be used for sample int workingBit = 7; // Setting ith bit System.out.println( "Setting " + workingBit + "th bit to 1"); myBoolContainer |= (1 << workingBit); // Printing the ith bit System.out.println( "Value at " + workingBit+"th bit = " + ((myBoolContainer >> workingBit) & 1) + "\n"); // Resetting the ith bit System.out.println( "Resetting " + workingBit + "th bit to 0"); myBoolContainer &= ~(1 << 7); // Printing the ith bit System.out.println( "Value at " + workingBit + "th bit = " + ((myBoolContainer >>workingBit) & 1)); } }
Python # Python program to implement # the above approach # This will be the integer variable # used as boolean container myBoolContainer = 0; # 7th bit will be used as example workingBit = 7; # Setting ith bit print("Setting " + str(workingBit) + "th bit to 1"); myBoolContainer |= (1 << workingBit); # Printing the ith bit print("Value at " + str(workingBit) + "th bit = " + str((myBoolContainer >> workingBit) & 1) + "\n"); # Resetting the ith bit print("Resetting " + str(workingBit) + "th bit to 0"); myBoolContainer &= ~(1 << 7); # Printing the ith bit print("Value at " + str(workingBit) + "th bit = " + str((myBoolContainer >> workingBit) & 1))
C# //C# code for the above approach using System; public class GFG { static public void Main() { // This will be the integer variable // used as boolean container int myBoolContainer = 0; // 7th bit will be used for sample int workingBit = 7; // Setting ith bit Console.WriteLine("Setting " + workingBit + "th bit to 1"); myBoolContainer |= (1 << workingBit); // Printing the ith bit Console.WriteLine( "Value at " + workingBit + "th bit = " + ((myBoolContainer >> workingBit) & 1) + "\n"); // Resetting the ith bit Console.WriteLine("Resetting " + workingBit + "th bit to 0"); myBoolContainer &= ~(1 << 7); // Printing the ith bit Console.WriteLine( "Value at " + workingBit + "th bit = " + ((myBoolContainer >> workingBit) & 1)); } } // This code is contributed by Potta Lokesh
JavaScript // Javascript program to implement // the above approach // This is an integer variable // used as a container var myBoolContainer = 0; // 7th bit will be used sample var workingBit = 7; // Setting ith bit console.log("Setting " + workingBit + "th bit to 1\n"); myBoolContainer |= (1 << workingBit); //Printing the ith bit console.log("Value at " + workingBit + "th bit = "+ ((myBoolContainer >> workingBit) & 1) + "\n\n"); // Resetting the ith bit console.log("Resetting " + workingBit + "th bit to 0\n"); myBoolContainer &= ~(1 << 7); // Printing the ith bit console.log("Value at " + workingBit + "th bit = " + ((myBoolContainer >> workingBit) & 1));
OutputSetting 7th bit to 1 Value at 7th bit = 1 Resetting 7th bit to 0 Value at 7th bit = 0
Solve Pangram Strings:
Let's solve the problem of pangram strings using the above approach.
Approach:
It is known that English alphabets of lower case range from (a-z) are having a count of no more than 26. So, in this approach, a bool array of constant size can be used. This will optimize the space complexity of the code.
Below is the implementation of the pangram strings using a boolean array:
C++ // C++ program to implement // the above approach #include <iostream> using namespace std; bool checkIsPanagram(string sentence) { // Initializing the container int n = 0; for(char &x:sentence) { // Checking that the char // is Alphabetic if(isalpha(x)) // setting ith bit to 1 // if char is 'a' then this will // set 0th bit to 1 and so on n |= (1 << (tolower(x) - 'a')); } // decimal number for all ones in last // 26 bits in binary is 67108863 return n == 67108863; } // Driver code int main() { string s = "Pack mY box witH fIve dozen liquor jugs"; cout << checkIsPanagram(s); }
Java // Java program to implement // the above approach import java.io.*; class Panagram { public boolean checkIsPanagram( String sentence) { // Initializing the container int n = 0; int size = sentence.length(); for(int i = 0; i < size; i++) { // Storing current character // in temp variable char x = sentence.charAt(i); // checking that the char is Alphabetic if(Character.isAlphabetic(x)) { // setting ith bit to 1 // if char is 'a' then this will // set 0th bit to 1 and so on n |= (1 << (Character.toLowerCase(x) - 'a')); } } // Decimal number for all ones in last // 26 bits in binary is 67108863 return (n == 67108863); } }; // Driver code class GFG { public static void main (String[] args) { String s = "Pack mY box witH fIve dozen liquor jugs"; Panagram panagram = new Panagram(); System.out.println( panagram.checkIsPanagram(s)); } }
Python # Python program to implement # the above approach def isPanagram(sentence): # Initializing the container n = 0 for char in sentence: # Checking that the char # is Alphabetic if char.isalpha(): # setting ith bit to 1 # if char is a then this will # set 0th bit to 1 and so on n |= (1 << (ord(char.lower()) - ord('a'))) # Decimal number for all ones in # last 26 bits in binary is 67108863 return n == 67108863 sentence = "Pack mY box witH fIve dozen liquor jugs" print(isPanagram(sentence))
C# // C# program to implement // the above approach using System; class Panagram { public bool checkIsPanagram( String sentence) { // Initializing the container int n = 0; int size = sentence.Length; for(int i = 0; i < size; i++) { // Storing current character // in temp variable char x = sentence[i]; // checking that the char is Alphabetic if(char.IsLetter(x)) { // setting ith bit to 1 // if char is 'a' then this will // set 0th bit to 1 and so on n |= (1 << (char.ToLower(x) - 'a')); } } // Decimal number for all ones in last // 26 bits in binary is 67108863 return (n == 67108863); } }; // Driver code public class GFG { public static void Main(String[] args) { String s = "Pack mY box witH fIve dozen liquor jugs"; Panagram panagram = new Panagram(); Console.WriteLine( panagram.checkIsPanagram(s)); } } // This code is contributed by 29AjayKumar
JavaScript <script> // javascript program to implement // the above approach function checkIsPanagram(sentence) { // Initializing the container var n = 0; var size = sentence.length; for(var i = 0; i < size; i++) { // Storing current character // in temp variable var x = sentence[i]; // checking that the char is Alphabetic if(isAlphabetic(x)) { // setting ith bit to 1 // if char is 'a' then this will // set 0th bit to 1 and so on n = n | (1 << (x.charCodeAt(0)- 'a'.charCodeAt(0))); } } // Decimal number for all ones in last // 26 bits in binary is 67108863 return (n == 67108863); } function isAlphabetic(str) { return /^[a-zA-Z()]+$/.test(str); } // Driver code var s = "Pack mY box witH fIve dozen liquor jugs"; document.write(checkIsPanagram(s)); // This code is contributed by 29AjayKumar </script>
Similar Reads
Replace every element of the array with BitWise XOR of all other
Given an array of integers. The task is to replace every element by the bitwise xor of all other elements of the array. Examples: Input: arr[] = { 2, 3, 3, 5, 5 } Output: 0 1 1 7 7 Bitwise Xor of 3, 3, 5, 5 = 0 Bitwise Xor of 2, 3, 5, 5 = 1 Bitwise Xor of 2, 3, 5, 5 = 1 Bitwise Xor of 2, 3, 3, 5 = 7
5 min read
Minimum operations to make all Array elements 0 by MEX replacement
Given an array of N integers. You can perform an operation that selects a contiguous subarray and replaces all its elements with the MEX (smallest non-negative integer that does not appear in that subarray), the task is to find the minimum number of operations required to make all the elements of th
5 min read
Rearrange given Array such that all set bit positions have higher value than others
Given an array B1[] and a binary array B2[] each of size N, the task is to rearrange array B1[] in a way such that for all setbit position i of B2[] the value of B1[i] will be greater than the values where bit is not set in B2[] i.e for all (i, j) B1[i] > B1[j] when B2[i] = 1, B2[j] = 0 (0 ⤠i, j
13 min read
Find element with the maximum set bits in an array
Given an array arr[]. The task is to find an element from arr[] which has the maximum count of set bits.Examples: Input: arr[] = {10, 100, 1000, 10000} Output: 1000 Binary(10) = 1010 (2 set bits) Binary(100) = 1100100 (3 set bits) Binary(1000) = 1111101000 (6 set bits) Binary(10000) = 10011100010000
5 min read
Find the missing element in an array of integers represented in binary format
Given N strings which represents all integers from 0 to N in binary format except any one. The task is to find the missing number. Input consists of an array of strings where array elements are represented in binary format. Examples: Input: arr[] = {"0000", "0001", "0010", "0100"} Output: 3 Input: a
15+ min read
Minimum pair sum operations to make array each element divisible by 4
Given an array of positive integers of length n. Our task is to find minimum number of operations to convert an array so that arr[i] % 4 is zero for each i. In each operation, we can take any two elements from the array, remove both of them and put back their sum in the array. Examples: Input : arr
12 min read
Minimize Array Sum by replacing pairs with (X, Y) keeping their bitwise OR same
Given an array arr[] of size N. Find the minimum sum of the array after performing given operations any number of times: Select two different indices i, j (1 ⤠i < j ⤠N),Replace arr[i] and arr[j] with X and Y respectively (X, Y>0), such that arr[i] | arr[j] = X | Y, where | denotes the bitwis
5 min read
Find a K-length subarray having Bitwise XOR equal to that of remaining array elements
Given an array arr[] of size N, the task is to check if any subarray of size K exists in the array or not, whose Bitwise XOR is equal to the Bitwise XOR of the remaining array elements. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: arr[] = { 2, 3, 3, 5, 7, 7, 3, 4 },
9 min read
Queries to count array elements from a given range having a single set bit
Given an array arr[] consisting of N integers and a 2D array Q[][] consisting of queries of the following two types: 1 L R: Print the count of numbers from the range [L, R] having only a single set bit.2 X V: Update the array element at Xth index with V.Examples: Input: arr[] = { 12, 11, 16, 2, 32 }
15+ min read
Queries to count array elements from a given range having a single set bit
Given an array arr[] consisting of positive integers and an array Q[][] consisting of queries, the task for every ith query is to count array elements from the range [Q[i][0], Q[i][1]] with only one set bit. Examples: Input: arr[] = {12, 11, 16, 8, 2, 5, 1, 3, 256, 1}, queries[][] = {{0, 9}, {4, 9}}
7 min read