Open In App

Find the missing element in an array of integers represented in binary format

Last Updated : 06 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given N strings which represents all integers from 0 to N in binary format except any one. The task is to find the missing number. Input consists of an array of strings where array elements are represented in binary format.

Examples: 

Input: arr[] = {"0000", "0001", "0010", "0100"} 
Output: 3

Input: arr[] = {"0000", "0001", "0010", "0011", "0100", "0110", "0111", "1000"} 
Output: 5 

Approach:

  • An imbalance of 1's and 0's in the least significant bits of the numbers can be observed in the N integers given. Since one number is missing either a 0 or 1 from the LSB is missing. If the number which is missing has LSB = 0 then count(1) will be greater than equal to count(0). If LSB of missing number is 1 then count(1) is less than count(0).
  • From the step 1 one can easily determine the LSB of missing number.
  • Once determined, discard all the numbers having LSB different from that of the missing number, i.e., if the missing number has LSB = 0, then discard all the numbers with LSB = 1 and vice versa.
  • Continue the process from step 1 all over again and recur for the next LSB.
  • Continue with the above process till all the bits are traversed.

Below is the implementation of the above approach: 

C++
// C++ program to find the missing integer
// in N numbers when N bits are given
#include <bits/stdc++.h>
using namespace std;
 
class BitInteger {
private:
    bool* bits;
 
public:
    static const int INTEGER_SIZE = 32;
 
    BitInteger()
    {
        bits = new bool[INTEGER_SIZE];
    }
 
    // Constructor to convert an integer
    // variable into binary format
    BitInteger(int value)
    {
        bits = new bool[INTEGER_SIZE];
 
        for (int j = 0; j < INTEGER_SIZE; j++) {
 
            // The if statement will shift the
            // original value j times.
            // So that appropriate (INTEGER_SIZE - 1 -j)th
            // bits will be either 0/1.
            //  (INTEGER_SIZE - 1 -j)th bit for all
            // j = 0 to INTEGER_SIZE-1 corresponds
            // to  LSB to MSB respectively.
            if (((value >> j) & 1) == 1)
                bits[INTEGER_SIZE - 1 - j] = true;
            else
                bits[INTEGER_SIZE - 1 - j] = false;
        }
    }
    // Constructor to convert a
    // string into binary format.
    BitInteger(string str)
    {
        int len = str.length();
        int x = INTEGER_SIZE - len;
        bits = new bool[INTEGER_SIZE];
 
        // If len = 4. Then x = 32 - 4 = 28.
        // Hence iterate from
        // bit 28 to bit 32 and just
        // replicate the input string.
        int i = 0;
 
        for (int j = x; j <= INTEGER_SIZE && i < len; j++, i++) {
            if (str[i] == '1')
                bits[j] = true;
            else
                bits[j] = false;
        }
    }
 
    // this function fetches the kth bit
    int fetch(int k)
    {
        if (bits[k])
            return 1;
 
        return 0;
    }
 
    // this function will set a value
    // of bit indicated by k to given bitValue
    void set(int k, int bitValue)
    {
        if (bitValue == 0)
            bits[k] = false;
        else
            bits[k] = true;
    }
 
    // convert binary representation to integer
    int toInt()
    {
        int n = 0;
        for (int i = 0; i < INTEGER_SIZE; i++) {
            n = n << 1;
            if (bits[i])
                n = n | 1;
        }
        return n;
    }
};
 
// Function to find the missing number
int findMissingFunc(list<BitInteger>& myList, int column)
{
    // This means that we have processed
    // the entire 32 bit binary number.
    if (column < 0)
        return 0;
 
    list<BitInteger> oddIndices;
    list<BitInteger> evenIndices;
 
    for (BitInteger t : myList) {
 
        // Initially column = LSB. So
        // if LSB of the given number is 0,
        // then the number is even and
        // hence we add it to evenIndices list.
        // else if LSB = 0 then add it to oddIndices list.
        if (t.fetch(column) == 0)
            evenIndices.push_back(t);
        else
            oddIndices.push_back(t);
    }
 
    // Step 1 and Step 2 of the algorithm.
    // Here we determine the LSB bit of missing number.
 
    if (oddIndices.size() >= evenIndices.size())
 
        // LSB of the missing number is 0.
        // Hence it is an even number.
        // Step 3 and 4 of the algorithm
        // (discarding all odd numbers)
        return (findMissingFunc(evenIndices, column - 1)) << 1 | 0;
 
    else
        // LSB of the missing number is 1.
        // Hence it is an odd number.
        // Step 3 and 4 of the algorithm
        // (discarding all even numbers)
        return (findMissingFunc(oddIndices, column - 1)) << 1 | 1;
}
 
// Function to return the missing integer
int findMissing(list<BitInteger>& myList)
{
    // Initial call is with given array and LSB.
    return findMissingFunc(myList, BitInteger::INTEGER_SIZE - 1);
}
 
// Driver Code.
int main()
{
 
    // a corresponds to the input array which
    // is a list of binary numbers
    list<BitInteger> a = { BitInteger("0000"), BitInteger("0001"),
                           BitInteger("0010"), BitInteger("0100"),
                           BitInteger("0101") };
    int missing1 = findMissing(a);
    cout << missing1 << "\n";
 
    return 0;
}
Java
// Java program to find the missing integer
// in N numbers when N bits are given
import java.util.*;

class BitInteger {
    boolean[] bits;

    public static int INTEGER_SIZE = 32;

    public BitInteger()
    {
        bits = new boolean[INTEGER_SIZE];
    }

    // Constructor to convert an integer
    // variable into binary format
    public BitInteger(int value)
    {
        bits = new boolean[INTEGER_SIZE];

        for (int j = 0; j < INTEGER_SIZE; j++) {

            // The if statement will shift the
            // original value j times.
            // So that appropriate (INTEGER_SIZE - 1 -j)th
            // bits will be either 0/1.
            //  (INTEGER_SIZE - 1 -j)th bit for all
            // j = 0 to INTEGER_SIZE-1 corresponds
            // to  LSB to MSB respectively.
            if (((value >> j) & 1) == 1)
                bits[INTEGER_SIZE - 1 - j] = true;
            else
                bits[INTEGER_SIZE - 1 - j] = false;
        }
    }
    // Constructor to convert a
    // string into binary format.
    public BitInteger(String str)
    {
        int len = str.length();
        int x = INTEGER_SIZE - len;
        bits = new boolean[INTEGER_SIZE];

        // If len = 4. Then x = 32 - 4 = 28.
        // Hence iterate from
        // bit 28 to bit 32 and just
        // replicate the input string.
        int i = 0;

        for (int j = x; j <= INTEGER_SIZE && i < len;
             j++, i++) {
            if (str.charAt(i) == '1')
                bits[j] = true;
            else
                bits[j] = false;
        }
    }

    // this function fetches the kth bit
    int fetch(int k)
    {
        if (bits[k])
            return 1;

        return 0;
    }

    // this function will set a value
    // of bit indicated by k to given bitValue
    void set(int k, int bitValue)
    {
        if (bitValue == 0)
            bits[k] = false;
        else
            bits[k] = true;
    }

    // convert binary representation to integer
    int toInt()
    {
        int n = 0;
        for (int i = 0; i < INTEGER_SIZE; i++) {
            n = n << 1;
            if (bits[i])
                n = n | 1;
        }
        return n;
    }
};

class GFG {

    // Function to find the missing number
    static int findMissingFunc(ArrayList<BitInteger> myList,
                               int column)
    {
        // This means that we have processed
        // the entire 32 bit binary number.
        if (column < 0)
            return 0;

        ArrayList<BitInteger> oddIndices
            = new ArrayList<BitInteger>();
        ArrayList<BitInteger> evenIndices
            = new ArrayList<BitInteger>();

        for (BitInteger t : myList) {

            // Initially column = LSB. So
            // if LSB of the given number is 0,
            // then the number is even and
            // hence we add it to evenIndices list.
            // else if LSB = 0 then add it to oddIndices
            // list.
            if (t.fetch(column) == 0)
                evenIndices.add(t);
            else
                oddIndices.add(t);
        }

        // Step 1 and Step 2 of the algorithm.
        // Here we determine the LSB bit of missing number.

        if (oddIndices.size() >= evenIndices.size())

            // LSB of the missing number is 0.
            // Hence it is an even number.
            // Step 3 and 4 of the algorithm
            // (discarding all odd numbers)
            return (findMissingFunc(evenIndices,
                                    column - 1))
                << 1
                | 0;

        else
            // LSB of the missing number is 1.
            // Hence it is an odd number.
            // Step 3 and 4 of the algorithm
            // (discarding all even numbers)
            return (findMissingFunc(oddIndices, column - 1))
                << 1
                | 1;
    }

    // Function to return the missing integer
    static int findMissing(ArrayList<BitInteger> myList)
    {
        // Initial call is with given array and LSB.
        return findMissingFunc(myList,
                               BitInteger.INTEGER_SIZE - 1);
    }
    public static void main(String[] args)
    {
        // a corresponds to the input array which
        // is a list of binary numbers
        ArrayList<BitInteger> a
            = new ArrayList<BitInteger>();
        a.add(new BitInteger("0000"));
        a.add(new BitInteger("0001"));
        a.add(new BitInteger("0010"));
        a.add(new BitInteger("0100"));
        a.add(new BitInteger("0101"));
        int missing1 = findMissing(a);
        System.out.println(missing1);
    }
}

// This code is contributed by phasing17
Python
# Python3 program to find the missing integer
# in N numbers when N bits are given
class BitInteger :

    # Constructor to convert an integer
    # variable into binary format
    def __init__(self, value): 
        self.INTEGER_SIZE = 32;
        self.bits = [False for _ in range(self.INTEGER_SIZE)];

        if isinstance(value, int):
            for j in range(self.INTEGER_SIZE): 

                # The if statement will shift the
                # original value j times.
                # So that appropriate (INTEGER_SIZE - 1 -j)th
                # bits will be either 0/1.
                #  (INTEGER_SIZE - 1 -j)th bit for all
                # j = 0 to INTEGER_SIZE-1 corresponds
                # to  LSB to MSB respectively.
                if (((value >> j) & 1) == 1):
                    bits[self.INTEGER_SIZE - 1 - j] = True;
                else:
                    bits[self.INTEGER_SIZE - 1 - j] = False;
            
        elif isinstance(value, str):
            # Constructor to convert a
            # string into binary format.

            if 1:
                str1 = value;
                len1 = len(str1);
                x = self.INTEGER_SIZE - len1
                self.bits = [0 for _ in range(self.INTEGER_SIZE)];

                # If len = 4. Then x = 32 - 4 = 28.
                # Hence iterate from
                # bit 28 to bit 32 and just
                # replicate the input string.
                i = 0;
                
                j = x
                while  j <= self.INTEGER_SIZE and i < len1 :
                    if (str1[i] == '1'):
                        self.bits[j] = True;
                    else:
                        self.bits[j] = False;
                    j += 1
                    i += 1

    # this function fetches the kth bit
    def fetch(self, k): 
        if (self.bits[k]):
            return 1;

        return 0;
    
    # this function will set a value
    # of bit indicated by k to given bitValue
    def sets(self, k, bitValue) :
        if (bitValue == 0):
            self.bits[k] = False;
        else:
            self.bits[k] = True;
    
    # convert binary representation to integer
    def toInt(self): 
        n = 0;
        for i in range(self.INTEGER_SIZE):
            n = n << 1;
            if (self.bits[i]):
                n = n | 1;
        
        return n;
    
# Function to find the missing number
def findMissingFunc(myList, column) :
    # This means that we have processed
    # the entire 32 bit binary number.
    if (column < 0):
        return 0;

    oddIndices = [];
    evenIndices = [];

    for t in myList:

        # Initially column = LSB. So
        # if LSB of the given number is 0,
        # then the number is even and
        # hence we add it to evenIndices list.
        # else if LSB = 0 then add it to oddIndices list.
        if (t.fetch(column) == 0):
            evenIndices.append(t);
        else:
            oddIndices.append(t);
    

    # Step 1 and Step 2 of the algorithm.
    # Here we determine the LSB bit of missing number.

    if (len(oddIndices) >= len(evenIndices)):

        # LSB of the missing number is 0.
        # Hence it is an even number.
        # Step 3 and 4 of the algorithm
        # (discarding all odd numbers)
        return (findMissingFunc(evenIndices, column - 1)) << 1 | 0;

    else:
        # LSB of the missing number is 1.
        # Hence it is an odd number.
        # Step 3 and 4 of the algorithm
        # (discarding all even numbers)
        return (findMissingFunc(oddIndices, column - 1)) << 1 | 1;


# Function to return the missing integer
def findMissing(myList) :
  
    # Initial call is with given array and LSB.
    return findMissingFunc(myList, 31);

# Driver Code.

# a corresponds to the input array which
# is a list of binary numbers
a = [BitInteger("0000"), BitInteger("0001"), BitInteger("0010"), BitInteger("0100"), BitInteger("0101")]
missing1 = findMissing(a);
print(missing1);

# This code is contributed by phasing17
C#
// C# program to find the missing integer
// in N numbers when N bits are given

using System;
using System.Collections.Generic;

class BitInteger {

    bool[] bits;

    public static int INTEGER_SIZE = 32;

    public BitInteger() { bits = new bool[INTEGER_SIZE]; }

    // Constructor to convert an integer
    // variable into binary format
    public BitInteger(int value)
    {
        bits = new bool[INTEGER_SIZE];

        for (int j = 0; j < INTEGER_SIZE; j++) {

            // The if statement will shift the
            // original value j times.
            // So that appropriate (INTEGER_SIZE - 1 -j)th
            // bits will be either 0/1.
            //  (INTEGER_SIZE - 1 -j)th bit for all
            // j = 0 to INTEGER_SIZE-1 corresponds
            // to  LSB to MSB respectively.
            if (((value >> j) & 1) == 1)
                bits[INTEGER_SIZE - 1 - j] = true;
            else
                bits[INTEGER_SIZE - 1 - j] = false;
        }
    }
    // Constructor to convert a
    // string into binary format.
    public BitInteger(string str)
    {
        int len = str.Length;
        int x = INTEGER_SIZE - len;
        bits = new bool[INTEGER_SIZE];

        // If len = 4. Then x = 32 - 4 = 28.
        // Hence iterate from
        // bit 28 to bit 32 and just
        // replicate the input string.
        int i = 0;

        for (int j = x; j <= INTEGER_SIZE && i < len;
             j++, i++) {
            if (str[i] == '1')
                bits[j] = true;
            else
                bits[j] = false;
        }
    }

    // this function fetches the kth bit
    public int fetch(int k)
    {
        if (bits[k])
            return 1;

        return 0;
    }

    // this function will set a value
    // of bit indicated by k to given bitValue
    public void set(int k, int bitValue)
    {
        if (bitValue == 0)
            bits[k] = false;
        else
            bits[k] = true;
    }

    // convert binary representation to integer
    public int toInt()
    {
        int n = 0;
        for (int i = 0; i < INTEGER_SIZE; i++) {
            n = n << 1;
            if (bits[i])
                n = n | 1;
        }
        return n;
    }
};

class GFG {

