Minimum operations required to make two elements equal in Array
Last Updated :
23 Jul, 2025
Given array A[] of size N and integer X, the task is to find the minimum number of operations to make any two elements equal in the array. In one operation choose any element A[i] and replace it with A[i] & X. where & is bitwise AND. If such operations do not exist print -1.
Examples:
Input: A[] = {1, 2, 3, 7}, X = 3
Output: 1
Explanation: Performing above operation on A[4] = 7, A[4] = A[4] & X = 7 & 3 = 3. Array A[] becomes {1, 2, 3, 3}, 3 exists on 3rd position so in one operation two elements can be made equal in array A[].
Input: A[] = {1, 2, 3}, X = 7
Output: -1
Explanation: It is not possible to make any two elements equal by performing above operations any number of times.
Naive approach: The basic way to solve the problem is as follows:
Making bitwise AND of current element and checking whether if any other element exists with same value.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following idea:
This problem can be divided in four cases:
- Case 1: Two equal elements already exist in array A[], In that case answer will be 0.
- Case 2: It is not possible to create two elements which are equal by above operations, In that case answer will be -1.
- Case 3: It is possible to make any two elements equal by performing above operations exactly once.
- Case 4: It is possible to make any two elements equal by performing above operations exactly twice.
Follow the steps below to solve the problem:
- Creating HashMap[].
- Iterating from 1 to N and filling frequency HashMap[] if some element repeats again return 0.
- Iterating from 1 to N and for each iteration remove the current element from HashMap[] and perform an operation on the current index and check whether it exists in HashMap[] if it exists return 1 else insert the current element again in HashMap[].
- Clear the HashMap[].
- Iterating from 1 to N and performing an operation on each element along with filling HashMap[], if the frequency of any element is more than 2 then return 2.
- Finally, if the function reaches the end return -1.
Below is the implementation of the above approach:
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to minimum operations required
// to make two elements equal in array.
int minOperations(int A[], int N, int M)
{
// Creating HashMap
map<int, int> HashMap;
for (int i = 0; i < N; i++) {
// Filling frequency HashMap
HashMap[A[i]]++;
// If two values same already exist
if (HashMap[A[i]] >= 2)
return 0;
}
for (int i = 0; i < N; i++) {
// Removing occurrence of current
// element from HashMap
HashMap[A[i]]--;
// Performing operation on
// current index
int performOperation = A[i] & M;
// Check if another element exists
// with same value
if (HashMap[performOperation])
return 1;
// Inserting back occurrence
// of element
HashMap[A[i]]++;
}
// Clearing the HashMap
HashMap.clear();
for (int i = 0; i < N; i++) {
// Performing operation on
// current index
int performOperation = A[i] & M;
// Inserting this element
// in Hashmap
HashMap[performOperation]++;
// If two elements exist such that
// both formed with operation
if (HashMap[A[i]] == 2)
return 2;
}
// If answer do not exist
return -1;
}
// Driver Code
int main()
{
// Input 1
int A[] = { 1, 2, 3, 7 };
int N = sizeof(A) / sizeof(A[0]);
int X = 3;
// Function Call
cout << minOperations(A, N, X) << endl;
// Input 2
int A1[] = { 1, 2, 3 };
int N1 = sizeof(A1) / sizeof(A1[0]);
int X1 = 7;
// Function Call
cout << minOperations(A1, N1, X1) << endl;
return 0;
}
Python3
# Python code to implement the approach
# Function to minimum operations required
# to make two elements equal in array.
def minOperations(A, N, M):
# Creating HashMap
HashMap = {}
for i in range(N):
# If two values same already exist
if A[i] in HashMap: return 0
# Filling frequency HashMap
else: HashMap[A[i]] = 1
for i in range(N):
# Removing occurrence of current
# element from HashMap
HashMap[A[i]] -= 1
# Performing operation on
# current index
performOperation = A[i] & M
# Check if another element exists
# with same value
if (HashMap[performOperation]): return 1
# Inserting back occurrence
# of element
HashMap[A[i]] += 1
# Clearing the HashMap
HashMap = {}
for i in range(N):
# Performing operation on
# current index
performOperation = A[i] & M
# Inserting this element
# in Hashmap
if performOperation in HashMap: HashMap[performOperation] += 1
else: HashMap[performOperation] = 1
# If two elements exist such that
# both formed with operation
if (HashMap[A[i]] == 2): return 2
# If answer do not exist
return -1
# Driver Code
# Input 1
A = [1, 2, 3, 7]
N = len(A)
X = 3
# Function Call
print(minOperations(A, N, X))
# Input 2
A1 = [1, 2, 3]
N1 = len(A1)
X1 = 7
# Function Call
print(minOperations(A1, N1, X1))
C#
//C# code to implement the approach
using System;
using System.Collections.Generic;
// Function to minimum operations required
// to make two elements equal in array.
class MainClass {
public static int MinOperations(int[] A, int N, int M) {
// Creating HashMap
Dictionary<int, int> HashMap = new Dictionary<int, int>();
for (int i = 0; i < N; i++)
{
// Filling frequency HashMap
if (HashMap.ContainsKey(A[i]))
{
HashMap[A[i]]++;
} else {
HashMap.Add(A[i], 1);
}
// If two values same already exist
if (HashMap[A[i]] >= 2)
{
return 0;
}
}
for (int i = 0; i < N; i++)
{
// Removing occurrence of current element from HashMap
HashMap[A[i]]--;
// Performing operation on current index
int performOperation = A[i] & M;
// Check if another element exists with same value
if (HashMap.ContainsKey(performOperation) &&
HashMap[performOperation] > 0) {
return 1;
}
// Inserting back occurrence of element
HashMap[A[i]]++;
}
// Clearing the HashMap
HashMap.Clear();
for (int i = 0; i < N; i++)
{
// Performing operation on current index
int performOperation = A[i] & M;
// Inserting this element in Hashmap
if (HashMap.ContainsKey(performOperation))
{
HashMap[performOperation]++;
}
else
{
HashMap.Add(performOperation, 1);
}
// If two elements exist such that both formed with operation
if (HashMap[performOperation] == 2)
{
return 2;
}
}
// If answer do not exist it will return -1
return -1;
}
// Drive Code
public static void Main(string[] args)
{
// Input 1
int[] A = { 1, 2, 3, 7 };
int N = A.Length;
int X = 3;
// Test Case 1 Function Call
Console.WriteLine(MinOperations(A, N, X));
// Input 2
int[] A1 = { 1, 2, 3 };
int N1 = A1.Length;
int X1 = 7;
// Test Case 2 Function Call
Console.WriteLine(MinOperations(A1, N1, X1));
}
}
// This Code is contributed by nikhilsainiofficial546
JavaScript
// JavaScript code to implement the approach
function minOperations(A, N, M) {
// Creating HashMap
let HashMap = {};
for (let i = 0; i < N; i++) {
// Filling frequency HashMap
if (HashMap[A[i]] === undefined) HashMap[A[i]] = 0;
HashMap[A[i]]++;
// If two values same already exist
if (HashMap[A[i]] >= 2) return 0;
}
for (let i = 0; i < N; i++) {
// Removing occurrence of current
// element from HashMap
HashMap[A[i]]--;
// Performing operation on
// current index
let performOperation = A[i] & M;
// Check if another element exists
// with same value
if (HashMap[performOperation]) return 1;
// Inserting back occurrence
// of element
HashMap[A[i]]++;
}
// Clearing the HashMap
HashMap = {};
for (let i = 0; i < N; i++) {
// Performing operation on
// current index
let performOperation = A[i] & M;
// Inserting this element
// in Hashmap
if (HashMap[performOperation] === undefined) HashMap[performOperation] = 0;
HashMap[performOperation]++;
// If two elements exist such that
// both formed with operation
if (HashMap[A[i]] === 2) return 2;
}
// If answer do not exist
return -1;
}
// Input 1
let A = [1, 2, 3, 7];
let N = A.length;
let X = 3;
// Function Call
console.log(minOperations(A, N, X));
// Input 2
let A1 = [1, 2, 3];
let N1 = A1.length;
let X1 = 7;
// Function Call
console.log(minOperations(A1, N1, X1));
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class GFG {
// Function to minimum operations required
// to make two elements equal in array.
static int minOperations(int A[], int N, int M)
{
// Creating HashMap
Map<Integer, Integer> HashMap = new HashMap<Integer, Integer>();
for (int i = 0; i < N; i++)
{
// Filling frequency HashMap
if (HashMap.containsKey(A[i]))
HashMap.put(A[i], HashMap.get(A[i]) + 1);
else
HashMap.put(A[i], 1);
// If two values same already exist
if (HashMap.get(A[i]) >= 2)
return 0;
}
for (int i = 0; i < N; i++) {
// Removing occurrence of current
// element from HashMap
if (HashMap.containsKey(A[i]))
HashMap.put(A[i], HashMap.get(A[i]) - 1);
else
HashMap.put(A[i], 1);
// Performing operation on
// current index
int performOperation = A[i] & M;
// Check if another element exists
// with same value
if (HashMap.get(performOperation)>0)
return 1;
// Inserting back occurrence
// of element
if (HashMap.containsKey(A[i]))
HashMap.put(A[i], HashMap.get(A[i]) + 1);
else
HashMap.put(A[i], 1);
}
// Clearing the HashMap
HashMap.clear();
for (int i = 0; i < N; i++) {
// Performing operation on
// current index
int performOperation = A[i] & M;
// Inserting this element
// in Hashmap
if (HashMap.containsKey(A[i]))
HashMap.put(A[i], HashMap.get(A[i]) + 1);
else
HashMap.put(A[i], 1);
// If two elements exist such that
// both formed with operation
if (HashMap.get(A[i]) == 2)
return 2;
}
// If answer do not exist
return -1;
}
// Driver Code
public static void main(String args[])
{
// Input 1
int A[] = { 1, 2, 3, 7 };
int N = A.length;
int X = 3;
// Function Call
System.out.println(minOperations(A, N, X));
// Input 2
int A1[] = { 1, 2, 3 };
int N1 = A1.length;
int X1 = 7;
// Function Call
System.out.println(minOperations(A1, N1, X1));
}
}
Time Complexity: O(N*logN)
Auxiliary Space: O(N)
Related Articles:
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem