Skip to content
Related Articles

Related Articles

Improve Article

Space optimization using bit manipulations

  • Difficulty Level : Medium
  • Last Updated : 06 May, 2021

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.

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

 

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.


C++




// C++ code to 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);
 
    // Size that will be used is actual_size/32
    // ceil is used to initialize the array with
    // positive number
    size = ceil(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

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :