VOOZH about

URL: https://www.geeksforgeeks.org/dsa/bit-manipulation-for-competitive-programming/

⇱ Bit Manipulation for Competitive Programming - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Bit Manipulation for Competitive Programming

Last Updated : 23 Jul, 2025

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.

Bitwise Operators are used to perform operations on individual bits in binary representations of numbers. Some common bitwise operators that are used in competitive programming:-

  • It is a bitwise operator that takes two numbers as operands and performs logical AND on corresponding bits of two numbers. When both bits in the compared position are 1, the bit in the resulting binary representation is 1, otherwise, the result is 0.
  • This bitwise operator takes two numbers as operands and performs a logical OR operation on their corresponding bits. When at least one of the bits in the compared position is 1, the bit in the resulting binary representation is 1, otherwise, the result is 0.
  • The bitwise XOR operator also takes two numbers as operands and performs an exclusive OR operation on their corresponding bits. When exactly one of the bits in the compared position is 1, the bit in the resulting binary representation is 1, otherwise, the result is 0.
  • The bitwise NOT is a unary operator operates on a single number and flips (inverts) all its bits. It changes 0s to 1s and 1s to 0s, effectively creating the one's complement of the input number.
  • The left shift operator takes two operands, the number to be shifted and the number of places to move it to the left. It shifts the bits of the first operand to the left by the number of places specified in the second operand. This is actually multiplying a number by 2 raised to the power of shift counts. For example: 5 << 2 =20, the binary representation of 5 (0101) is shifted left by 2 positions, resulting in 20 (10100) in decimal.
  • The right shift operator also takes two operands, the number to be shifted and the number of places to move it to the right. It shifts the bits of the first operand to the right by the number of places specified in the second operand. This is equivalent to dividing a number by 2 raised to the power of the shift count (integer division). For example: 20 >> 2 = 5, where the binary representation of 20 (10100) is shifted right by 2 positions, resulting in 5 (00101) in decimal.

1.

This can be done by left-shifting the value 1 by 'pos' positions (1<< pos) and performing a bitwise OR operation with number n. This operation effectively turns on the bit at the specified position.

2.

This can be done by left-shifting the value 1 by pos positions (1<< pos) and then use bitwise NOT operator ‘~’ to unset this shifted 1, making the bit at position pos to 0 and then use Bitwise AND with the number n that will unset bit at desired positoon of number n.

3.

Use the bitwise XOR (^) operator to toggle (flip) the bit at the given position. If the bit is 0, it becomes 1, and if it's 1, it becomes 0.

4.

This can be done by performing a bitwise AND operation with a mask having only that bit set. If the result is non-zero, the bit is set; otherwise, it's unset.

5.

A power of two is a number with only one bit set in its binary representation, while the number just before it has that bit unset and all the following bits set. Consequently, when you perform a bitwise AND operation between a number and its predecessor, the result will always be 0.

Suppose you are given an array a of n numbers and q queries and each query is of the form (l,r). The task is to compute Bitwise AND of the numbers from index l to r i.e., (al & al+1 ..... & ar-1 & ar).

A simple approach will be for each query travese from index l to r and compute Bitwise AND. By this we will be able to answer each query in O(n) time in worst case.

But to answer each query in constant time prefix sum can be a useful method.

1.

  • To start, we want to determine whether a specific bit (let's call it the "j-th bit") in the binary representation of a number at a given index (let's call it "i") is set (1) or unset (0). We accomplish this by creating a 2D array called "temp," with dimensions "n x 32" (assuming 32-bit integers), where "n" is the number of elements in our array. Each cell "temp[i][j]" stores this information for the i-th number's j-th bit.
  • Next, we calculate prefix sums for each bit position (from 0 to 31, assuming 32-bit integers) in our "temp" array. This "prefix sum" array, let's call it "psum," keeps track of the count of numbers up to a certain index that have their j-th bit set.
  • Now, let's focus on finding the Bitwise AND of numbers within a specific range, say from index "l" to "r." To determine whether the j-th bit of the result should be set to 1, we compare the number of elements with the j-th bit set in the range [l, r]. This can be done using prefix sum array psum. psum[i][j] will denote numbers of elements till index i, which have their jth bit set and
    psum[r][j]-psum[l-1][j] will give number of indexes from l to r which have their jth bit set.
  • If the count of numbers with the j-th bit set in the range [l, r] is equal to the range size (r - l + 1), it means that all numbers in that range have their j-th bit set. In this case, we set the j-th bit of the result to 1. Otherwise, if not all numbers in the range have the j-th bit set, we set it to 0.
👁 Bit-Manipulation-for-Competitive-Programming
Bit Manipulation for Competitive Programming


Below is the code for above approach:


Output
Bitwise AND of range [2,4] is: 2

Note- When you increase the range for Bitwise AND, the result will never increase; it will either stay the same or decrease. This is a useful property and we can apply Binary search on answer we are given to determine the largest range whose Bitwise AND is greater than or equal to a given number.

2.

Bitwise OR can be computed in a similar way. WE will make temp and psum array in a similar way,

  • To determine whether the j-th bit of the result should be set to 1, we compare the number of elements with the j-th bit set in the range [l, r].
  • Use the prefix sum array, psum, we can get count of numbers with the jth bit set in range [l,r] from psum[r][j]-psum[l-1][j].
  • If the count of numbers with the j-th bit set in the range [l, r] is greater than 0, it means at least one number in that range has the j-th bit set. In this case, we set the j-th bit of the result to 1. Otherwise, if no numbers in the range have the j-th bit set, we set it to 0.
👁 Bit-Manipulation-for-Competitive-Programming-1
Bit Manipulation for Competitive Programming

Below is the code for above approach:


Output
Bitwise OR of range [2,4] is: 11

Note: When you increase the range for Bitwise OR, the result will never decrease; it will either stay the same or increase. Again this is a useful property and we can apply Binary search on answer we are given to determine the smallest range whose Bitwise OR is smaller than or equal to a given number.

3.

Bitwise XOR for a range can be done in similar way:

  • To determine whether the j-th bit of the result should be set to 1, we compare the number of elements with the j-th bit set in the range [l, r].
  • Use the prefix sum array, psum, we can get count of numbers with the jth bit set in range [l,r] from psum[r][j]-psum[l-1][j].
  • If the count of numbers with the j-th bit set in the range [l, r] is odd, it means that the j-th bit of the result should be set to 1. If the count is even, the j-th bit of the result should be set to 0.

👁 Bit-Manipulation-for-Competitive-Programming-2

Below is the implementation of the above approach:


Output
Bitwise XOR of range [2,4] is :10

a|b = a⊕b + a&b

a⊕(a&b) = (a|b)⊕b

(a&b)⊕(a|b) = a⊕b

a+b = a|b + a&b

a+b = a⊕b + 2(a&b)

In most of the problems involving bit manipulation it is better to work bit by bit i.e., break down the problem into individual bits. Focus on solving the problem for a single bit position before moving on to the next.

Let's consider few examples:

Given an integer array arr. The task is to find the size of largest subset such that bitwise AND of all the elements of the subset is greater than 0.

  • To start, notice that for a subset's bitwise AND to be greater than zero, there must be a bit position where all the elements in the subset have that bit set to 1.
  • We approach this problem bit by bit, examining each of the 32 possible bit positions in the numbers.
  • For each bit position, we count how many elements in the array have that bit set to 1.
  • Our answer is the largest count of elements that have their bit set for a particular bit position.

Given an integer array arr of size n. A graph is formed using these elements. There exists an edge between index i and index j if i!=j and a[i] AND a[j]>0. The task is to determine whether there exists a cycle in the graph.

We begin by analyzing each bit position in the binary representation of the numbers and for each bit determine how many elements have that bit set.

  • For a specific bit position,
    • If there are more than two elements in the array that have that bit set, it indicates that there exists a cycle in the graph.
    • Otherwise, there will be almost 2 numbers that have a particular bit set. It follows that each bit can contribute to atmost 1 edge.
  • Importantly, the entire graph won't have more than 32 edges because each number in the array is represented using 32 bits.
  • To ascertain the presence of a cycle in the graph,a straightforward Depth-First Search (DFS) algorithm can be used.

Count Bit Sets of a Number

Count Total Set Bits of a first N natural number

Check whether the number has only first and last bits set

Shortest path length between two given nodes such that adjacent nodes are at bit difference 2

Calculate Bitwise OR of two integers from their given Bitwise AND and Bitwise XOR values

Unset least significant K bits of a given number

Find all powers of 2 less than or equal to a given number

Powers-2-required-sum

Print bitwise AND set of a number N

Print all submasks of a given mask

Count of subsets not containing adjacent elements

Find array such that no subarray has xor zero or Y

Minimum Bitwise OR operations to make any two array elements equal

Minimum Bitwise XOR operations to make any two array elements equal

Minimum Bitwise AND operations to make any two array elements equal

Longest substring whose characters can be rearranged to form a Palindrome

Number of ordered pairs such that (Ai & Aj) = 0

Minimize product of first N – 1 natural numbers by swapping same positioned bits of pairs

Minimum number N such that total set bits of all numbers from 1 to N is at-least X

Find a number X such that XOR of given Array after adding X to each element is 0

Count numbers in the range [L, R] having only three set bits

Comment
Article Tags: