Search⌘ K

Solution Review: Pairs with Sums

Learn to implement a Python method that identifies all pairs of nodes in a doubly linked list whose data values add up to a specified sum. Understand the use of two pointers and nested loops to traverse and check node pairs efficiently.

We'll cover the following...

Here is an overview of our solution to finding a pair of nodes in a doubly linked list that sums up to a specific number.

Implementation

Here is the coding solution in Python for the previous challenge:

Python 3.5
def pairs_with_sum(self, sum_val):
pairs = list()
p = self.head
q = None
while p:
q = p.next
while q:
if p.data + q.data == sum_val:
pairs.append("(" + str(p.data) + "," + str(q.data) + ")")
q = q.next
p = p.next
return pairs

Explanation

On line 2, pairs is initialized to an empty Python list. In the next lines (lines 3-4), p and q are set equal to self.head ...