Check if a pair with given product exists in Linked list in C++


We have a set of elements. And a product K. The task is to check whether there exist two numbers in the linked list, whose product is same as K. If there are two numbers, then print them, if there are more than two numbers, then print any of them. Suppose the linked list is like this {2, 4, 8, 12, 15}, and k value is 16. then it will return (2, 8)

We will solve this using the hashing technique. Take one hash table, and mark all elements as 0. Now iteratively mark all elements as 1 in hash table, if that is present in the linked list. Now start traversing the linked list, and check whether the given product is divisible by current element or not. If yes, then check if (K/current element) of linked list is present in hash table or not.

Example

#include <unordered_set>
#define MAX 100000
using namespace std;
class Node {
   public:
   int data;
   Node* next;
};
void append(struct Node** start, int key) {
   Node* new_node = new Node;
   new_node->data = key;
   new_node->next = (*start);
   (*start) = new_node;
}
bool isPairPresent(Node* start, int K) {
   unordered_set<int> s;
   Node* p = start;
   while (p != NULL) {
      int current = p->data;
      if ((K % current == 0) && (s.find(K / current) != s.end())) {
         cout << current << " " << K / current;
         return true;
      }
      s.insert(p->data);
      p = p->next;
   }
   return false;
}
int main() {
   Node* start = NULL;
   int arr[] = {2, 4, 8, 12, 15};
   int n = sizeof(arr)/sizeof(arr[0]);
   for(int i = 0; i<n; i++){
      append(&start, arr[i]);
   }
   if (isPairPresent(start, 16) == false)
   cout << "NO PAIR EXIST";
}

Output

2 8

Updated on: 22-Oct-2019

110 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements