×

Count pairs from two linked lists whose sum is equal to a given value

Count pairs from two linked lists whose sum is equal to a given value

In this problem, we have given two linked lists of size n1 and n2 with distinct elements and a value k. We need to count all pairs from both lists whose sum is equal to the value k.

Note: The pair has an element from each linked list.

Examples:

Input: list1 = 3 ->1 ->5 ->7

 list2 = 8 ->2 ->5 ->3k = 10

Output: 2

The pairs are:

(5, 5) and (7, 3)

Input:list1 = 4 ->3 ->5 ->7 ->11 ->2 ->1

list2 = 2 ->3 ->4 ->5 ->6 ->8->12k = 9        

Output: 5

Method 1:(Naive Approach)

In this method, we will use two loops to pick elements from both the linked lists and check whether the sum of the pair is equal to x or not.

C implementation to count pairs from both linked lists whose sum is equal to a given value

 #include<stdio.h>
 #include<stdlib.h>
 struct node
 {
 int info;
 struct node * next;
 };
 struct node * start1 = NULL, * start2 = NULL, * res = NULL;
 intlen = 0, n;
 // For inserting the elements in the linked list
 void add(int item, struct node ** temp)
 {
 struct node * t, * p;
 t = (struct node * )malloc( sizeof( struct node ));
 if(*temp == NULL)
 {
 * temp = t;
 (* temp) ->info = item;
 (* temp) ->next = NULL;
 return;
 }
 else
 {
 struct node * p = * temp;
 while(p -> next != NULL)
 {
 p = p -> next;
 }
 p -> next = t;
 p = p -> next;
 p -> info = item;
 p -> next = NULL;
 }
 }
 // For counting pairs from two linked lists whose sum is equal to a given value
 intcountPairs(struct node * head1, struct node *  head2, int k)
 {
 int count = 0;
 struct node * t1, * t2;
     // traverse the 1st linked list
 for (t1 = head1; t1 != NULL; t1 = t1 -> next)
 for (t2 = head2; t2 != NULL; t2 = t2 -> next)
 if ((t1 -> info + t2 -> info) == k)
 count++;
 return count;
 }
 // To display the elements of the linked list
 void traverse(struct node * t)
 {
 if(t == NULL)
 {
             printf(" Linked list is empty\n");
 }
 while(t -> next != NULL)
 {
                         printf("%d -> ", t -> info);
                         t = t -> next;
 }
                         printf("%d\n", t -> info);
 }
 // Driver Function
 int main()
 {
 int k;
 printf("Enter the value of k:");
 scanf("%d", &k);
 // Add element into the linked1
 add(4, &start1);
 add(3, &start1);
 add(5, &start1);
 add(6, &start1);
 add(9, &start1);
 add(8, &start1);
 // Add element into the linked2
 add(1, &start2);
 add(4, &start2);
 add(3, &start2);
 add(7, &start2);
 add(9, &start2);
 add(2, &start2);
 int res = countPairs(start1, start2, k);
 printf("count is:%d",res);
 return 0;
 } 

Output:

Count pairs from two linked lists whose sum is equal to a given value

Time Complexity: The time complexity of the above method is O(n1*n2).

Space Complexity:The space complexity of the above method is O(1) which is constant.

Method 2:(By Sorting)

This method will sort the 1st linked list in ascending order and the 2nd linked list in descending order. Then, we will traverse both the linked lists from left to right to count the pairs.

Note:Here, we assume that we have sorted linked lists.

 #include<stdio.h>
 #include<stdlib.h>
 struct node
 {
 int info;
 struct node * next;
 };
 struct node * start1 = NULL, * start2 = NULL, * res = NULL;
 intlen = 0, n;
 // For inserting the elements in the linked list
 void add(int item, struct node ** temp)
 {
 struct node * t, * p;
 t = (struct node * )malloc( sizeof( struct node ));
 if(*temp == NULL)
 {
 * temp = t;
 (* temp) ->info = item;
 (* temp) ->next = NULL;
 return;
 }
 else
 {
 struct node * p = * temp;
 while(p -> next != NULL)
 {
 p = p -> next;
 }
 p -> next = t;
 p = p -> next;
 p -> info = item;
 p -> next = NULL;
 }
 }
 // For counting pairs from two linked lists whose sum is equal to a given value
 intcountPairs(struct node * head1, struct node *  head2, int k)
 {
 int count = 0;
 while (head1 != NULL && head2 != NULL)
     {
 if ((head1->data + head2->data) == x)
         {
             head1 = head1->next;
             head2 = head2->next;
 count++;   
         }   
 else if ((head1->data + head2->data)> x)
             head2 = head2->next;
 else
             head1 = head1 ->next;
     }       
 return count;
 }
 // To display the elements of the linked list
 void traverse(struct node * t)
 {
 if(t == NULL)
 {
             printf(" Linked list is empty\n");
 }
 while(t -> next != NULL)
 {
                         printf("%d -> ", t -> info);
                         t = t -> next;
 }
                         printf("%d\n", t -> info);
 }
 // Driver Function
 int main()
 {
 int k;
 printf("Enter the value of k:");
 scanf("%d", &k);
 // Add element into the linked1
 add(3, &start1);
 add(4, &start1);
 add(5, &start1);
 add(6, &start1);
 add(8, &start1);
 add(9, &start1);
 // Add element into the linked2
 add(9, &start2);
 add(7, &start2);
 add(4, &start2);
 add(3, &start2);
 add(2, &start2);
 add(1, &start2);
 int res = countPairs(start1, start2, k);
 printf("count is:%d",res);
 return 0;
 } 