    // Function to find the missing number
    static int findMissingFunc(List<BitInteger> myList,
                               int column)
    {
        // This means that we have processed
        // the entire 32 bit binary number.
        if (column < 0)
            return 0;

        List<BitInteger> oddIndices
            = new List<BitInteger>();
        List<BitInteger> evenIndices
            = new List<BitInteger>();

        foreach(BitInteger t in myList)
        {

            // Initially column = LSB. So
            // if LSB of the given number is 0,
            // then the number is even and
            // hence we add it to evenIndices list.
            // else if LSB = 0 then add it to oddIndices
            // list.
            if (t.fetch(column) == 0)
                evenIndices.Add(t);
            else
                oddIndices.Add(t);
        }

        // Step 1 and Step 2 of the algorithm.
        // Here we determine the LSB bit of missing number.

        if (oddIndices.Count >= evenIndices.Count)

            // LSB of the missing number is 0.
            // Hence it is an even number.
            // Step 3 and 4 of the algorithm
            // (discarding all odd numbers)
            return (findMissingFunc(evenIndices,
                                    column - 1))
                << 1
                | 0;

        else
            // LSB of the missing number is 1.
            // Hence it is an odd number.
            // Step 3 and 4 of the algorithm
            // (discarding all even numbers)
            return (findMissingFunc(oddIndices, column - 1))
                << 1
                | 1;
    }

    // Function to return the missing integer
    static int findMissing(List<BitInteger> myList)
    {
        // Initial call is with given array and LSB.
        return findMissingFunc(myList,
                               BitInteger.INTEGER_SIZE - 1);
    }
    public static void Main(string[] args)
    {
        // a corresponds to the input array which
        // is a list of binary numbers
        List<BitInteger> a = new List<BitInteger>();
        a.Add(new BitInteger("0000"));
        a.Add(new BitInteger("0001"));
        a.Add(new BitInteger("0010"));
        a.Add(new BitInteger("0100"));
        a.Add(new BitInteger("0101"));
        int missing1 = findMissing(a);
        Console.WriteLine(missing1);
    }
}

// This code is contributed by phasing17
JavaScript
// JS program to find the missing integer
// in N numbers when N bits are given
class BitInteger {


    // Constructor to convert an integer
    // variable into binary format
    constructor(value) {
        this.INTEGER_SIZE = 32;
        this.bits = new Array(this.INTEGER_SIZE);

        if (typeof value == 'number') {
            for (var j = 0; j < this.INTEGER_SIZE; j++) {

                // The if statement will shift the
                // original value j times.
                // So that appropriate (INTEGER_SIZE - 1 -j)th
                // bits will be either 0/1.
                //  (INTEGER_SIZE - 1 -j)th bit for all
                // j = 0 to INTEGER_SIZE-1 corresponds
                // to  LSB to MSB respectively.
                if (((value >> j) & 1) == 1)
                    bits[this.INTEGER_SIZE - 1 - j] = true;
                else
                    bits[this.INTEGER_SIZE - 1 - j] = false;
            }
        } else if (typeof value == 'string') {
            // Constructor to convert a
            // string into binary format.

            {
                let str = value;
                let len = str.length;
                let x = this.INTEGER_SIZE - len;
                this.bits = new Array(this.INTEGER_SIZE);

                // If len = 4. Then x = 32 - 4 = 28.
                // Hence iterate from
                // bit 28 to bit 32 and just
                // replicate the input string.
                let i = 0;

                for (let j = x; j <= this.INTEGER_SIZE && i < len; j++, i++) {
                    if (str.charAt(i) == '1')
                        this.bits[j] = true;
                    else
                        this.bits[j] = false;
                }
            }
        }
    }

    // this function fetches the kth bit
    fetch(k) {
        if (this.bits[k])
            return 1;

        return 0;
    }

    // this function will set a value
    // of bit indicated by k to given bitValue
    set(k, bitValue) {
        if (bitValue == 0)
            this.bits[k] = false;
        else
            this.bits[k] = true;
    }

