Count pair of nodes with greater Bitwise AND than Bitwise XOR in given Linked List
Last Updated :
18 Apr, 2023
Given a singly linked list, the task is to Count the pairs of nodes with greater Bitwise AND than Bitwise XOR.
Examples:
Input: list: 1->4->2->6->3
Output: 2
Explanation: 1st List Node Pair: (4, 6 ), Bitwise AND = 4, Bitwise XOR = 2
2nd List Node Pair: (2, 3), Bitwise AND = 2, Bitwise XOR = 1
Input: list: 17->34->62->46->30->51
Output: 7
Explanation: Valid List Node Pairs are (17, 30 ), (34, 62), (34, 46), (34, 51), (62, 46), (62, 51), (46, 51).
Naive Approach: The naive approach is to iterate the linked list and for each node find all other possible nodes forming a pair such that the bitwise AND is greater than bitwise XOR.
Below is the implementation of the above approach:
C++
// C++ program for above approach
#include<bits/stdc++.h>
using namespace std;
// Structure of node of singly linked list
struct Node {
int data;
Node *next;
Node(int x) {
data = x;
}
};
Node *head;
// Inserting new node at the beginning of the linked list
void push(int new_data)
{
// Create a new node with the given data.
Node *new_node = new Node(new_data);
// Make the new node point to the head.
if (head == NULL) {
head = new_node;
return;
}
new_node->next = head;
// Make the new node as the head node.
head = new_node;
}
// Function to find the count of all possible pairs
static int PerfectPair()
{
int ans = 0;
while (head != NULL) {
Node *temp = head->next;
while (temp != NULL) {
if ((head->data & temp->data) > (head->data ^ temp->data)) {
ans++;
}
temp = temp->next;
}
head = head->next;
}
return ans;
}
// Driver code
int main()
{
// Create an empty singly linked list
head = NULL;
// Insert values in Linked List
push(51);
push(30);
push(46);
push(62);
push(34);
push(17);
// Call PerfectPair function
cout << PerfectPair();
}
// This code is contributed by ajaymakvana.
Java
// Java program for above approach
import java.util.ArrayList;
import java.util.HashMap;
public class GFG {
// Structure of node of singly linked list
static class Node {
int data;
Node next;
Node(int x) { data = x; }
};
// Inserting new node
// at the beginning of the linked list
static void push(int new_data)
{
// Create a new node with the given data.
Node new_node = new Node(new_data);
// Make the new node point to the head.
if (head == null) {
head = new_node;
return;
}
new_node.next = head;
// Make the new node as the head node.
head = new_node;
}
static Node head;
// Function to find the
// count of all possible pairs
static int PerfectPair()
{
int ans = 0;
while(head!=null){
Node temp = head.next;
while(temp!=null){
if((head.data & temp.data) > (head.data ^ temp.data)){
ans++;
}
temp = temp.next;
}
head = head.next;
}
return ans;
}
// Driver code
public static void main(String[] args)
{
// Create an empty singly linked list
head = null;
// Insert values in Linked List
push(51);
push(30);
push(46);
push(62);
push(34);
push(17);
// Call PerfectPair function
System.out.println(PerfectPair());
}
}
Python3
# Python program for above approach
# Structure of node of singly linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# Inserting new node
# at the beginning of the linked list
def push(self, new_data):
# Create a new node with the given data.
new_node = Node(new_data)
# Make the new node point to the head.
if self.head == None:
self.head = new_node
return
new_node.next = self.head
self.head = new_node
# Function to find the
# count of all possible pairs
def PerfectPair(self):
ans = 0
current = self.head
while current:
temp = current.next
while temp:
if (current.data & temp.data) > (current.data ^ temp.data):
ans += 1
temp = temp.next
current = current.next
return ans
# Driver code
if __name__ == "__main__":
llist = LinkedList()
# Insert values in Linked List
llist.push(51)
llist.push(30)
llist.push(46)
llist.push(62)
llist.push(34)
llist.push(17)
print(llist.PerfectPair())
# This code is contributed by divya_p123.
C#
// C# program for above approach
using System;
public class GFG {
// Structure of node of singly linked list
class Node {
public int data;
public Node next;
public Node(int x) { data = x; }
}
// Inserting new node
// at the beginning of the linked list
static void push(int new_data)
{
// Create a new node with the given data.
Node new_node = new Node(new_data);
// Make the new node point to the head.
if (head == null) {
head = new_node;
return;
}
new_node.next = head;
// Make the new node as the head node.
head = new_node;
}
static Node head;
// Function to find the
// count of all possible pairs
static int PerfectPair()
{
int ans = 0;
while (head != null) {
Node temp = head.next;
while (temp != null) {
if ((head.data & temp.data)
> (head.data ^ temp.data)) {
ans++;
}
temp = temp.next;
}
head = head.next;
}
return ans;
}
static public void Main()
{
// Create an empty singly linked list
head = null;
// Insert values in Linked List
push(51);
push(30);
push(46);
push(62);
push(34);
push(17);
// Call PerfectPair function
Console.WriteLine(PerfectPair());
}
}
// This code is contributed by lokeshmvs21.
JavaScript
<script>
// Structure of node of singly linked list
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
let head;
// Inserting new node at the beginning of the linked list
function push(newData) {
// Create a new node with the given data.
let newNode = new Node(newData);
// Make the new node point to the head.
if (head === null) {
head = newNode;
return;
}
newNode.next = head;
// Make the new node as the head node.
head = newNode;
}
// Function to find the count of all possible pairs
function PerfectPair() {
let ans = 0;
while (head !== null) {
let temp = head.next;
while (temp !== null) {
if ((head.data & temp.data) > (head.data ^ temp.data)) {
ans++;
}
temp = temp.next;
}
head = head.next;
}
return ans;
}
// Create an empty singly linked list
head = null;
// Insert values in Linked List
push(51);
push(30);
push(46);
push(62);
push(34);
push(17);
// Call PerfectPair function
console.log(PerfectPair());
</script>
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: The problem can be solved efficiently by using the below observation:
If First Set bit (Most significant bit) of two number is at same position, then the Bitwise AND or that numbers is always greater than the XOR because the XOR of two 1 is 0 and AND of two 1s is 1.
For any other cases, XOR will be always greater than the AND
Follow the below steps to solve the problem:
- Traverse the linked list and Store the MSB position for each Node value in an array.
- Initialize a variable ans to store the total possible pairs.
- Create a hash map to store the count of nodes that have the same value of MSB (Most significant bit).
- Traverse the array containing the MSB position and in each iteration:
- Get the count of nodes that have the same position of MSB.
- Add the count of possible pairs from these nodes into ans.
- Return the answer variable.
Below is the implementation of the above approach:
C++
// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
// Structure of node of singly linked list
struct Node {
int data;
Node* next;
Node(int x)
{
data = x;
next = NULL;
}
};
// Inserting new node
// at the beginning of the linked list
void push(struct Node** head_ref,
int new_data)
{
// Create a new node with the given data.
struct Node* new_node
= new Node(new_data);
// Make the new node point to the head.
new_node->next = (*head_ref);
// Make the new node as the head node.
(*head_ref) = new_node;
}
// Function to find the
// count of all possible pairs
int PerfectPair(Node* head)
{
int ans = 0, size = 0;
unordered_map<int, int> mp;
vector<int> firstSetBit;
// Iterate Linked List and store the
// firstSetBit position
// for each Node Data
while (head != NULL) {
firstSetBit.push_back(
log2(head->data));
size++;
head = head->next;
}
// Check all previous node
// which can make
// pair with current node
for (int i = 0; i < size; i++) {
ans += mp[firstSetBit[i]];
mp[firstSetBit[i]]++;
}
return ans;
}
// Driver code
int main()
{
// Create an empty singly linked list
struct Node* head = NULL;
// Insert values in Linked List
push(&head, 51);
push(&head, 30);
push(&head, 46);
push(&head, 62);
push(&head, 34);
push(&head, 17);
// Call PerfectPair function
cout << PerfectPair(head);
return 0;
}
Java
// Java program for above approach
import java.util.ArrayList;
import java.util.HashMap;
public class GFG {
// Structure of node of singly linked list
static class Node {
int data;
Node next;
Node(int x) { data = x; }
};
// Inserting new node
// at the beginning of the linked list
static void push(int new_data)
{
// Create a new node with the given data.
Node new_node = new Node(new_data);
// Make the new node point to the head.
if (head == null) {
head = new_node;
return;
}
new_node.next = head;
// Make the new node as the head node.
head = new_node;
}
static Node head;
// Function to find the
// count of all possible pairs
static int PerfectPair()
{
int ans = 0, size = 0;
HashMap<Integer, Integer> mp
= new HashMap<Integer, Integer>();
ArrayList<Integer> firstSetBit
= new ArrayList<Integer>();
// Iterate Linked List and store the
// firstSetBit position
// for each Node Data
while (head != null) {
firstSetBit.add(log2(head.data));
size++;
head = head.next;
}
// Check all previous node
// which can make
// pair with current node
for (int i = 0; i < size; i++) {
int val
= mp.getOrDefault(firstSetBit.get(i), 0);
ans += val;
mp.put(firstSetBit.get(i), val + 1);
}
return ans;
}
// Function to calculate the
// log base 2 of an integer
public static int log2(int N)
{
// calculate log2 N indirectly
// using log() method
int result = (int)(Math.log(N) / Math.log(2));
return result;
}
// Driver code
public static void main(String[] args)
{
// Create an empty singly linked list
head = null;
// Insert values in Linked List
push(51);
push(30);
push(46);
push(62);
push(34);
push(17);
// Call PerfectPair function
System.out.println(PerfectPair());
}
}
// This code is contributed by jainlovely450
Python3
# Python program for above approach
import math
class GFG:
# Structure of node of singly linked list
class Node:
data = 0
next = None
def __init__(self, x):
self.data = x
# Inserting new node
# at the beginning of the linked list
@staticmethod
def push(new_data):
# Create a new node with the given data.
new_node = GFG.Node(new_data)
# Make the new node point to the head.
if (GFG.head == None):
GFG.head = new_node
return
new_node.next = GFG.head
# Make the new node as the head node.
GFG.head = new_node
head = None
# Function to find the
# count of all possible pairs
@staticmethod
def PerfectPair(K):
ans = 0
size = 0
mp = dict()
firstSetBit = []
# Iterate Linked List and store the
# firstSetBit position
# for each Node Data
while (GFG.head != None):
firstSetBit.append(GFG.log2(GFG.head.data))
size += 1
GFG.head = GFG.head.next
# Check all previous node
# which can make
# pair with current node
i = 0
while (i < size):
try:
val = mp[firstSetBit[i]]
except:
val = 0
ans += val
mp[firstSetBit[i]] = val + 1
i += 1
return ans
# Function to calculate the
# log base 2 of an integer
@staticmethod
def log2(N):
# calculate log2 N indirectly
# using log() method
result = int((math.log(N) / math.log(2)))
return result
# Driver code
@staticmethod
def main(args):
K = 4
# Create an empty singly linked list
GFG.head = None
# Insert values in Linked List
GFG.push(51)
GFG.push(30)
GFG.push(46)
GFG.push(62)
GFG.push(34)
GFG.push(17)
# Call PerfectPair function
print(GFG.PerfectPair(K))
if __name__ == "__main__":
GFG.main([])
'''This Code is written by Rajat Kumar'''
C#
// C# program for above approach
using System;
using System.Collections.Generic;
using System.Collections;
static class GFG
{
public class Node
{
public int data;
public Node next;
public Node(int x) { data = x; }
};
// Structure of node of singly linked list
// Inserting new node
// at the beginning of the linked list
static void push(int new_data)
{
// Create a new node with the given data.
Node new_node = new Node(new_data);
// Make the new node point to the head.
if (head == null)
{
head = new_node;
return;
}
new_node.next = head;
// Make the new node as the head node.
head = new_node;
}
static Node head;
// Function to find the
// count of all possible pairs
static int PerfectPair()
{
int ans = 0, size = 0;
Dictionary<int, int> mp = new Dictionary<int, int>();
ArrayList firstSetBit = new ArrayList();
// Iterate Linked List and store the
// firstSetBit position
// for each Node Data
while (head != null)
{
firstSetBit.Add(log2(head.data));
size++;
head = head.next;
}
// Check all previous node
// which can make
// pair with current node
for (int i = 0; i < size; i++)
{
int val = mp.GetValueOrDefault((int)firstSetBit[i], 0);
ans += val;
mp[(int)firstSetBit[i]] = val + 1;
}
return ans;
}
// Function to calculate the
// log base 2 of an integer
public static int log2(int N)
{
// calculate log2 N indirectly
// using log() method
int result = (int)(Math.Log(N) / Math.Log(2));
return result;
}
// Driver code
public static void Main()
{
// Create an empty singly linked list
head = null;
// Insert values in Linked List
push(51);
push(30);
push(46);
push(62);
push(34);
push(17);
// Call PerfectPair function
Console.Write(PerfectPair());
}
}
// This code is contributed by Saurabh Jaiswal
JavaScript
// Class for node of singly linked list
class Node {
constructor(data) {
// Store the data of node
this.data = data;
// Point to the next node in the linked list
this.next = null;
}
}
// Class for the GFG program
class GFG {
// static variable to store the head node of linked list
static head = null;
// Function to insert new node at the beginning of linked list
static push(newData) {
// Create a new node with the given
let newNode = new Node(newData);
// If linked list is empty, make the new node as head
if (!GFG.head) {
GFG.head = newNode;
return;
}
// Make the new node point to the current head
newNode.next = GFG.head;
GFG.head = newNode;
}
static log2(N) {
return Math.floor(Math.log2(N));
}
// Function to find the count of all possible pairs
static PerfectPair(K) {
let ans = 0;
let size = 0;
const mp = {};
const firstSetBit = [];
// Iterate linked list and store the first set bit position for each node data
let currentNode = GFG.head;
while (currentNode) {
firstSetBit.push(GFG.log2(currentNode.data));
size++;
currentNode = currentNode.next;
}
// Check all previous node which can make pair with current node
for (let i = 0; i < size; i++) {
const val = mp[firstSetBit[i]] || 0;
ans += val;
mp[firstSetBit[i]] = val + 1;
}
return ans;
}
// Main function to run the program
static main() {
const K = 4;
// Insert values in linked list
GFG.push(51);
GFG.push(30);
GFG.push(46);
GFG.push(62);
GFG.push(34);
GFG.push(17);
// Call PerfectPair function
console.log(GFG.PerfectPair(K));
}
}
// Call the main function
GFG.main();
Time Complexity: O(N * log N)
Auxiliary Space: O(N)
Similar Reads
Count of pairs with bitwise XOR value greater than its bitwise AND value
Given an array arr that contains N positive Integers. Find the count of all possible pairs whose bitwise XOR value is greater than bitwise AND value Examples: Input : arr[]={ 12, 4, 15}Output: 2Explanation: 12 ^ 4 = 8, 12 & 4 = 4. so 12 ^ 4 > 12 & 4 4 ^ 15 = 11, 4 & 15 = 4. so 4 ^ 15
4 min read
Count of pairs with bitwise XOR value greater than its bitwise AND value | Set 2
Given an array arr that contains N positive Integers. Find the count of all possible pairs whose bit wise XOR value is greater than bit wise AND value Examples: Input : arr[]={ 12, 4 , 15}Output: 2Explanation: 12 ^ 4 = 8 , 12 & 4 = 4 . so 12 ^ 4 > 12 & 4 4 ^ 15 = 11, 4 & 15 = 4. so 4
6 min read
Count pairs from an array whose Bitwise OR is greater than Bitwise AND
Given an array A[] consisting of N integers, the task is to count the number of pairs (i, j) such that i < j, and Bitwise OR of A[i] and A[j] is greater than Bitwise AND of A[i] and A[j]. Examples: Input: A[] = {1, 4, 7}Output: 3Explanation: There are 3 such pairs: (1, 4), (4, 7), (1, 7).1) 1 | 4
10 min read
Find size of largest subset with bitwise AND greater than their bitwise XOR
Given an array arr[] of N integers, the task is to find the size of the largest subset such that the bitwise AND of all elements of the subset is greater than the bitwise XOR of all elements of the subset. Example: Input: arr[] = {1, 2, 3, 4, 5}Output: 2Explanation: The subset {2, 3} has the bitwise
6 min read
Count Number of Pairs where Bitwise AND and Bitwise XOR is Equal
Given an integer array arr of size N, the task is to count the number of pairs whose BITWISE AND and BITWISE XOR are equal. Example: Input: N = 3, arr[] = {0,0,1}Output: 1Explanation: There is only one pair arr[0] and arr[1] as 0&0=0 and 0^0=0 Input: N = 4, arr[] = {1, 2, 4, 8}Output: 0Explanati
4 min read
Count pairs having bitwise XOR greater than K from a given array
Given an array arr[]of size N and an integer K, the task is to count the number of pairs from the given array such that the Bitwise XOR of each pair is greater than K. Examples: Input: arr = {1, 2, 3, 5} , K = 2 Output: 4 Explanation: Bitwise XOR of all possible pairs that satisfy the given conditio
15+ min read
Check if any Array pair has bitwise XOR greater than bitwise AND
Given an array arr[] of size N, the task is to find if there exists a pair in the array, such that their bitwise XOR is greater than their bitwise AND i.e. arr[i] â arr[j] > arr[i] & arr[j], (0 ⤠i < j ⤠N-1) where â represents the Bitwise XOR operator and & represents bitwise AND oper
9 min read
Counting pairs with prime bitwise AND in a Singly Linked List
Given a Singly linked list of integers, the task is to count the number of pairs of nodes whose bitwise AND is a prime number. Examples: Input: 4 -> 2 -> 3 -> 1 -> 5 -> 6Output: 3Explanation: The only pair with bitwise AND being a prime number is (2, 3), (2, 6), (3, 6). Input: 10 -
6 min read
Count pairs with bitwise XOR exceeding bitwise AND from a given array
Given an array, arr[] of size N, the task is to count the number of pairs from the given array such that the bitwise AND(&) of each pair is less than its bitwise XOR(^). Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 8Explanation: Pairs that satisfy the given conditions are: (1 & 2) < (
10 min read
Count pairs with Bitwise XOR greater than both the elements of the pair
Given an array arr[] of size N, the task is to count the number of pairs whose Bitwise XOR is greater than both the elements in the pair. Examples: Input: arr[] = {2, 4, 3}Output: 2Explanation: There are only 2 pairs whose Bitwise XOR is greater than both the elements in the pair:1) (2, 4): Bitwise
10 min read