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++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a = 2, b = 10;
int size = abs (b - a) + 1;
int * array = new int [size];
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
import java.lang.*;
class GFG {
public static void main(String[] args)
{
int a = 2 , b = 10 ;
int size = Math.abs(b - a) + 1 ;
int array[] = new int [size];
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 + " " );
}
}
|
Python3
import math
a = 2
b = 10
size = abs (b - a) + 1
array = [ 0 ] * size
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 = " " )
|
C#
using System;
class GFG {
static public void Main ()
{
int a = 2, b = 10;
int size = Math.Abs(b - a) + 1;
int [] array = new int [size];
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 + " " );
}
}
|
PHP
<?php
$a = 2;
$b = 10;
$size = abs ( $b - $a ) + 1;
$array = array_fill (0, $size , 0);
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 . " " ;
?>
|
Javascript
<script>
let a = 2, b = 10;
let size = Math.abs(b - a) + 1;
let array = [];
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 + " " );
</script>
|
OutputMULTIPLES 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
- Find the actual index in int[] that needs to be bit manipulated it will be bitwise index/ 32.
- 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
- Turn on the bit by doing | (bitwise OR) with (1 << X) (here we turn on the Xth bit by bit manipulation)
- 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++.
- Now instead of using arithmetic operators we can use bitwise operations for efficiency
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
bool checkbit( int array[], int index)
{
return array[index >> 5] & (1 << (index & 31));
}
void setbit( int array[], int index)
{
array[index >> 5] |= (1 << (index & 31));
}
int main()
{
int a = 2, b = 10;
int size = abs (b - a)+1;
size = ceil (( double )size/32);
int * array = new int [size];
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
import java.io.*;
import java.util.*;
class GFG
{
static boolean checkbit( int array[], int index)
{
int val = array[index >> 5 ] & ( 1 << (index & 31 ));
if (val == 0 )
return false ;
return true ;
}
static void setbit( int array[], int index)
{
array[index >> 5 ] |= ( 1 << (index & 31 ));
}
public static void main(String args[])
{
int a = 2 , b = 10 ;
int size = Math.abs(b-a);
size = ( int )Math.ceil(( double )size / 32 );
int [] array = new int [size];
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 + " " );
}
}
|
Python3
import math
def checkbit( array, index):
return array[index >> 5 ] & ( 1 << (index & 31 ))
def setbit( array, index):
array[index >> 5 ] | = ( 1 << (index & 31 ))
a = 2
b = 10
size = abs (b - a)
size = math.ceil(size / 32 )
array = [ 0 for i in range (size)]
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 = " " )
|
C#
using System;
class GFG
{
static bool checkbit( int []array, int index)
{
int val = array[index >> 5] &
(1 << (index & 31));
if (val == 0)
return false ;
return true ;
}
static void setbit( int []array, int index)
{
array[index >> 5] |= (1 << (index & 31));
}
public static void Main(String []args)
{
int a = 2, b = 10;
int size = Math.Abs(b-a);
size = ( int )Math.Ceiling(( double )size / 32);
int [] array = new int [size];
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 + " " );
}
}
|
Javascript
<script>
function checkbit(array, index)
{
return array[index >> 5] &
(1 << (index & 31));
}
function setbit(array, index)
{
array[index >> 5] |=
(1 << (index & 31));
}
let a = 2, b = 10;
let size = Math.abs(b - a);
size = Math.ceil(size / 32);
let array = new Array(size);
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 + " " );
</script>
|
OutputMULTIPLES of 2 and 5:
2 4 5 6 8 10
Time Complexity: O(|b – a|)
Auxiliary space: O(|b – a|)