    // convert binary representation to integer
    toInt() {
        let n = 0;
        for (let i = 0; i < this.INTEGER_SIZE; i++) {
            n = n << 1;
            if (this.bits[i])
                n = n | 1;
        }
        return n;
    }
};

// Function to find the missing number
function findMissingFunc(myList, column) {
    // This means that we have processed
    // the entire 32 bit binary number.
    if (column < 0)
        return 0;

    let oddIndices = [];
    let evenIndices = [];

    for (var t of myList) {

        // Initially column = LSB. So
        // if LSB of the given number is 0,
        // then the number is even and
        // hence we add it to evenIndices list.
        // else if LSB = 0 then add it to oddIndices list.
        if (t.fetch(column) == 0)
            evenIndices.push(t);
        else
            oddIndices.push(t);
    }

    // Step 1 and Step 2 of the algorithm.
    // Here we determine the LSB bit of missing number.

    if (oddIndices.length >= evenIndices.length)

        // LSB of the missing number is 0.
        // Hence it is an even number.
        // Step 3 and 4 of the algorithm
        // (discarding all odd numbers)
        return (findMissingFunc(evenIndices, column - 1)) << 1 | 0;

    else
        // LSB of the missing number is 1.
        // Hence it is an odd number.
        // Step 3 and 4 of the algorithm
        // (discarding all even numbers)
        return (findMissingFunc(oddIndices, column - 1)) << 1 | 1;
}

// Function to return the missing integer
function findMissing(myList) {
    // Initial call is with given array and LSB.
    return findMissingFunc(myList, 31);
}

// Driver Code.

// a corresponds to the input array which
// is a list of binary numbers
let a = [new BitInteger("0000"), new BitInteger("0001"),
    new BitInteger("0010"), new BitInteger("0100"),
    new BitInteger("0101")
]
let missing1 = findMissing(a);
console.log(missing1);


// This code is contributed by phasing17

Output
3

Time Complexity: O(N)

Approach : Using XOR

Follow the below approach steps:

  • XOR all integers from 0 to N.
  • XOR all the integers represented by the binary strings in the array.
  • XOR of these two results will give the missing number because all numbers except the missing one will cancel out.

Below is the implementation of the above approach: 

C++
#include <bitset>
#include <iostream>
#include <string>
#include <vector>

int find_missing_number(const std::vector<std::string>& arr)
{
    int n = arr.size(); // The number of binary strings in
                        // the array. Since one number is
                        // missing, n = N
    int xor_all = 0;

    // XOR all integers from 0 to N (inclusive)
    for (int i = 0; i <= n; ++i) {
        xor_all ^= i;
    }

    int xor_arr = 0;

    // XOR all the integers represented by the binary
    // strings in the array
    for (const auto& num : arr) {
        xor_arr ^= std::bitset<32>(num).to_ulong();
    }

    // The missing number is the XOR of xor_all and xor_arr
    int missing_number = xor_all ^ xor_arr;
    return missing_number;
}

int main()
{
    std::vector<std::string> arr
        = { "0000", "0001", "0010", "0100" };
    std::cout << find_missing_number(arr) << std::endl;
    return 0;
}

// This code is contributed by Shivam
Python
def find_missing_number(arr):
    # The number of binary strings in the array. Since one number is missing, n = N
    n = len(arr)
    xor_all = 0

    # XOR all integers from 0 to N (inclusive)
    for i in range(n + 1):
        xor_all ^= i

    xor_arr = 0

    # XOR all the integers represented by the binary strings in the array
    for num in arr:
        xor_arr ^= int(num, 2)

    # The missing number is the XOR of xor_all and xor_arr
    missing_number = xor_all ^ xor_arr
    return missing_number


print(find_missing_number(["0000", "0001", "0010", "0100"]))

Output
3
  • Time Complexity: O(N)
  • Auxiliary space: O(1)

Next Article
Article Tags :
Practice Tags :

Similar Reads