The Wayback Machine - https://web.archive.org/web/20240818165441/https://www.geeksforgeeks.org/space-optimization-using-bit-manipulations/
Open In App

Space optimization using bit manipulations

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

There are many situations where we use integer values as index in array to see presence or absence, we can use bit manipulations to optimize space in such problems.
Let us consider below problem as an example.
Given two numbers say a and b, mark the multiples of 2 and 5 between a and b using less than O(|b – a|) space and output each of the multiples. 

Note : We have to mark the multiples i.e save (key, value) pairs in memory such that each key either have value as 1 or 0 representing as multiple of 2 or 5 or not respectively. 

Examples :  

Input : 2 10
Output : 2 4 5 6 8 10

Input: 60 95
Output: 60 62 64 65 66 68 70 72 74 75 76 78 
        80 82 84 85 86 88 90 92 94 95

Approach 1 (Simple): 

Hash the indices in an array from a to b and mark each of the indices as 1 or 0. 
Space complexity : O(max(a, b))

Approach 2 (Better than simple): 

Save memory, by translating a to 0th index and b to (b-a)th index. 
Space complexity : O(|b-a|).

Simply hash |b – a| positions of an array as 0 and 1.

Implementation:

C++




// C++ program to mark numbers as multiple of 2 or 5
#include <bits/stdc++.h>
using namespace std;
 
// Driver code
int main()
{
    int a = 2, b = 10;
    int size = abs(b - a) + 1;
    int* array = new int[size];
 
    // Iterate through a to b, If it is a multiple
    // of 2 or 5 Mark index in array as 1
    for (int i = a; i <= b; i++)
        if (i % 2 == 0 || i % 5 == 0)
            array[i - a] = 1;
 
    cout << "MULTIPLES of 2 and 5:\n";
    for (int i = a; i <= b; i++)
        if (array[i - a] == 1)
            cout << i << " ";
 
    return 0;
}


Java




// Java program to mark numbers as
// multiple of 2 or 5
import java.lang.*;
 
class GFG {
     
    // Driver code
    public static void main(String[] args)
    {
        int a = 2, b = 10;
        int size = Math.abs(b - a) + 1;
        int array[] = new int[size];
     
        // Iterate through a to b, If
        // it is a multiple of 2 or 5
        // Mark index in array as 1
        for (int i = a; i <= b; i++)
            if (i % 2 == 0 || i % 5 == 0)
                array[i - a] = 1;
     
        System.out.println("MULTIPLES of 2"
                              + " and 5:");
        for (int i = a; i <= b; i++)
            if (array[i - a] == 1)
                System.out.printf(i + " ");
    }
}
 
// This code is contributed by
// Smitha Dinesh Semwal


Python3




# Python3 program to mark numbers
# as multiple of 2 or 5
import math
 
# Driver code
a = 2
b = 10
size = abs(b - a) + 1
array = [0] * size
 
# Iterate through a to b,
# If it is a multiple of 2
# or 5 Mark index in array as 1
for i in range(a, b + 1):
    if (i % 2 == 0 or i % 5 == 0):
            array[i - a] = 1
 
print("MULTIPLES of 2 and 5:")
for i in range(a, b + 1):
    if (array[i - a] == 1):
            print(i, end=" ")
 
# This code is contributed by
# Smitha Dinesh Semwal


C#




// C# program to mark numbers as
// multiple of 2 or 5
using System;
 
class GFG {
     
    // Driver code
    static public void Main ()
    {
        int a = 2, b = 10;
        int size = Math.Abs(b - a) + 1;
        int[] array = new int[size];
     
        // Iterate through a to b, If
        // it is a multiple of 2 or 5
        // Mark index in array as 1
        for (int i = a; i <= b; i++)
            if (i % 2 == 0 || i % 5 == 0)
                array[i - a] = 1;
     
        Console.WriteLine("MULTIPLES of 2" +
                          " and 5:");
        for (int i = a; i <= b; i++)
            if (array[i - a] == 1)
                Console.Write(i + " ");
    }
}
 
// This code is contributed by Ajit.


PHP




<?php
// PHP program to mark
// numbers as multiple
// of 2 or 5
 
// Driver Code
$a = 2;
$b = 10;
$size = abs($b - $a) + 1;
$array = array_fill(0, $size, 0);
 
// Iterate through a to b,
// If it is a multiple of
// 2 or 5 Mark index in
// array as 1
for ($i = $a; $i <= $b; $i++)
    if ($i % 2 == 0 || $i % 5 == 0)
        $array[$i - $a] = 1;
 
echo "MULTIPLES of 2 and 5:\n";
for ($i = $a; $i <= $b; $i++)
    if ($array[$i - $a] == 1)
        echo $i . " ";
 
// This code is contributed by mits.
?>


Javascript




<script>
 
// JavaScript program to mark numbers as
// multiple of 2 or 5
 
// Driver code
let a = 2, b = 10;
let size = Math.abs(b - a) + 1;
let array = [];
 
// Iterate through a to b, If
// it is a multiple of 2 or 5
// Mark index in array as 1
for(let i = a; i <= b; i++)
    if (i % 2 == 0 || i % 5 == 0)
        array[i - a] = 1;
 
document.write("MULTIPLES of 2" +
               " and 5:" + "<br/>");
for(let i = a; i <= b; i++)
    if (array[i - a] == 1)
        document.write(i + " ");
         
// This code is contributed by code_hunt
 
</script>


Output

MULTIPLES of 2 and 5:
2 4 5 6 8 10 

Time Complexity: O(|b – a|)

Auxiliary space: O(|b – a|)

Approach 3 (Using Bit Manipulations):

Here is a space optimized which uses bit manipulation technique that can be applied to problems mapping binary values in arrays. 

Size of int variable in 64-bit compiler is 4 bytes. 1 byte is represented by 8 bit positions in memory. So, an integer in memory is represented by 32 bit positions(4 Bytes) these 32 bit positions can be used instead of just one index to hash binary values.

We can Implement the above Approach for 32-bit integers by following these steps

  1.  Find the actual index in int[] that needs to be bit manipulated it will be bitwise index/ 32.
  2.  Find the index of bit in those 32 bits that needs to be turned on it will be bitwise index % 32.  Let’s Call it X
  3.  Turn on the bit by doing | (bitwise OR) with (1 << X) (here we turn on the Xth bit by bit manipulation)
  4.  To get the value of a bit at a bitwise index we calculate the same indices and do a bitwise & so that if Xth bit is on it will return an integer not equal to 0 which is true in C++.
  5. Now instead of using arithmetic operators we can use bitwise operations for efficiency

Implementation:

C++




// C++ code for marking multiples
#include <bits/stdc++.h>
using namespace std;
 
// index >> 5 corresponds to dividing index by 32
// index & 31 corresponds to modulo operation of
// index by 32
 
// Function to check value of bit position whether
// it is zero or one
bool checkbit(int array[], int index)
{
    return array[index >> 5] & (1 << (index & 31));
}
 
// Sets value of bit for corresponding index
void setbit(int array[], int index)
{
    array[index >> 5] |= (1 << (index & 31));
}
 
/* Driver program to test above functions*/
int main()
{
    int a = 2, b = 10;
    int size = abs(b - a)+1;
 
    // Size that will be used is actual_size/32
    // ceil is used to initialize the array with
    // positive number
    size = ceil((double)size/32);
     
    // Array is dynamically initialized as
    // we are calculating size at run time
    int* array = new int[size];
 
    // Iterate through every index from a to b and
    // call setbit() if it is a multiple of 2 or 5
    for (int i = a; i <= b; i++)
        if (i % 2 == 0 || i % 5 == 0)
            setbit(array, i - a);
 
    cout << "MULTIPLES of 2 and 5:\n";
    for (int i = a; i <= b; i++)
        if (checkbit(array, i - a))
            cout << i << " ";
 
    return 0;
}


Java




// Java code to for marking multiples
import java.io.*;
import java.util.*;
 
class GFG
{
    // index >> 5 corresponds to dividing index by 32
    // index & 31 corresponds to modulo operation of
    // index by 32
 
    // Function to check value of bit position whether
    // it is zero or one
    static boolean checkbit(int array[], int index)
    {
            int val = array[index >> 5] & (1 << (index & 31));
            if (val == 0)
                return false;
            return true;
    }
 
    // Sets value of bit for corresponding index
    static void setbit(int array[], int index)
    {
            array[index >> 5] |= (1 << (index & 31));
    }
 
    // Driver code
    public static void main(String args[])
    {
            int a = 2, b = 10;
            int size = Math.abs(b-a);
 
            // Size that will be used is actual_size/32
            // ceil is used to initialize the array with
            // positive number
            size = (int)Math.ceil((double)size / 32);
 
            // Array is dynamically initialized as
            // we are calculating size at run time
            int[] array = new int[size];
 
            // Iterate through every index from a to b and
            // call setbit() if it is a multiple of 2 or 5
            for (int i = a; i <= b; i++)
                if (i % 2 == 0 || i % 5 == 0)
                    setbit(array, i - a);
 
            System.out.println("MULTIPLES of 2 and 5:");
            for (int i = a; i <= b; i++)
                if (checkbit(array, i - a))
                    System.out.print(i + " ");
    }
}
 
// This code is contributed by rachana soma


Python3




# Python3 code to for marking multiples
import math
 
# index >> 5 corresponds to dividing index by 32
# index & 31 corresponds to modulo operation of
# index by 32
 
# Function to check value of bit position whether
# it is zero or one
def checkbit( array, index):
    return array[index >> 5] & (1 << (index & 31))
 
# Sets value of bit for corresponding index
def setbit( array, index):
    array[index >> 5] |= (1 << (index & 31))
 
# Driver code
a = 2
b = 10
size = abs(b - a)
 
# Size that will be used is actual_size/32
# ceil is used to initialize the array with
# positive number
size = math.ceil(size / 32)
     
# Array is dynamically initialized as
# we are calculating size at run time
array = [0 for i in range(size)]
 
# Iterate through every index from a to b and
# call setbit() if it is a multiple of 2 or 5
for i in range(a, b + 1):
    if (i % 2 == 0 or i % 5 == 0):
        setbit(array, i - a)
 
print("MULTIPLES of 2 and 5:")
for i in range(a, b + 1):
    if (checkbit(array, i - a)):
        print(i, end = " ")
 
# This code is contributed by rohitsingh07052


C#




// C# code to for marking multiples
using System;
 
class GFG
{
    // index >> 5 corresponds to dividing index by 32
    // index & 31 corresponds to modulo operation of
    // index by 32
 
    // Function to check value of bit position 
    // whether it is zero or one
    static bool checkbit(int []array, int index)
    {
        int val = array[index >> 5] &
                 (1 << (index & 31));
        if (val == 0)
            return false;
        return true;
    }
 
    // Sets value of bit for corresponding index
    static void setbit(int []array, int index)
    {
            array[index >> 5] |= (1 << (index & 31));
    }
 
    // Driver code
    public static void Main(String []args)
    {
        int a = 2, b = 10;
        int size = Math.Abs(b-a);
 
        // Size that will be used is actual_size/32
        // ceil is used to initialize the array with
        // positive number
        size = (int)Math.Ceiling((double)size / 32);
 
        // Array is dynamically initialized as
        // we are calculating size at run time
        int[] array = new int[size];
 
        // Iterate through every index from a to b and
        // call setbit() if it is a multiple of 2 or 5
        for (int i = a; i <= b; i++)
            if (i % 2 == 0 || i % 5 == 0)
                setbit(array, i - a);
 
        Console.WriteLine("MULTIPLES of 2 and 5:");
        for (int i = a; i <= b; i++)
            if (checkbit(array, i - a))
                Console.Write(i + " ");
    }
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// JavaScript code to for marking multiples
 
// index >> 5 corresponds to dividing index
// by 32 index & 31 corresponds to modulo
// operation of index by 32
 
// Function to check value of bit
// position whether it is zero or one
function checkbit(array, index)
{
    return array[index >> 5] &
                    (1 << (index & 31));
}
 
// Sets value of bit for corresponding index
function setbit(array, index)
{
    array[index >> 5] |=
             (1 << (index & 31));
}
 
// Driver code
let a = 2, b = 10;
let size = Math.abs(b - a);
 
// Size that will be used is actual_size/32
// ceil is used to initialize the array with
// positive number
size = Math.ceil(size / 32);
 
// Array is dynamically initialized as
// we are calculating size at run time
let array = new Array(size);
 
// Iterate through every index from a to b and
// call setbit() if it is a multiple of 2 or 5
for(let i = a; i <= b; i++)
    if (i % 2 == 0 || i % 5 == 0)
        setbit(array, i - a);
 
document.write("MULTIPLES of 2 and 5:<br>");
for(let i = a; i <= b; i++)
    if (checkbit(array, i - a))
        document.write(i + " ");
 
// This code is contributed by Surbhi Tyagi.
 
</script>


Output

MULTIPLES of 2 and 5:
2 4 5 6 8 10 

Time Complexity: O(|b – a|)
Auxiliary space: O(|b – a|)



Previous Article
Next Article

Similar Reads

Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character | Set 2
Given two equal-size strings s[] and t[] of size N. In one step, choose any character of t[] and replace it with another character. Return the minimum number of steps to make t[] an anagram of s[]. Note: An Anagram of a string is a string that contains the same characters with a different (or the same) ordering. Examples: Input: s = "baa", t = "aba
6 min read
Least number of manipulations needed to ensure two strings have identical characters
Given two strings return the value of least number of manipulations needed to ensure both strings have identical characters, i.e., both string become anagram of each other. Examples: Input : s1 = "aab" s2 = "aba" Output : 2 Explanation : string 1 contains 2 a's and 1 b, also string 2 contains same characters Input : s1 = "abc" s2 = "cdd" Output : 2
5 min read
Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character
Given two strings s1 and s2, we need to find the minimum number of manipulations required to make two strings anagram without deleting any character. Note:- The anagram strings have same set of characters, sequence of characters can be different. If deletion of character is allowed and cost is given, refer to Minimum Cost To Make Two Strings Identi
10 min read
QuickSort Tail Call Optimization (Reducing worst case space to Log n )
Prerequisite : Tail Call Elimination In QuickSort, partition function is in-place, but we need extra space for recursive function calls. A simple implementation of QuickSort makes two calls to itself and in worst case requires O(n) space on function call stack. The worst case happens when the selected pivot always divides the array such that one pa
12 min read
Counting Triangles in a Rectangular space using BIT
Pre-requisite: BIT(Binary Indexed Tree or Fenwick Tree), 2D BITGiven a 2D plane, respond to Q queries, each of the following type: Insert x y - Insert a point (x, y) coordinate.Triangle x1 y1 x2 y2 - Print the number of triangles that can be formed, by joining the points inside the rectangle, described by two points (x1, y1) and (x2, y2), (x1, y1)
12 min read
Inserting M into N such that m starts at bit j and ends at bit i | Set-2
Given two 32-bit numbers, N and M, and two-bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all of M. Assuming index start from 0.Examples: a) N = 1024 (10000000000), M = 19 (10011), i = 2, j = 6 Output : 1100 (10001001100) b) N
10 min read
Count of 1-bit and 2-bit characters in the given binary string
Given two special characters, the first character can be represented by one bit which is 0 and the second character can be represented by two bits either 10 or 11. Now given a string represented by several bits. The task is to return the number of characters it represents. Note that the given string is always valid.Examples: Input: str = "11100" Ou
4 min read
Count bases which contains a set bit as the Most Significant Bit in the representation of N
Given a positive integer N, the task is to count the number of different bases in which, when N is represented, the most significant bit of N is a found to be a set bit. Examples: Input: N = 6Output: 4Explanation: The number 6 can be represented in 5 different bases, i.e. base 2, base 3, base 4, base 5, base 6. (6)10 in base 2: (110)2(6)10 in base
5 min read
Implementation of Bit Stuffing and Bit Destuffing
Bit Stuffing is a process of inserting an extra bit as 0, once the frame sequence encountered 5 consecutive 1's. Given an array, arr[] of size N consisting of 0's and 1's, the task is to return an array after the bit stuffing. Examples: Input: N = 6, arr[] = {1, 1, 1, 1, 1, 1}Output: 1111101Explanation: During the traversal of the array, 5 consecut
15 min read
Find the index at which bit must be set to maximise distance between next set bit
Given a binary array arr[]. The task is to find the position of any 0 in arr[] such that the distance between two set bits is maximized. Examples Input: arr = [1, 0, 0, 0, 1, 0, 1]Output: 2Explanation: Flip the bit at arr[2] Input: arr = [1, 0, 0, 0]Output: 3 Approach: The problem can be solved by finding the longest distance between adjacent set b
5 min read
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
Minimize bit flips such that each continuous segment of same bit has even length
Given a binary string S of even size that contains only 0s and 1s, the task is to find the minimum flips (that is 0 to 1 or 1 to 0) such that every contiguous subsegment that contains the same bit is of even size. Examples: Input: S = "1110011000 "Output: 3Explanation: Change S[2], S[5] and S[6] to '0'. After that S becomes "1100000000", it can be
8 min read
Find array elements with rightmost set bit at the position of the rightmost set bit in K
Given an array arr[] consisting of N and an integer K, the task is to print the elements of arr[] whose rightmost set bit is at the same position as the rightmost set bit in K. Examples: Input: arr[] = { 3, 4, 6, 7, 9, 12, 15 }, K = 7Output: { 3, 7, 9, 15 }Explanation:Binary representation of K (= 7) is 0111.Rightmost set bit in 7 is at position 1.
11 min read
Inserting m into n such that m starts at bit j and ends at bit i.
We are given two numbers n and m, and two-bit positions, i and j. Insert bits of m into n starting from j to i. We can assume that the bits j through i have enough space to fit all of m. That is, if m = 10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j = 3 and i = 2, because m could not fully f
8 min read
What is the difference between Auxiliary space and Space Complexity?
Space complexity and Auxiliary space are two of the most often confused and interchangeably used terms when talking about the space complexity of a certain algorithm: Auxiliary Space: The extra space that is taken by an algorithm temporarily to finish its workSpace Complexity: Space complexity is the total space taken by the algorithm with respect
4 min read
Trie memory optimization using hash map
We introduced and discussed an implementation in below post. Trie | (Insert and Search) - GeeksforGeeks The implementation used in above post uses an array of alphabet size with every node. It can be made memory efficient. One way to implementing Trie is linked set of nodes, where each node contains an array of child pointers, one for each symbol i
7 min read
Create Balanced Binary Tree using its Leaf Nodes without using extra space
Prerequisites: Binary Tree to Doubly Linked ListGiven a Binary Tree, the task is to create a Balanced Binary Tree from all the leaf nodes of the given Binary Tree. Examples: Input: Output: 7 8 5 9 10 Explanation: Required balanced binary tree will be: Input: Output: 13 21 29 7 15 Explanation: Required balanced binary tree is: 29 / \ 21 7 / \ 13 15
15 min read
Optimization techniques for Gradient Descent
Gradient Descent is a widely used optimization algorithm for machine learning models. However, there are several optimization techniques that can be used to improve the performance of Gradient Descent. Here are some of the most popular optimization techniques for Gradient Descent: Learning Rate Scheduling: The learning rate determines the step size
4 min read
Knuth's Optimization in Dynamic Programming
Knuth's optimization is a very powerful tool in dynamic programming, that can be used to reduce the time complexity of the solutions primarily from O(N3) to O(N2). Normally, it is used for problems that can be solved using range DP, assuming certain conditions are satisfied. In this article, we will first explore the optimization itself, and then s
15+ min read
Divide and Conquer Optimization in Dynamic Programming
Dynamic programming (DP) is arguably the most important tool in a competitive programmer's repertoire. There are several optimizations in DP that reduce the time complexity of standard DP procedures by a linear factor or more, such as Knuth's optimization, Divide and Conquer optimization, the Convex Hull Trick, etc. They are, of paramount importanc
15+ min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Code Optimization Technique (logical AND and logical OR)
Logical AND (&amp;&amp;)While using &amp;&amp; (logical AND), we must put the condition first whose probability of getting false is high so that compiler doesn’t need to check the second condition if the first condition is false. C/C++ Code #include &lt;bits/stdc++.h&gt; using namespace std; // Function to check whether n is odd bool isOdd(int n) {
7 min read
Optimization Techniques | Set 1 (Modulus)
Modulus operator is costly. The modulus operator (%) in various languages is costly operation. Ultimately every operator/operation must result in processor instructions. Some processors won't have modulus instruction at hardware level, in such case the compilers will insert stubs (predefined functions) to perform modulus. It impacts performance. Th
3 min read
Optimization for Unordered Map O(1) operations
C++ provides convenient data structures like std::set and std::map, tree-based structures with operations taking O(log n) time. With C++11, hash-based alternatives were introduced: std::unordered_set and std::unordered_map. However, concerns arise regarding potential vulnerabilities and efficiency in real-world scenarios. In this article, we're goi
12 min read
Find majority element using Bit Magic
Pre-requisite: Majority Element, Majority Element | Set-2 (Hashing)Given an array of size N, find the majority element. The majority element is the element that appears more than n/2 times in the given array. Examples: Input: {3, 3, 4, 2, 4, 4, 2, 4, 4} Output: 4 Input: {3, 3, 6, 2, 4, 4, 2, 4} Output: No Majority Element Approach:In this post, we
8 min read
Check if a number is positive, negative or zero using bit operators
Given a number N, check if it is positive, negative or zero without using conditional statements.Examples: Input : 30 Output : 30 is positive Input : -20 Output : -20 is negative Input: 0 Output: 0 is zero The signed shift n&gt;&gt;31 converts every negative number into -1 and every other into 0. When we do a -n&gt;&gt;31, if it is a positive numbe
5 min read
Find letter's position in Alphabet using Bit operation
Given a string of English alphabets. The task is, for every character in the string print its position in the English alphabets.Note: The characters in the string are considered to be case-insensitive. That is, both 'A' and 'a' is at the first position.Examples: Input: "Geeks" Output: 7 5 5 11 19 'G' is the 7th character of the alphabets 'e' is the
3 min read
Find average of two numbers using bit operation
Given two integers x and y, the task is to find the average of these numbers i.e. (x + y) / 2 using bit operations. Note that this method will give result as floor value of the calculated average.Examples: Input: x = 2, y = 4 Output: 3 (2 + 4) / 2 = 3Input: x = 10, y = 9 Output: 9 Approach: Average of two numbers x and y can be calculated using bit
3 min read
Longest Increasing Subsequence using BIT
Given an array arr, the task is to find the length of The Longest Increasing Sequence using Binary Indexed Tree (BIT) Examples: Input: arr = {6, 5, 1, 3, 2, 4, 8, 7} Output: 4 Explanation: The possible subsequences are {1 2 4 7}, {1 2 4 8}, {1 3 4 8}, {1 3 4 7} Now insert the elements one by one from left to right: 6 is inserted: max length till 5
13 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
Article Tags :
Practice Tags :
three90RightbarBannerImg