700607. Count Pairs whose sum is equal to X
Count Pairs whose sum is equal to X
Slug: count-pairs-whose-sum-is-equal-to-x Difficulty: Easy Id: 700607 Topic Tags: Linked List, Data Structures Company Tags: Amazon
Summary
Given a sorted linked list and an integer X, the problem requires you to find the number of pairs in the linked list whose sum is equal to X. This problem involves basic concepts of data structures and algorithms.
Detailed Explanation
To solve this problem, we can iterate through the linked list and for each node, try to find a pair that sums up to X by iterating backwards from the current node. If such a pair is found, increment the count. We also keep track of the previous node to avoid duplicate pairs.
Here's the step-by-step breakdown:
- Initialize a counter variable
countto 0. - Iterate through the linked list. For each node:
- Initialize two pointers,
prevandcurr, to the current node and the previous node respectively. - While
curris not null:- If the sum of
curr's value andprev's value equalsX, increment thecount. - Move
prevone step forward. - Decrement
curruntil it becomes null or the sum exceedsX.
- If the sum of
- Initialize two pointers,
- Return the
count.
Time complexity: O(n), where n is the number of nodes in the linked list. Space complexity: O(1).
Optimized Solutions
Java
java
public int countPairs(SinglyLinkedListNode node, int X) {
int count = 0;
SinglyLinkedListNode prev = null;
for (SinglyLinkedListNode curr = node; curr != null; curr = curr.next) {
while (prev != null && curr.value + prev.value > X) {
prev = prev.next;
}
if (prev != null && curr.value + prev.value == X) {
count++;
}
prev = curr;
}
return count;
}
Python
Not available