Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Sum of Bitwise XOR of each array element with all other array elements
Next article icon

Find last element in Array formed from bitwise AND of array elements

Last Updated : 29 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array A[] of size N, the task is to find the last remaining element in a new array B containing all pairwise bitwise AND of elements from A i.e., B consists of N?(N ? 1) / 2 elements, each of the form Ai & Aj for some 1 ? i < j ? N. And we can perform the following operation any number of times on a new array till there is only one element remaining such as:

  • Let X and Y be the current maximum and minimum elements of array B respectively and remove X and Y from array B and insert X|Y into it.

Examples:

Input: A[] = {2, 7, 1}
Output: 3
?Explanation: Array B will be [A1 & A2, A1 & A3, A2 & A3] = [2 & 7, 2 & 1, 7 & 1] = [2, 0, 1].
Then, we do the following operations on B:
Remove 2 and 0 from B and insert 2|0=2 into it. Now, B=[1, 2].
Remove 2 and 1 from B and insert 2|1=3 into it. Now, B=[3].
The last remaining element is thus 3.

Input: A[] = {4, 6, 7, 2}
Output: 6

Approach: The problem can be solved based on the following observation:

Observations:

  • The property of bitwise or is that if we are performing X | Y, bit i will be set if atleast one of bit i in X or Y is set.
  • This leads us to the most crucial observation of the problem, for every bit i, if bit i is set in atleast one of B1, B2, …BN?(N?1)/2, then bit i will be set in the final remaining element of B when all the operations are performed. We don’t need to worry about how the operations are performed.
  • For bit i to be set in atleast one element of B, we need to have atleast 2 elements in A say j and k where Aj and Ak both have bit i set. This sets the bit i in Aj & Ak.
  • Now we have the following solution, iterate over every valid bit i, count the number of elements in array A which have bit i set. If this count is greater than 1, the final answer will have bit i set else it will be unset.

Follow the steps mentioned below to implement the idea:

  • Create an array of size 32 to store the count of bits set in ith position.
  • Traverse the array and for each array element:
    • Find the positions in which the bit is set.
    • Increment the set bit count for that position by 1.
  • Traverse the array storing the set bit count.
    • If the count is at least 2, set that bit in the final answer.
  • Return the number formed as the required answer.

Below is the implementation of the above approach:

C++
// C++ code to implement the approach #include <bits/stdc++.h> using namespace std;  // Function to find last remaining // element in a new array int find(int a[], int n) {     int count = 0;     int b[33] = { 0 };     for (int bit = 30; bit >= 0; bit--) {         for (int i = 0; i < n; i++) {             if (((1 << bit) & (a[i])) != 0) {                 b[bit]++;             }         }     }     for (int bit = 30; bit >= 0; bit--) {         if (b[bit] > 1)             count = count + (1 << bit);     }     return count; }  // Driver Code int main() {     int A[] = { 2, 7, 1 };     int N = 3;      // Function call     cout << (find(A, N));     return 0; }  // This code is contributed by Rohit Pradhan 
Java
// Java code to implement the approach  import java.io.*; import java.util.*;  public class GFG {      // Function to find last remaining     // element in a new array     public static int find(int a[], int n)     {         int count = 0;         int b[] = new int[33];         for (int bit = 30; bit >= 0; bit--) {             for (int i = 0; i < n; i++) {                 if (((1 << bit) & (a[i])) != 0) {                     b[bit]++;                 }             }         }         for (int bit = 30; bit >= 0; bit--) {             if (b[bit] > 1)                 count = count + (1 << bit);         }         return count;     }      // Driver code     public static void main(String[] args)     {         int A[] = { 2, 7, 1 };         int N = A.length;          // Function call         System.out.println(find(A, N));     } } 
Python3
# Python code for the above approach  # Function to find last remaining element in a new array def find(a, n):     count = 0     b = [0] * 33     for bit in range(30, -1, -1):         for i in range(n):             if(((1 << bit) & (a[i])) is not 0):                 b[bit] += 1      for bit in range(30, -1, -1):         if(b[bit] > 1):             count = count + (1 << bit)      return count  A = [2, 7, 1] N = len(A)  # Function call print(find(A, N))  # This code is contributed by lokesh 
C#
// C# implementation of the approach using System; using System.Collections.Generic;  class GFG {     // Function to find last remaining     // element in a new array     public static int find(int[] a, int n)     {         int count = 0;         int[] b = new int[33];         for (int bit = 30; bit >= 0; bit--) {             for (int i = 0; i < n; i++) {                 if (((1 << bit) & (a[i])) != 0) {                     b[bit]++;                 }             }         }         for (int bit = 30; bit >= 0; bit--) {             if (b[bit] > 1)                 count = count + (1 << bit);         }         return count;     }   // Driver code  public static void Main(String[] args)  {      int[] A = { 2, 7, 1 };         int N = A.Length;          // Function call        Console.WriteLine(find(A, N));  } }  // This code is contributed by code_hunt. 
JavaScript
<script> // JS code to implement the approach      // Function to find last remaining     // element in a new array     function find(a, n)     {         let count = 0;         let b = new Array(33);         for (let i = 0; i < n; i++) {             b[i]=0;         }         for (let bit = 30; bit >= 0; bit--) {             for (let i = 0; i < n; i++) {                 if (((1 << bit) & (a[i])) != 0) {                     b[bit]++;                 }             }         }         for (let bit = 30; bit >= 0; bit--) {             if (b[bit] > 1)                 count = count + (1 << bit);         }         return count;     }  // Driver code          let A = [ 2, 7, 1 ];         let N = A.length;          // Function call         document.write(find(A, N));  // This code is contributed by sanjoy_62. </script> 