Output:

Count pairs from two linked lists whose sum is equal to a given value

Time Complexity: The time complexity of above method is O(n1 *  logn1) +.O(n2 *  logn2).

Space Complexity:The space complexity of the above method is O(1) which is constant.


Related Topics

Cocktail Sort

C Program executes cocktail sort. Combo sort is a somewhat straightforward arranging calculation initially planned by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered by Stephen Lacey and Richard Box...

5 minutes read.

Compare Balanced Binary Tree and Complete Binary Tree

Complete and balanced binary trees are important and general topics in the concept – Tree data structure. Before discussing the complete and balanced binary tree, we need to have an...

8 minutes read.

Union and Intersection of two Linked Lists

Union and Intersection of two Linked Lists This article explains how we can do the union and intersection of two linked lists. In this problem, we have given two linked lists...

3 minutes read.

Stack Data Structure

The stack is a non-primitive and linear data structure. It works on the principle of LIFO (Last In First Out). That is, the element that is added to the end...

3 minutes read.

What is the difference between Tree and Graph

We usually use a diverse range of data structure to store our data and information. To store them in a more sequential manner and to access them easily, we use...

4 minutes read.

Box Stacking Problem

Stacking of boxes depending on their base You have been given n different boxes. These boxes will have different heights, widths, and depths. You have to stack all these boxes in...

4 minutes read.

Advantages and Disadvantages of Linked List

Advantages of Linked List The linked list is a dynamic data structure.You can also decrease and increase the linked list at run-time. That is, you can allocate and deallocate memory at...

3 minutes read.

Operations of B Tree in C++ Language

B tree tends to be a self-aligning and balancing tree that helps us organise our data and document safely. We know that every data or information in the B tree...

9 minutes read.

Linear vs Binary Search: Data Structure

Difference Between Linear and Binary Search What is Linear Search? A linear search also referred as a sequential search. It is a way to find an element within a list and it...

3 minutes read.

Finding Rank in a Binary Search Tree

Implementation // writing a C++ program to find out the rank and element in the program.  #include <bits/stdc++.h> using namespace std; struct __nod { int record; __nod *Lft, *Rt; int LftSize; }; __nod* new__nod(int record) { __nod *temp = new __nod; temp->record...

6 minutes read.

Does Overloading Work with Inheritance

This is a question that occasionally comes to many programmers. Who are curious to know more now has a complete explanation and a solution through this tutorial! Inheritance: The functions of...

3 minutes read.

Data Structure Prefix to Postfix Conversion

Prefix to Postfix Conversion Prefix: As the name suggests if the operator placed before the operands called the prefix expression.  The form of prefix expression is (operator, operand1, operand2). Example:  *+EF-GH (Infix:...

2 minutes read.

Binary Tree to Doubly Linked List

Binary Tree to Doubly Linked List This article will explain how to convert the given binary tree into a Doubly Linked List. The left and right pointers in tree nodes are...

2 minutes read.

Stack vs Array

Difference between Array and Stack In this article, we are going to discuss the major differences between the stack and array data structures: Array – In the data structure, the array is...

3 minutes read.

Bucket Sort

Bucket Sort: In the sorting algorithm, we create buckets and put elements into them. We can apply some sorting algorithm (insertion sort) to sort the elements in each bucket. Finally,...

4 minutes read.

Top view of binary tree

We know that a binary tree is a kind of tree that helps us organize our tree and that it is a kind of non-linear info structure that at least...

4 minutes read.

Application of Stack in Data Structures

In this article, we will discuss all the different applications of stack. What is meant by stack? The stack is a non-primitive linear data structure in which the insertion of the new...

11 minutes read.

What is a Threaded Binary Tree?

When we consider those binary trees that are interlinked with each other, we do come across the fact that the fields present in there do consist of NULL values that...

3 minutes read.

What is a Sparse Matrix in Data Structure?

Definition A matrix in which a few non-zero elements are present is called a Sparse matrix. In a Sparse matrix, almost all the matrices are filled with zero (0). A matrix...

5 minutes read.

Singly Linked list

Singly Linked list A singly linked list is a kind of linked list which is unidirectional. If we talk about singly linked list, then we can say it can be traversed...

3 minutes read.