The Wayback Machine - https://web.archive.org/web/20240828074839/https://www.geeksforgeeks.org/bit-manipulation-technique-to-replace-boolean-arrays-of-fixed-size-less-than-64/
Open In App

Bit Manipulation technique to replace boolean arrays of fixed size less than 64

Last Updated : 28 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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));


Output

Setting 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>


 
 

Output

1

 



Similar Reads

Find X in range [1, N] of bit size A[i] such that X^2's bit size is not present in Array
Given an array A of N integers, where: Each element of array represents the bit size of an imaginary unsigned integer datatype.If ith imaginary datatype has a size of A[i] bits, then it can store integers from size 0 to 2A[i]-1. The task is to check if there exist some integer X, such that: X is in range 1 to NX can fit in a datatype of bit size A[
8 min read
Maximum size of square such that all submatrices of that size have sum less than K
Given an N x M matrix of integers and an integer K, the task is to find the size of the maximum square sub-matrix (S x S), such that all square sub-matrices of the given matrix of that size have a sum less than K. Examples: Input: K = 30 mat[N][M] = {{1, 2, 3, 4, 6}, {5, 3, 8, 1, 2}, {4, 6, 7, 5, 5}, {2, 4, 8, 9, 4} }; Output: 2 Explanation: All Su
15+ min read
Maximum subarray size, such that all subarrays of that size have sum less than k
Given an array of n positive integers and a positive integer k, the task is to find the maximum subarray size such that all subarrays of that size have the sum of elements less than or equals to k. Examples : Input : arr[] = {1, 2, 3, 4} and k = 8. Output : 2 Sum of subarrays of size 1: 1, 2, 3, 4. Sum of subarrays of size 2: 3, 5, 7. Sum of subarr
15+ min read
Minimum flips to make mean of all k size sub-arrays less than 1
Given an array A of size N, having each element either 0 or 1 and an integer K. Find the minimum number of elements that need to be flipped, such that no sub-array of size greater than or equal to K has an arithmetic mean of 1. Examples: Input: N = 5, A = {1, 1, 1, 1, 1}, K = 5Output: 1Explanation: Initially, mean of only sub-array of size 5 is (1+
11 min read
Maximize the Expression | Bit Manipulation
Given two positive integers A and B. Let's define D such that B AND D = D. The task is to maximize the expression A XOR D.Examples: Input: A = 11 B = 4 Output: 15 Take D = 4 as (B AND D) = (4 AND 4) = 4. Also, (A XOR D) = (11 XOR 4) = 15 which is the maximum according to the given condition. Input: A = 9 and B = 13 Output: 13 Naive approach: Since
7 min read
Maximize the expression (A AND X) * (B AND X) | Bit Manipulation
Given two positive integers A and B such that A != B, the task is to find a positive integer X which maximizes the expression (A AND X) * (B AND X).Example: Input: A = 9 B = 8 Output: 8 (9 AND 8) * (8 AND 8) = 8 * 8 = 64 (maximum possible)Input: A = 11 and B = 13 Output: 9 Naive approach: One can run a loop from 1 to max(A, B) and can easily find X
6 min read
Winner in the Rock-Paper-Scissor game using Bit manipulation
Two players are playing a series of games of Rock–paper–scissors. There are a total of N games played represented by an array arr[][] where arr[i][0] is the move of player one and arr[i][1] is the move of the player two in the ith game from the set {'R', 'P', 'S'}. The task is to find the winner of each of the game. Note that the game is a draw if
6 min read
All about Bit Manipulation
Bit Manipulation is a technique used in a variety of problems to get the solution in an optimized way. This technique is very effective from a Competitive Programming point of view. It is all about Bitwise Operators which directly works upon binary numbers or bits of numbers that help the implementation fast. Below are the Bitwise Operators that ar
14 min read
Find square root of a number using Bit Manipulation
Given a non-negative integer N, the task is to find the square root of N using bitwise operations. If the integer is not the perfect square, return largest integer that is smaller than or equal to square root of N i.e., floor(√N). Examples: Input: N = 36Output: 6Explanation: The square root of 36 is 6. Input: N = 19Output: 4Explanation: The square
7 min read
Store two numbers in one Byte using Bit manipulation
Given two values A and B (A, B &lt; 16), the task is to store the numbers in one byte. Examples: Input: A = 5, B = 9Output: 89Explanation: 5 in binary form is 0101 and the binary form for 9 is 1001. Since 1 byte contains 8 bits, we can store these two nibbles in that 1 bit, forming 01011001 which when converted into decimal becomes 89. Input: A = 2
8 min read
What is Bit Manipulation
Bit manipulation is the process of manipulating individual bits or groups of bits in a binary representation of data. It involves performing logical and arithmetic operations on binary digits or bits to achieve a desired result. How to Perform Bit Manipulation?Bit manipulation is performed using bit-wise operators, which operate on individual bits
4 min read
Print all Palindromic Partitions of a String using Bit Manipulation
Given a string, find all possible palindromic partitions of a given string. Note that this problem is different from Palindrome Partitioning Problem, there the task was to find the partitioning with minimum cuts in input string. Here we need to print all possible partitions. Example: Input: nitinOutput: n i t i n n iti n nitin Input: geeksOutput: g
10 min read
Bit Manipulation for Competitive Programming
Bit manipulation is a technique in competitive programming that involves the manipulation of individual bits in binary representations of numbers. It is a valuable technique in competitive programming because it allows you to solve problems efficiently, often reducing time complexity and memory usage. Table of Content Bitwise OperatorsUseful Bitwis
15+ min read
Largest number with maximum trailing nines which is less than N and greater than N-D
Given two numbers N and D. The task is to find out the largest number smaller than or equal to N which contains the maximum number of trailing nines and the difference between N and the number should not be greater than D. Examples: Input: N = 1029, D = 102 Output: 999 1029 has 1 trailing nine while 999 has three trailing nine. Also 1029-999 = 30(w
14 min read
Largest number less than N with digit sum greater than the digit sum of N
Given an integer N, the task is to find the greatest number less than N such that the sum of its digits is greater than the sum of the digits of N. If the condition isn't satisfied for any number then print -1.Examples: Input: N = 100 Output: 99 99 is the largest number less than 100 sum of whose digits is greater than the sum of the digits of 100I
9 min read
Highest and Smallest power of K less than and greater than equal to N respectively
Given positive integers N and K, the task is to find the highest and smallest power of K greater than equal to and less than equal to N respectively. Examples: Input: N = 3, K = 2 Output: 2 4 Highest power of 2 less than 3 = 2 Smallest power of 2 greater than 3 = 4 Input: N = 6, K = 3 Output: 3 9 Highest power of 3 less than 6 = 3 Smallest power of
5 min read
Sum of all array elements less than X and greater than Y for Q queries
Given a sorted array arr[], and a set Q having M queries, where each query has values X and Y, the task is to find the sum of all integers less than X and greater than Y present in the array. Note: X and Y may or may not be present in the array. Examples: Input: arr[] = [3 5 8 12 15], Q = {{5, 12}, {4, 8}} Output: 18 30 Explanation: For query 1, X
9 min read
For each A[i] find smallest subset with all elements less than A[i] sum more than B[i]
Given two arrays A[] and B[] of N integers, the task is to find for each element A[i], the size of the smallest subset S of indices, such that : Each value corresponding to the indices in subset S is strictly less than A[i].Sum of elements corresponding to the indices in B is strictly greater than B[i]. Examples: Input: N = 5, A = {3, 2, 100, 4, 5}
10 min read
Find minimum integer greater than B that is product of two values less than A
Given 2 positive integers A and B, the task is to find the minimum possible integer C, which is greater than or equal to B and is a product of two positive integers, both of which are less than or equal to A. Examples: Input: A = 5, B = 7Output: 8Explanation: 8 can be represented as a product of 2 positive integers less than 5. i.e. 2*4 = 8. Also,
6 min read
Queries for greater than and not less than
Given an array of N integers. There will be Q queries, each include two integer of form q and x, 0 &lt;= q &lt;= 1. Queries are of two types: In first query (q = 0), the task is to find count of integers which are not less than x (OR greater than or equal to x). In second query (q = 1), the task is to find count of integers greater than x. Examples
8 min read
Count of alphabets having ASCII value less than and greater than k
Given a string, the task is to count the number of alphabets having ASCII values less than and greater than or equal to a given integer k. Examples: Input: str = "GeeksForGeeks", k = 90Output:3, 10G, F, G have ascii values less than 90.e, e, k, s, o, r, e, e, k, s have ASCII values greater than or equal to 90 Input: str = "geeksforgeeks", k = 90Out
11 min read
PreComputation Technique on Arrays
Precomputation refers to the process of pre-calculating and storing the results of certain computations or data structures(array in this case) in advance, in order to speed up the execution time of a program. This can be useful in situations where the same calculations are needed multiple times, as it avoids the need to recalculate them every time.
15 min read
Maximum size square Sub-Matrix with sum less than or equals to K
Given a Matrix arr[][] of size M x N having positive integers and a number K, the task is to find the size of the largest square sub-matrix whose sum of elements is less than or equals to K. Example: Input: arr[][] = { { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 } }, K = 4 Output: 2 Explanation: Maximum size square Sub-M
12 min read
Maximum sum subarray of size K with sum less than X
Given an array arr[] and two integers K and X, the task is to find the maximum sum among all subarrays of size K with the sum less than X. Examples: Input: arr[] = {20, 2, 3, 10, 5}, K = 3, X = 20Output: 18Explanation: Subarray of size 3 having maximum sum less than 20 is {3, 10, 5}. Therefore, required output is 18. Input: arr[] = {-5, 8, 7, 2, 10
7 min read
Maximize value at Kth index to create N size array with adjacent difference 1 and sum less than M
Given three numbers N, K, and M, the task is to find the maximum value that can be assigned to the Kth index if positive values are assigned to all N indices such that the total sum of values is less than M, and the difference between the values at adjacent positions is atmost 1. Examples: Input : N=3, M=10, K=2Output: 4Explanation: The optimal way
11 min read
Count sub-arrays which have elements less than or equal to X
Given an array of n elements and an integer X. Count the number of sub-arrays of this array which have all elements less than or equal to X. Examples: Input : arr[] = {1, 5, 7, 8, 2, 3, 9} X = 6 Output : 6 Explanation : Sub-arrays are {1}, {5}, {2}, {3}, {1, 5}, {2, 3} Input : arr[] = {1, 10, 12, 4, 5, 3, 2, 7} X = 9 Output : 16 Naive Approach : A
15 min read
Number of non-decreasing sub-arrays of length less than or equal to K
Given an array arr[] of N elements and an integer K, the task is to find the number of non-decreasing sub-arrays of length less than or equal to K.Examples: Input: arr[] = {1, 2, 3}, K = 2 Output: 5 {1}, {2}, {3}, {1, 2} and {2, 3} are the valid subarrays.Input: arr[] = {3, 2, 1}, K = 1 Output: 3 Naive approach: A simple approach is to generate all
6 min read
Count N-length arrays made from first M natural numbers whose subarrays can be made palindromic by replacing less than half of its elements
Given two integer N and M, the task is to find the count of arrays of size N with elements from the range [1, M] in which all subarrays of length greater than 1 can be made palindromic by replacing less than half of its elements i.e., floor(length/2). Examples: Input: N = 2, M = 3Output: 6Explanation:There are 9 arrays possible of length 2 using va
4 min read
Reduce sum of same-indexed elements of two arrays to less than K by rearranging the second array
Given two arrays arr1[] and arr2[], both of size N and an integer X, the task is to check if the sum of same-indexed elements of both the arrays at corresponding indices can be made at most K after rearranging the second array. If it is possible then print "Yes" else print "No". Examples: Input: arr1[] = {1, 2, 3}, arr2[] = {1, 1, 2}, X = 4Output:
6 min read
Find the pairs of IDs from two arrays having sum less than target closest to it
Given two arrays arr1[] and arr2[] of pairs of the form {ID, value} of size N and M respectively and an integer target, the task is to find all the pairs of IDs from both the arrays such that the sum of the values of the pairs is maximum and has a value at most M. Examples: Input: arr1[] = [[1, 2000], [2, 3000], [3, 2000]], arr2[] = [[1, 2500], [2,
9 min read
Practice Tags :