Open In App

Count remaining array elements after reversing binary representation of each array element

Last Updated : 31 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N positive integers, the task is to modify every array element by reversing them binary representation and count the number of elements in the modified array that were also present in the original array.

Examples:

Input: arr[] = {2, 4, 5, 20, 16} 
Output: 2
Explanation:
2 -> (10)2     -> (1) 2   -> 1 i.e. not present in the original array
4 ->  (100 )2   -> (1 )2 -> 1 i.e. not present in the original array
5 ->  (101 )2  -> (101 )2 -> 5 i.e. present in the original array
20 -> (10100)2 -> (101)2 -> 5 i.e. present in the original array
16 -> (10000)2  -> (1)2   -> 1 i.e. not present in the original array

Input: arr[] = {1, 30, 3, 8, 12}
Output: 4

Approach: Follow the steps below to solve the problem:

  • Initialize a variable, say count, to store the required count, a vector, say V, to store the reversed bits of each array element, and a Map to store the array elements in the original array.
  • Traverse the given array arr[] and perform the following steps:
    • Store the number formed by reversing each bit of binary representation of element arr[i] in the vector V.
    • Mark the presence of the current element arr[i] in the Map.
  • Traverse the vector V, and if any element present in the vector is also present in the Map, then increment count by 1.
  • After completing the above steps, print the value of the count as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to reverse the binary
// representation of a number
int findReverse(int N)
{
    int rev = 0;
 
    // Traverse bits of N
    // from the right
    while (N > 0) {
 
        // Bitwise left
        // shift 'rev' by 1
        rev <<= 1;
 
        // If current bit is '1'
        if (N & 1 == 1)
            rev ^= 1;
 
        // Bitwise right
        // shift N by 1
        N >>= 1;
    }
 
    // Required number
    return rev;
}
 
// Function to count elements from the
// original array that are also present
// in the array formed by reversing the
// binary representation of each element
void countElements(int arr[], int N)
{
    // Stores the reversed num
    vector<int> ans;
 
    // Iterate from [0, N]
    for (int i = 0; i < N; i++) {
        ans.push_back(findReverse(arr[i]));
    }
 
    // Stores the presence of integer
    unordered_map<int, int> cnt;
    for (int i = 0; i < N; i++) {
        cnt[arr[i]] = 1;
    }
 
    // Stores count of elements
    // present in original array
    int count = 0;
 
    // Traverse the array
    for (auto i : ans) {
 
        // If current number is present
        if (cnt[i])
            count++;
    }
 
    // Print the answer
    cout << count << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 30, 3, 8, 12 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    countElements(arr, N);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
public class GFG
{
 
  // Function to reverse the binary
  // representation of a number
  static int findReverse(int N)
  {
    int rev = 0;
 
    // Traverse bits of N
    // from the right
    while (N > 0)
    {
 
      // Bitwise left
      // shift 'rev' by 1
      rev <<= 1;
 
      // If current bit is '1'
      if ((N & 1) == 1)
        rev ^= 1;
 
      // Bitwise right
      // shift N by 1
      N >>= 1;
    }
 
    // Required number
    return rev;
  }
 
  // Function to count elements from the
  // original array that are also present
  // in the array formed by reversing the
  // binary representation of each element
  static void countElements(int arr[], int N)
  {
    // Stores the reversed num
    Vector<Integer> ans = new Vector<Integer>();
 
    // Iterate from [0, N]
    for (int i = 0; i < N; i++)
    {
      ans.add(findReverse(arr[i]));
    }
 
    // Stores the presence of integer
    HashMap<Integer, Integer> cnt = new HashMap<Integer, Integer>();
    for (int i = 0; i < N; i++)
    {
      cnt.put(arr[i], 1);
    }
 
    // Stores count of elements
    // present in original array
    int count = 0;
 
    // Traverse the array
    for(Integer i : ans) {
 
      // If current number is present
      if (cnt.containsKey(i))
        count++;
    }
 
    // Print the answer
    System.out.println(count);
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int[] arr = { 1, 30, 3, 8, 12 };
    int N = arr.length;
 
    countElements(arr, N);
  }
}
 
// This code is contributed by divyeshrabadiya07.


Python3




# Python 3 program for the above approach
 
# Function to reverse the binary
# representation of a number
def findReverse(N):
    rev = 0
 
    # Traverse bits of N
    # from the right
    while (N > 0):
       
        # Bitwise left
        # shift 'rev' by 1
        rev <<= 1
 
        # If current bit is '1'
        if (N & 1 == 1):
            rev ^= 1
 
        # Bitwise right
        # shift N by 1
        N >>= 1
 
    # Required number
    return rev
 
# Function to count elements from the
# original array that are also present
# in the array formed by reversing the
# binary representation of each element
def countElements(arr, N):
   
    # Stores the reversed num
    ans = []
 
    # Iterate from [0, N]
    for i in range(N):
        ans.append(findReverse(arr[i]))
 
    # Stores the presence of integer
    cnt = {}
    for i in range(N):
        cnt[arr[i]] = 1
 
    # Stores count of elements
    # present in original array
    count = 0
 
    # Traverse the array
    for i in ans:
       
        # If current number is present
        if (i in cnt):
            count += 1
 
    # Print the answer
    print(count)
 
# Driver Code
if __name__ == '__main__':
    arr =  [1, 30, 3, 8, 12]
    N =  len(arr)
 
    countElements(arr, N)
 
    # This code is contributed by SURENDRA_GANGWAR.


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to reverse the binary
  // representation of a number
  static int findReverse(int N)
  {
    int rev = 0;
 
    // Traverse bits of N
    // from the right
    while (N > 0) {
 
      // Bitwise left
      // shift 'rev' by 1
      rev <<= 1;
 
      // If current bit is '1'
      if ((N & 1) == 1)
        rev ^= 1;
 
      // Bitwise right
      // shift N by 1
      N >>= 1;
    }
 
    // Required number
    return rev;
  }
 
  // Function to count elements from the
  // original array that are also present
  // in the array formed by reversing the
  // binary representation of each element
  static void countElements(int[] arr, int N)
  {
    // Stores the reversed num
    List<int> ans = new List<int>();
 
    // Iterate from [0, N]
    for (int i = 0; i < N; i++) {
      ans.Add(findReverse(arr[i]));
    }
 
    // Stores the presence of integer
    Dictionary<int, int> cnt
      = new Dictionary<int, int>();
    for (int i = 0; i < N; i++) {
      cnt[arr[i]] = 1;
    }
 
    // Stores count of elements
    // present in original array
    int count = 0;
 
    // Traverse the array
    foreach(int i in ans)
    {
 
      // If current number is present
      if (cnt.ContainsKey(i))
        count++;
    }
 
    // Print the answer
    Console.WriteLine(count);
  }
 
  // Driver Code
  public static void Main()
  {
    int[] arr = { 1, 30, 3, 8, 12 };
    int N = arr.Length;
 
    countElements(arr, N);
  }
}
 
// This code is contributed by chitranayal.


Javascript




<script>
// Js program for the above approach
 
// Function to reverse the binary
// representation of a number
function findReverse(N) {
     
    let rev = 0;
 
    // Traverse bits of N
    // from the right
    while (N > 0) {
 
        // Bitwise left
        // shift 'rev' by 1
        rev <<= 1;
 
        // If current bit is '1'
        if (N & 1 == 1)
            rev ^= 1;
 
        // Bitwise right
        // shift N by 1
        N >>= 1;
    }
 
    // Required number
    return rev;
}
 
// Function to count elements from the
// original array that are also present
// in the array formed by reversing the
// binary representation of each element
function countElements( arr, N)
{
    // Stores the reversed num
    let ans=[];
 
    // Iterate from [0, N]
    for (let i = 0; i < N; i++) {
        ans.push(findReverse(arr[i]));
    }
 
    // Stores the presence of integer
    let cnt = new Map();
    for (let i = 0; i < N; i++) {
        cnt[arr[i]] = 1;
    }
 
    // Stores count of elements
    // present in original array
    let count = 0;
 
    // Traverse the array
    for (let i = 0;i<ans.length;i++) {
 
        // If current number is present
        if (cnt[ans[i]])
            count++;
    }
 
    // Print the answer
    document.write( count,'<br>');
}
 
// Driver Code
let arr = [ 1, 30, 3, 8, 12 ];
let N = arr.length;
 
countElements(arr, N);
</script>


Output: 

4

 

Time Complexity: O(N), as we are using a loop to traverse N times.

Auxiliary Space: O(N), as we are using extra space for the map cnt.



Similar Reads

Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element
Given an array arr[] consisting of N integers, the task is to find the remaining array element after subtracting each element from its next adjacent element and removing the last array element repeatedly. Examples: Input: arr[] = {3, 4, 2, 1}Output: 4Explanation:Operation 1: The array arr[] modifies to {4 - 3, 2 - 4, 1 - 2} = {1, -2, -1}.Operation
8 min read
Sum of array elements after reversing each element
Given an array arr[] consisting of N positive integers, the task is to find the sum of all array elements after reversing digits of every array element. Examples: Input: arr[] = {7, 234, 58100}Output: 18939Explanation:Modified array after reversing each array elements = {7, 432, 18500}.Therefore, the sum of the modified array = 7 + 432 + 18500 = 18
7 min read
Find the last remaining element after repeated removal of an element from pairs of increasing adjacent array elements
Given an array arr[] consisting of N integers, the task is to print the last remaining array element after repeatedly selecting pairs of increasing adjacent elements (arr[i], arr[i + 1]) and removing any of the elements in the pair. If it is not possible to reduce the array to a single element, then print "Not Possible". Examples: Input: arr[] = {3
4 min read
Find the last positive element remaining after repeated subtractions of smallest positive element from all Array elements
Given an array arr[] consisting of N positive integers, the task is to find the last positive array element remaining after repeated subtractions of the smallest positive array element from all array elements. Examples: Input: arr[] = {3, 5, 4, 7}Output: 2Explanation: Subtract the smallest positive element from the array, i.e. 3, the new array is a
6 min read
Find the maximum between N and the number formed by reversing 32-bit binary representation of N
Given a positive 32-bit integer N, the task is to find the maximum between the value of N and the number obtained by decimal representation of reversal of binary representation of N in a 32-bit integer. Examples: Input: N = 6Output: 1610612736Explanation: Binary representation of 6 in a 32-bit integer is 00000000000000000000000000000110 i.e., (0000
6 min read
Print the Array formed by reversing the given Array after each index
Given an array arr[], the task is to print the array formed by traversing given array from first to the last index by flipping the whole array after printing every element. Example: Input: arr = {0, 1, 2, 3, 4, 5} Output: 0 4 2 2 4 0Explanation: On 1st iteration element on index 0 -&gt; 0 is printed then the whole array is flipped: {0, 1, 2, 3, 4,
6 min read
Remaining array element after repeated removal of the smallest element from pairs with absolute difference of 2 or 0
Given an array arr[] consisting of N positive integers, the task is to check if it is possible to reduce the size of the array to 1 by repeatedly removing the smallest element from a pair having absolute difference of 2 or 0 between them. If it is not possible to reduce, then print "-1". Otherwise, print the last remaining element in the array. Exa
6 min read
Last element remaining after repeated removal of Array elements at perfect square indices
Given an array arr[](1-based indexing) consisting of N integers, the task is to find the last element remaining element after repeated removal of array element at perfect square indices. Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: 5Explanation:Following the removal of array element at perfect square indices that are performed: Removing array el
7 min read
Count pairs of equal array elements remaining after every removal
Given an array arr[] of size N, the task for every array element arr[i], is to count the number of pairs of equal elements that can be obtained by removing arr[i] from the array. Examples: Input: arr[] = { 1, 1, 1, 2 } Output: 1 1 1 3 Explanation: Removing arr[0] from the array modifies arr[] to { 1, 1, 2 } and count of pairs of equal elements = 1
11 min read
Average of remaining elements after removing K largest and K smallest elements from array
Given an array of N integers. The task is to find the average of the numbers after removing k largest elements and k smallest element from the array i.e. calculate the average value of the remaining N - 2K elements. Examples: Input: arr = [1, 2, 4, 4, 5, 6], K = 2Output: 4Remove 2 smallest elements i.e. 1 and 2Remove 2 largest elements i.e. 5 and 6
5 min read