Given two singly Linked list of integer data. The task is to write a program that efficiently checks if two linked lists are permutations of each other.
Examples:
Input: 1 -> 2 -> 3 -> 4 -> 5
2 -> 1 -> 3 -> 5 -> 4
Output: Yes
Input: 10 -> 20 -> 30 -> 40
20 -> 50 -> 60 -> 70
Output: No
Approach: Do the following for both linked lists:
- Take a temporary node pointing to the head of the linked list.
- Start traversing through the linked list, and keep sum and multiplications of data of nodes.
Note: After having sum and multiplication of both linked list, check if sum and multiplication of both linked lists are equal. If they are equal, it means linked lists are permutations of each other, else not.
Below is the implementation of the above approach:
// C++ program to check if linked lists // are permutations of each other #include <bits/stdc++.h> using namespace std;
// A linked list node struct Node {
int data;
struct Node* next;
}; /*Function to check if two linked lists * are permutations of each other * first : reference to head of first linked list * second : reference to head of second linked list */ bool isPermutation( struct Node* first, struct Node* second)
{ // Variables to keep track of sum and multiplication
int sum1 = 0, sum2 = 0, mul1 = 1, mul2 = 1;
struct Node* temp1 = first;
// Traversing through linked list
// and calculating sum and multiply
while (temp1 != NULL) {
sum1 += temp1->data;
mul1 *= temp1->data;
temp1 = temp1->next;
}
struct Node* temp2 = second;
// Traversing through linked list
// and calculating sum and multiply
while (temp2 != NULL) {
sum2 += temp2->data;
mul2 *= temp2->data;
temp2 = temp2->next;
}
return ((sum1 == sum2) && (mul1 == mul2));
} // Function to add a node at the // beginning of Linked List void push( struct Node** head_ref, int new_data)
{ /* allocate node */
struct Node* new_node = ( struct Node*) malloc ( sizeof ( struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list of the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
} // Driver program to test above function int main()
{ struct Node* first = NULL;
/* First constructed linked list is:
12 -> 35 -> 1 -> 10 -> 34 -> 1 */
push(&first, 1);
push(&first, 34);
push(&first, 10);
push(&first, 1);
push(&first, 35);
push(&first, 12);
struct Node* second = NULL;
/* Second constructed linked list is:
35 -> 1 -> 12 -> 1 -> 10 -> 34 */
push(&second, 35);
push(&second, 1);
push(&second, 12);
push(&second, 1);
push(&second, 10);
push(&second, 34);
if (isPermutation(first, second)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
return 0;
} |
// Java program to check if linked lists // are permutations of each other import java.util.*;
class GFG
{ static class Node
{ int data;
Node next;
}; /*Function to check if two linked lists * are permutations of each other * first : reference to head of first linked list * second : reference to head of second linked list */ static boolean isPermutation(Node first,
Node second)
{ // Variables to keep track of
// sum and multiplication
int sum1 = 0 , sum2 = 0 ,
mul1 = 1 , mul2 = 1 ;
Node temp1 = first;
// Traversing through linked list
// and calculating sum and multiply
while (temp1 != null )
{
sum1 += temp1.data;
mul1 *= temp1.data;
temp1 = temp1.next;
}
Node temp2 = second;
// Traversing through linked list
// and calculating sum and multiply
while (temp2 != null )
{
sum2 += temp2.data;
mul2 *= temp2.data;
temp2 = temp2.next;
}
return ((sum1 == sum2) &&
(mul1 == mul2));
} // Function to add a node at the // beginning of Linked List static Node push(Node head_ref, int new_data)
{ /* allocate node */
Node new_node = new Node();
/* put in the data */
new_node.data = new_data;
/* link the old list of the new node */
new_node.next = head_ref;
/* move the head to point to the new node */
head_ref = new_node;
return head_ref;
} // Driver Code public static void main(String[] args)
{ Node first = null ;
/* First constructed linked list is:
12 . 35 . 1 . 10 . 34 . 1 */
first = push(first, 1 );
first = push(first, 34 );
first = push(first, 10 );
first = push(first, 1 );
first = push(first, 35 );
first = push(first, 12 );
Node second = null ;
/* Second constructed linked list is:
35 . 1 . 12 . 1 . 10 . 34 */
second = push(second, 35 );
second = push(second, 1 );
second = push(second, 12 );
second = push(second, 1 );
second = push(second, 10 );
second = push(second, 34 );
if (isPermutation(first, second))
{
System.out.print( "Yes" );
}
else
{
System.out.print( "No" );
}
} } // This code is contributed by 29AjayKumar |
# Python3 program to check if linked lists # are permutations of each other class Node:
def __init__( self ):
self .data = 0
self . next = None
# Function to check if two linked lists # are permutations of each other # first : reference to head of first linked list # second : reference to head of second linked list def isPermutation(first, second):
# Variables to keep track of
# sum and multiplication
sum1 = 0
sum2 = 0
mul1 = 1
mul2 = 1
temp1 = first
# Traversing through linked list
# and calculating sum and multiply
while (temp1 ! = None ):
sum1 + = temp1.data
mul1 * = temp1.data
temp1 = temp1. next
temp2 = second
# Traversing through linked list
# and calculating sum and multiply
while (temp2 ! = None ):
sum2 + = temp2.data
mul2 * = temp2.data
temp2 = temp2. next
return ((sum1 = = sum2) and (mul1 = = mul2))
# Function to add a node at the # beginning of Linked List def push(head_ref, new_data):
# Allocate node
new_node = Node()
# Put in the data
new_node.data = new_data
# Link the old list of the new node
new_node. next = head_ref
# Move the head to point to the new node
head_ref = new_node
return head_ref
# Driver Code if __name__ = = '__main__' :
first = None
# First constructed linked list is:
# 12 . 35 . 1 . 10 . 34 . 1
first = push(first, 1 )
first = push(first, 34 )
first = push(first, 10 )
first = push(first, 1 )
first = push(first, 35 )
first = push(first, 12 )
second = None
# Second constructed linked list is:
# 35 . 1 . 12 . 1 . 10 . 34
second = push(second, 35 )
second = push(second, 1 )
second = push(second, 12 )
second = push(second, 1 )
second = push(second, 10 )
second = push(second, 34 )
if (isPermutation(first, second)):
print ( "Yes" )
else :
print ( "No" )
# This code is contributed by pratham76 |
// C# program to check if linked lists // are permutations of each other using System;
class GFG
{ public class Node
{ public int data;
public Node next;
}; /*Function to check if two linked lists * are permutations of each other * first : reference to head of first linked list * second : reference to head of second linked list */ static bool isPermutation(Node first,
Node second)
{ // Variables to keep track of
// sum and multiplication
int sum1 = 0, sum2 = 0,
mul1 = 1, mul2 = 1;
Node temp1 = first;
// Traversing through linked list
// and calculating sum and multiply
while (temp1 != null )
{
sum1 += temp1.data;
mul1 *= temp1.data;
temp1 = temp1.next;
}
Node temp2 = second;
// Traversing through linked list
// and calculating sum and multiply
while (temp2 != null )
{
sum2 += temp2.data;
mul2 *= temp2.data;
temp2 = temp2.next;
}
return ((sum1 == sum2) &&
(mul1 == mul2));
} // Function to add a node at the // beginning of Linked List static Node push(Node head_ref, int new_data)
{ /* allocate node */
Node new_node = new Node();
/* put in the data */
new_node.data = new_data;
/* link the old list of the new node */
new_node.next = head_ref;
/* move the head to point to the new node */
head_ref = new_node;
return head_ref;
} // Driver Code public static void Main(String[] args)
{ Node first = null ;
/* First constructed linked list is:
12 . 35 . 1 . 10 . 34 . 1 */
first = push(first, 1);
first = push(first, 34);
first = push(first, 10);
first = push(first, 1);
first = push(first, 35);
first = push(first, 12);
Node second = null ;
/* Second constructed linked list is:
35 . 1 . 12 . 1 . 10 . 34 */
second = push(second, 35);
second = push(second, 1);
second = push(second, 12);
second = push(second, 1);
second = push(second, 10);
second = push(second, 34);
if (isPermutation(first, second))
{
Console.Write( "Yes" );
}
else
{
Console.Write( "No" );
}
} } // This code is contributed by PrinciRaj1992 |
<script> // JavaScript program to check if linked lists
// are permutations of each other
class Node {
constructor() {
this .data = 0;
this .next = null ;
}
}
/*Function to check if two linked lists
* are permutations of each other
* first : reference to head of first linked list
* second : reference to head of second linked list
*/
function isPermutation(first, second) {
// Variables to keep track of
// sum and multiplication
var sum1 = 0,
sum2 = 0,
mul1 = 1,
mul2 = 1;
var temp1 = first;
// Traversing through linked list
// and calculating sum and multiply
while (temp1 != null ) {
sum1 += temp1.data;
mul1 *= temp1.data;
temp1 = temp1.next;
}
var temp2 = second;
// Traversing through linked list
// and calculating sum and multiply
while (temp2 != null ) {
sum2 += temp2.data;
mul2 *= temp2.data;
temp2 = temp2.next;
}
return sum1 == sum2 && mul1 == mul2;
}
// Function to add a node at the
// beginning of Linked List
function push(head_ref, new_data) {
/* allocate node */
var new_node = new Node();
/* put in the data */
new_node.data = new_data;
/* link the old list of the new node */
new_node.next = head_ref;
/* move the head to point to the new node */
head_ref = new_node;
return head_ref;
}
// Driver Code
var first = null ;
/* First constructed linked list is:
12 . 35 . 1 . 10 . 34 . 1 */
first = push(first, 1);
first = push(first, 34);
first = push(first, 10);
first = push(first, 1);
first = push(first, 35);
first = push(first, 12);
var second = null ;
/* Second constructed linked list is:
35 . 1 . 12 . 1 . 10 . 34 */
second = push(second, 35);
second = push(second, 1);
second = push(second, 12);
second = push(second, 1);
second = push(second, 10);
second = push(second, 34);
if (isPermutation(first, second)) {
document.write( "Yes" );
} else {
document.write( "No" );
}
</script> |
Yes
Complexity Analysis:
- Time Complexity: O(N) where N is the size of linked lists
- Auxiliary Space: O(1) because using constant space
Check if two Linked Lists are permutations of each other using Hashing.
Here’s an approach to check if two linked lists are permutations of each other using a hash table:
- Traverse through both linked lists and store the frequency of each element in a hash table. The hash table can be implemented using an array of size equal to the range of the elements in the linked lists.
- Traverse through both linked lists again and compare the frequency of each element in the hash table. If the frequency is not equal, the linked lists are not permutations of each other.
- If the frequency of all elements is equal, the linked lists are permutations of each other.
Below is the implementation of the above approach:
#include <bits/stdc++.h> using namespace std;
// A linked list node struct Node {
int data;
struct Node* next;
}; // Function to check if two linked lists are permutations of each other bool arePermutations( struct Node* first, struct Node* second) {
// Initialize hash table with all elements set to 0
const int range = 1000; // Change range according to the range of elements in linked lists
int hash[range] = {0};
// Traverse through first linked list and update hash table
struct Node* temp = first;
while (temp != NULL) {
hash[temp->data]++;
temp = temp->next;
}
// Traverse through second linked list and compare hash table
temp = second;
while (temp != NULL) {
if (hash[temp->data] == 0) {
return false ;
}
hash[temp->data]--;
temp = temp->next;
}
// Check if all elements have the same frequency in both linked lists
for ( int i = 0; i < range; i++) {
if (hash[i] != 0) {
return false ;
}
}
return true ;
} // Function to add a node at the beginning of Linked List void push( struct Node** head_ref, int new_data) {
/* allocate node */
struct Node* new_node = ( struct Node*) malloc ( sizeof ( struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list of the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
} // Driver program to test above function int main() {
struct Node* first = NULL;
/* First constructed linked list is:
12 -> 35 -> 1 -> 10 -> 34 -> 1 */
push(&first, 1);
push(&first, 34);
push(&first, 10);
push(&first, 1);
push(&first, 35);
push(&first, 12);
struct Node* second = NULL;
/* Second constructed linked list is:
35 -> 1 -> 12 -> 1 -> 10 -> 34 */
push(&second, 35);
push(&second, 1);
push(&second, 12);
push(&second, 1);
push(&second, 10);
push(&second, 34);
if (arePermutations(first, second)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
return 0;
} |
import java.util.HashMap;
class Node {
int data;
Node next;
public Node( int data)
{
this .data = data;
this .next = null ;
}
} public class LinkedListPermutations {
// Function to check if two linked lists are
// permutations of each other
public static boolean arePermutations(Node first,
Node second)
{
// Initialize a HashMap to count the frequency of
// elements
HashMap<Integer, Integer> freqMap = new HashMap<>();
// Traverse through the first linked list and update
// the frequency HashMap
Node temp = first;
while (temp != null ) {
if (freqMap.containsKey(temp.data)) {
freqMap.put(temp.data,
freqMap.get(temp.data) + 1 );
}
else {
freqMap.put(temp.data, 1 );
}
temp = temp.next;
}
// Traverse through the second linked list and
// compare with the frequency HashMap
temp = second;
while (temp != null ) {
if (!freqMap.containsKey(temp.data)
|| freqMap.get(temp.data) == 0 ) {
return false ;
}
freqMap.put(temp.data,
freqMap.get(temp.data) - 1 );
temp = temp.next;
}
// Check if all elements have the same frequency in
// both linked lists
for ( int value : freqMap.values()) {
if (value != 0 ) {
return false ;
}
}
return true ;
}
// Function to add a node at the beginning of the linked
// list
public static Node push(Node head, int newData)
{
Node newNode = new Node(newData);
newNode.next = head;
head = newNode;
return head;
}
public static void main(String[] args)
{
Node first = null ;
// First constructed linked list is: 12 -> 35 -> 1
// -> 10 -> 34 -> 1
first = push(first, 1 );
first = push(first, 34 );
first = push(first, 10 );
first = push(first, 1 );
first = push(first, 35 );
first = push(first, 12 );
Node second = null ;
// Second constructed linked list is: 35 -> 1 -> 12
// -> 1 -> 10 -> 34
second = push(second, 35 );
second = push(second, 1 );
second = push(second, 12 );
second = push(second, 1 );
second = push(second, 10 );
second = push(second, 34 );
if (arePermutations(first, second)) {
System.out.println( "Yes" );
}
else {
System.out.println( "No" );
}
}
} |
class Node:
def __init__( self , data):
self .data = data
self . next = None
# Function to check if two linked lists are permutations of each other def are_permutations(first, second):
# Initialize a dictionary to count the frequency of elements
freq_dict = {}
# Traverse through the first linked list and update the frequency dictionary
temp = first
while temp:
if temp.data in freq_dict:
freq_dict[temp.data] + = 1
else :
freq_dict[temp.data] = 1
temp = temp. next
# Traverse through the second linked list and compare with the frequency dictionary
temp = second
while temp:
if temp.data not in freq_dict or freq_dict[temp.data] = = 0 :
return False
freq_dict[temp.data] - = 1
temp = temp. next
# Check if all elements have the same frequency in both linked lists
return all (value = = 0 for value in freq_dict.values())
# Function to add a node at the beginning of the linked list def push(head_ref, new_data):
new_node = Node(new_data)
new_node. next = head_ref[ 0 ]
head_ref[ 0 ] = new_node
# Driver program to test the above function if __name__ = = "__main__" :
first = None
# First constructed linked list is: 12 -> 35 -> 1 -> 10 -> 34 -> 1
push([first], 1 )
push([first], 34 )
push([first], 10 )
push([first], 1 )
push([first], 35 )
push([first], 12 )
second = None
# Second constructed linked list is: 35 -> 1 -> 12 -> 1 -> 10 -> 34
push([second], 35 )
push([second], 1 )
push([second], 12 )
push([second], 1 )
push([second], 10 )
push([second], 34 )
if are_permutations(first, second):
print ( "Yes" )
else :
print ( "No" )
# This code is contributed by shivamgupta0987654321 |
using System;
using System.Collections.Generic;
// A linked list node class Node
{ public int data;
public Node next;
public Node( int data)
{
this .data = data;
this .next = null ;
}
} class LinkedList
{ // Function to check if two linked lists are permutations of each other
public static bool ArePermutations(Node first, Node second)
{
// Initialize a dictionary to store the frequency of elements
Dictionary< int , int > frequencyMap = new Dictionary< int , int >();
// Traverse through the first linked list and update the frequency map
Node temp = first;
while (temp != null )
{
if (frequencyMap.ContainsKey(temp.data))
frequencyMap[temp.data]++;
else
frequencyMap[temp.data] = 1;
temp = temp.next;
}
// Traverse through the second linked list and compare with the frequency map
temp = second;
while (temp != null )
{
if (!frequencyMap.ContainsKey(temp.data) || frequencyMap[temp.data] == 0)
return false ;
frequencyMap[temp.data]--;
temp = temp.next;
}
// Check if all elements have a frequency of 0 in the frequency map
foreach ( int value in frequencyMap.Values)
{
if (value != 0)
return false ;
}
return true ;
}
// Function to add a node at the beginning of the linked list
public static Node Push(Node head, int newData)
{
Node newNode = new Node(newData);
newNode.next = head;
return newNode;
}
// Driver program to test the above function
public static void Main()
{
Node first = null ;
/* First constructed linked list is:
12 -> 35 -> 1 -> 10 -> 34 -> 1 */
first = Push(first, 1);
first = Push(first, 34);
first = Push(first, 10);
first = Push(first, 1);
first = Push(first, 35);
first = Push(first, 12);
Node second = null ;
/* Second constructed linked list is:
35 -> 1 -> 12 -> 1 -> 10 -> 34 */
second = Push(second, 35);
second = Push(second, 1);
second = Push(second, 12);
second = Push(second, 1);
second = Push(second, 10);
second = Push(second, 34);
if (ArePermutations(first, second))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
} |
// A linked list node class Node { constructor(data) {
this .data = data;
this .next = null ;
}
} function GFG(first, second) {
const range = 1000;
const hash = Array.from({ length: range }, () => 0);
// Traverse through first linked list and
// update hash table
let temp = first;
while (temp !== null ) {
hash[temp.data]++;
temp = temp.next;
}
// Traverse through second linked list and
// compare hash table
temp = second;
while (temp !== null ) {
if (hash[temp.data] === 0) {
return false ;
}
hash[temp.data]--;
temp = temp.next;
}
// Check if all elements have the same frequency in
// both linked lists
for (let i = 0; i < range; i++) {
if (hash[i] !== 0) {
return false ;
}
}
return true ;
} // Function to add a node at the // beginning of Linked List function push(headRef, new_data) {
const new_node = new Node(new_data);
new_node.next = headRef;
headRef = new_node;
return headRef;
} let first = null ;
// First constructed linked list first = push(first, 1);
first = push(first, 34);
first = push(first, 10);
first = push(first, 1);
first = push(first, 35);
first = push(first, 12);
let second = null ;
second = push(second, 35);
second = push(second, 1);
second = push(second, 12);
second = push(second, 1);
second = push(second, 10);
second = push(second, 34);
if (GFG(first, second)) {
console.log( "Yes" );
} else {
console.log( "No" );
}
|
Yes
Complexity Analysis:
- Time Complexity: O(N) where N is the size of linked lists
- Auxiliary Space: O(1) because using constant space