Output
3

Time Complexity: O(N) 
Auxiliary Space: O(1)


Next Article
Sum of Bitwise XOR of each array element with all other array elements
author
aarohirai2616
Improve
Article Tags :
  • Bit Magic
  • Competitive Programming
  • DSA
  • Arrays
  • Bitwise-OR
  • Bitwise-AND
Practice Tags :
  • Arrays
  • Bit Magic

Similar Reads

  • Sum of Bitwise XOR of each array element with all other array elements
    Given an array arr[] of length N, the task for every array element is to print the sum of its Bitwise XOR with all other array elements. Examples: Input: arr[] = {1, 2, 3}Output: 5 4 3Explanation:For arr[0]: arr[0] ^ arr[0] + arr[0] ^ arr[1] + arr[0] ^ arr[2] = 1^1 + 1^2 + 1^3 = 0 + 3 + 2 = 5For arr
    9 min read
  • Sum of Bitwise XOR of elements of an array with all elements of another array
    Given an array arr[] of size N and an array Q[], the task is to calculate the sum of Bitwise XOR of all elements of the array arr[] with each element of the array q[]. Examples: Input: arr[ ] = {5, 2, 3}, Q[ ] = {3, 8, 7}Output: 7 34 11Explanation:For Q[0] ( = 3): Sum = 5 ^ 3 + 2 ^ 3 + 3 ^ 3 = 7.For
    9 min read
  • Sum of Bitwise AND of each array element with the elements of another array
    Given two arrays arr1[] of size M and arr2[] of size N, the task is to find the sum of bitwise AND of each element of arr1[] with the elements of the array arr2[]. Examples: Input: arr1[] = {1, 2, 3}, arr2[] = {1, 2, 3}, M = 3, N = 3Output: 2 4 6Explanation:For elements at index 0 in arr1[], Sum = a
    11 min read
  • Sum of Bitwise OR of every array element paired with all other array elements
    Given an array arr[] consisting of non-negative integers, the task for each array element arr[i] is to print the sum of Bitwise OR of all pairs (arr[i], arr[j]) ( 0 ≤ j ≤ N ). Examples: Input: arr[] = {1, 2, 3, 4}Output: 12 14 16 22Explanation:For i = 0 the required sum will be (1 | 1) + (1 | 2) + (
    11 min read
  • Minimum Bitwise AND operations to make any two array elements equal
    Given an array of integers of size 'n' and an integer 'k', We can perform the Bitwise AND operation between any array element and 'k' any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make an
    10 min read
  • Sum of Bitwise OR of each array element of an array with all elements of another array
    Given two arrays arr1[] of size M and arr2[] of size N, the task is to find the sum of bitwise OR of each element of arr1[] with every element of the array arr2[]. Examples: Input: arr1[] = {1, 2, 3}, arr2[] = {1, 2, 3}, M = 3, N = 3Output: 7 8 9Explanation: For arr[0]: Sum = arr1[0]|arr2[0] + arr1[
    11 min read
  • Count ways to make Bitwise XOR of odd and even indexed elements equal by removing an array element
    Given an array arr[] of length N, the task is to find the count of array indices such that removing an element from these indices makes the Bitwise xor of odd-indexed elements and even-indexed (1-based indexing) elements are equal. Examples: Input: arr[] = {1, 0, 1, 0, 1}, N = 5Output: 3Explanation:
    10 min read
  • Minimum Bitwise OR operations to make any two array elements equal
    Given an array arr[] of integers and an integer K, we can perform the Bitwise OR operation between any array element and K any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make any two eleme
    9 min read
  • Check if original Array Sum is Odd or Even using Bitwise AND of Array
    Given an integer N denoting the size of an array and the bitwise AND (K) of all elements of the array. The task is to determine whether the total sum of the elements is odd or even or cannot be determined. Examples: Input: N = 1, K = 11Output: OddExplanation: As there is only one element in the arra
    6 min read
  • Minimum Bitwise XOR operations to make any two array elements equal
    Given an array arr[] of integers of size N and an integer K. One can perform the Bitwise XOR operation between any array element and K any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make a
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences