Two nodes in a Linked list whose product is equal to the target value
Given a head of a singly linked list and a target value. The task is to find whether there exist any two nodes in the linked list whose product is equal to the target value.
Examples:
Input: Linked-List = 2->5->3->4->6, Target = 12
Output: TrueInput: Linked-List = 1->4->3->7->2, Target = 5
Output: False
Approach: This can be solved with the following idea:
Using the Set data structure, check if the target is divided by a value in the linked list that is present or not. If present return true, otherwise return false.
Steps involved in the implementation of code:
- Declare a set seen.
- Iterate in a linked list:
- If target/ Curvalue is present in the set, return true.
- Otherwise, store the CurValue in the set.
- If no value is found after iterating return false.
Below is the implementation of the code:
C++
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Related Articles:
Given a head of a singly linked list and a target value. The task is to find whether there exist any two nodes in the linked list whose product is equal to the target value.
Examples:
Input: Linked-List = 2->5->3->4->6, Target = 12
Output: TrueInput: Linked-List = 1->4->3->7->2, Target = 5
Output: False
Approach: This can be solved with the following idea:
Using the Set data structure, check if the target is divided by a value in the linked list that is present or not. If present return true, otherwise return false.
Steps involved in the implementation of code:
- Declare a set seen.
- Iterate in a linked list:
- If target/ Curvalue is present in the set, return true.
- Otherwise, store the CurValue in the set.
- If no value is found after iterating return false.
Below is the implementation of the code:
C++
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Related Articles: