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++
#include<bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *next;
Node( int x) {
data = x;
}
};
Node *head;
void push( int new_data)
{
Node *new_node = new Node(new_data);
if (head == NULL) {
head = new_node;
return ;
}
new_node->next = head;
head = new_node;
}
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;
}
int main()
{
head = NULL;
push(51);
push(30);
push(46);
push(62);
push(34);
push(17);
cout << PerfectPair();
}
|
Java
import java.util.ArrayList;
import java.util.HashMap;
public class GFG {
static class Node {
int data;
Node next;
Node( int x) { data = x; }
};
static void push( int new_data)
{
Node new_node = new Node(new_data);
if (head == null ) {
head = new_node;
return ;
}
new_node.next = head;
head = new_node;
}
static Node head;
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;
}
public static void main(String[] args)
{
head = null ;
push( 51 );
push( 30 );
push( 46 );
push( 62 );
push( 34 );
push( 17 );
System.out.println(PerfectPair());
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def push( self , new_data):
new_node = Node(new_data)
if self .head = = None :
self .head = new_node
return
new_node. next = self .head
self .head = new_node
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
if __name__ = = "__main__" :
llist = LinkedList()
llist.push( 51 )
llist.push( 30 )
llist.push( 46 )
llist.push( 62 )
llist.push( 34 )
llist.push( 17 )
print (llist.PerfectPair())
|
C#
using System;
public class GFG {
class Node {
public int data;
public Node next;
public Node( int x) { data = x; }
}
static void push( int new_data)
{
Node new_node = new Node(new_data);
if (head == null ) {
head = new_node;
return ;
}
new_node.next = head;
head = new_node;
}
static Node head;
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()
{
head = null ;
push(51);
push(30);
push(46);
push(62);
push(34);
push(17);
Console.WriteLine(PerfectPair());
}
}
|
Javascript
<script>
class Node {
constructor(data) {
this .data = data;
this .next = null ;
}
}
let head;
function push(newData) {
let newNode = new Node(newData);
if (head === null ) {
head = newNode;
return ;
}
newNode.next = head;
head = newNode;
}
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;
}
head = null ;
push(51);
push(30);
push(46);
push(62);
push(34);
push(17);
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++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
Node( int x)
{
data = x;
next = NULL;
}
};
void push( struct Node** head_ref,
int new_data)
{
struct Node* new_node
= new Node(new_data);
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int PerfectPair(Node* head)
{
int ans = 0, size = 0;
unordered_map< int , int > mp;
vector< int > firstSetBit;
while (head != NULL) {
firstSetBit.push_back(
log2(head->data));
size++;
head = head->next;
}
for ( int i = 0; i < size; i++) {
ans += mp[firstSetBit[i]];
mp[firstSetBit[i]]++;
}
return ans;
}
int main()
{
struct Node* head = NULL;
push(&head, 51);
push(&head, 30);
push(&head, 46);
push(&head, 62);
push(&head, 34);
push(&head, 17);
cout << PerfectPair(head);
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.HashMap;
public class GFG {
static class Node {
int data;
Node next;
Node( int x) { data = x; }
};
static void push( int new_data)
{
Node new_node = new Node(new_data);
if (head == null ) {
head = new_node;
return ;
}
new_node.next = head;
head = new_node;
}
static Node head;
static int PerfectPair()
{
int ans = 0 , size = 0 ;
HashMap<Integer, Integer> mp
= new HashMap<Integer, Integer>();
ArrayList<Integer> firstSetBit
= new ArrayList<Integer>();
while (head != null ) {
firstSetBit.add(log2(head.data));
size++;
head = head.next;
}
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;
}
public static int log2( int N)
{
int result = ( int )(Math.log(N) / Math.log( 2 ));
return result;
}
public static void main(String[] args)
{
head = null ;
push( 51 );
push( 30 );
push( 46 );
push( 62 );
push( 34 );
push( 17 );
System.out.println(PerfectPair());
}
}
|
Python3
import math
class GFG:
class Node:
data = 0
next = None
def __init__( self , x):
self .data = x
@staticmethod
def push(new_data):
new_node = GFG.Node(new_data)
if (GFG.head = = None ):
GFG.head = new_node
return
new_node. next = GFG.head
GFG.head = new_node
head = None
@staticmethod
def PerfectPair(K):
ans = 0
size = 0
mp = dict ()
firstSetBit = []
while (GFG.head ! = None ):
firstSetBit.append(GFG.log2(GFG.head.data))
size + = 1
GFG.head = GFG.head. next
i = 0
while (i < size):
try :
val = mp[firstSetBit[i]]
except :
val = 0
ans + = val
mp[firstSetBit[i]] = val + 1
i + = 1
return ans
@staticmethod
def log2(N):
result = int ((math.log(N) / math.log( 2 )))
return result
@staticmethod
def main(args):
K = 4
GFG.head = None
GFG.push( 51 )
GFG.push( 30 )
GFG.push( 46 )
GFG.push( 62 )
GFG.push( 34 )
GFG.push( 17 )
print (GFG.PerfectPair(K))
if __name__ = = "__main__" :
GFG.main([])
|
C#
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; }
};
static void push( int new_data)
{
Node new_node = new Node(new_data);
if (head == null )
{
head = new_node;
return ;
}
new_node.next = head;
head = new_node;
}
static Node head;
static int PerfectPair()
{
int ans = 0, size = 0;
Dictionary< int , int > mp = new Dictionary< int , int >();
ArrayList firstSetBit = new ArrayList();
while (head != null )
{
firstSetBit.Add(log2(head.data));
size++;
head = head.next;
}
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;
}
public static int log2( int N)
{
int result = ( int )(Math.Log(N) / Math.Log(2));
return result;
}
public static void Main()
{
head = null ;
push(51);
push(30);
push(46);
push(62);
push(34);
push(17);
Console.Write(PerfectPair());
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .next = null ;
}
}
class GFG {
static head = null ;
static push(newData) {
let newNode = new Node(newData);
if (!GFG.head) {
GFG.head = newNode;
return ;
}
newNode.next = GFG.head;
GFG.head = newNode;
}
static log2(N) {
return Math.floor(Math.log2(N));
}
static PerfectPair(K) {
let ans = 0;
let size = 0;
const mp = {};
const firstSetBit = [];
let currentNode = GFG.head;
while (currentNode) {
firstSetBit.push(GFG.log2(currentNode.data));
size++;
currentNode = currentNode.next;
}
for (let i = 0; i < size; i++) {
const val = mp[firstSetBit[i]] || 0;
ans += val;
mp[firstSetBit[i]] = val + 1;
}
return ans;
}
static main() {
const K = 4;
GFG.push(51);
GFG.push(30);
GFG.push(46);
GFG.push(62);
GFG.push(34);
GFG.push(17);
console.log(GFG.PerfectPair(K));
}
}
GFG.main();
|
Time Complexity: O(N * log N)
Auxiliary Space: O(N)