Find Pair Sum in Sorted Doubly Linked List

Last Updated : 11 Aug, 2026

Given a sorted doubly linked list containing distinct positive integers and an integer target, find all pairs of nodes whose values add up to target.

Examples:

Input: target = 7

1

Output: [[1, 6], [2, 5]]
Explanation: There are two pairs (1, 6) and (2,5) with sum 7.

Input: target = 6

2

Output: [[1, 5]]
Explanation: There is one pairs (1, 5) with sum 6.

Try It Yourself
redirect icon

[Naive Approach] Check Every Pair - O(n ^ 2) Time and O(1) Space

The idea is to check every possible pair of nodes in the doubly linked list. For each node, traverse all the nodes after it and compare their sum with the target. If the sum equals the target, store the pair. After checking all pairs, return the result.

Working of Approach:

  • Start from the first node.
  • For every node, traverse all remaining nodes.
  • Compare the sum of every pair with the target.
  • Store every matching pair in the answer.
C++
#include <bits/stdc++.h>
using namespace std;

class Node
{
  public:
    int data;
    Node *next, *prev;

    Node(int val)
    {
        data = val;
        next = prev = nullptr;
    }
};

// Function to find all pairs with given sum
vector<vector<int>> givenSumPairs(Node *head, int target)
{

    vector<vector<int>> res;

    // Check every possible pair
    for (Node *first = head; first != nullptr; first = first->next)
    {

        for (Node *second = first->next; second != nullptr; second = second->next)
        {

            // Pair found
            if (first->data + second->data == target)
                res.push_back({first->data, second->data});
        }
    }

    return res;
}

// Insert node at end
Node *insert(Node *head, int val)
{

    Node *newNode = new Node(val);

    if (!head)
        return newNode;

    Node *curr = head;

    while (curr->next)
        curr = curr->next;

    curr->next = newNode;
    newNode->prev = curr;

    return head;
}

int main()
{

    vector<int> arr = {1, 2, 4, 5, 6, 8, 9};

    Node *head = nullptr;

    for (int x : arr)
        head = insert(head, x);

    int target = 7;

    vector<vector<int>> ans = givenSumPairs(head, target);

    cout << "[";

    for (int i = 0; i < ans.size(); i++)
    {
        cout << "[" << ans[i][0] << ", " << ans[i][1] << "]";
        if (i + 1 != ans.size())
            cout << ", ";
    }

    cout << "]";

    return 0;
}
Java
import java.util.ArrayList;

class Node {
    public int data;
    public Node next, prev;

    public Node(int val)
    {
        data = val;
        next = prev = null;
    }
}

public class GFG {
    // Function to find all pairs with given sum
    public static ArrayList<ArrayList<Integer> >
    givenSumPairs(Node head, int target)
    {
        ArrayList<ArrayList<Integer> > res
            = new ArrayList<>();

        // Check every possible pair
        for (Node first = head; first != null;
             first = first.next) {
            for (Node second = first.next; second != null;
                 second = second.next) {
                // Pair found
                if (first.data + second.data == target) {
                    ArrayList<Integer> pair
                        = new ArrayList<>();
                    pair.add(first.data);
                    pair.add(second.data);
                    res.add(pair);
                }
            }
        }
        return res;
    }

    // Insert node at end
    public static Node insert(Node head, int val)
    {
        Node newNode = new Node(val);
        if (head == null)
            return newNode;
        Node curr = head;
        while (curr.next != null)
            curr = curr.next;
        curr.next = newNode;
        newNode.prev = curr;
        return head;
    }

    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 4, 5, 6, 8, 9 };
        Node head = null;
        for (int x : arr)
            head = insert(head, x);

        int target = 7;

        ArrayList<ArrayList<Integer> > ans
            = givenSumPairs(head, target);

        System.out.print("[");
        for (int i = 0; i < ans.size(); i++) {
            System.out.print("[" + ans.get(i).get(0) + ", "
                             + ans.get(i).get(1) + "]");
            if (i + 1 != ans.size())
                System.out.print(", ");
        }
        System.out.print("]");
    }
}
Python
class Node:
    def __init__(self, val):
        self.data = val
        self.next = self.prev = None

# Function to find all pairs with given sum


def givenSumPairs(head, target):
    res = []

    # Check every possible pair
    first = head
    while first is not None:
        second = first.next
        while second is not None:
            # Pair found
            if first.data + second.data == target:
                res.append([first.data, second.data])
            second = second.next
        first = first.next

    return res

# Insert node at end


def insert(head, val):
    newNode = Node(val)
    if head is None:
        return newNode
    curr = head
    while curr.next is not None:
        curr = curr.next
    curr.next = newNode
    newNode.prev = curr
    return head


if __name__ == '__main__':
    arr = [1, 2, 4, 5, 6, 8, 9]
    head = None
    for x in arr:
        head = insert(head, x)
    target = 7
    ans = givenSumPairs(head, target)
    print('[', end='')
    for i in range(len(ans)):
        print('[' + str(ans[i][0]) + ',' + str(ans[i][1]) + ']')
        if i + 1 != len(ans):
            print(', ', end='')
    print(']')
C#
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node next, prev;

    public Node(int val)
    {
        data = val;
        next = prev = null;
    }
}

class GFG {
    // Function to find all pairs with given sum
    static List<List<int> > givenSumPairs(Node head,
                                          int target)
    {
        List<List<int> > res = new List<List<int> >();

        // Check every possible pair
        for (Node first = head; first != null;
             first = first.next) {
            for (Node second = first.next; second != null;
                 second = second.next) {
                // Pair found
                if (first.data + second.data == target) {
                    res.Add(new List<int>{ first.data,
                                           second.data });
                }
            }
        }
        return res;
    }

    // Insert node at end
    static Node insert(Node head, int val)
    {
        Node newNode = new Node(val);
        if (head == null)
            return newNode;
        Node curr = head;
        while (curr.next != null)
            curr = curr.next;
        curr.next = newNode;
        newNode.prev = curr;
        return head;
    }

    static void Main(string[] args)
    {
        int[] arr = { 1, 2, 4, 5, 6, 8, 9 };
        Node head = null;
        foreach(int x in arr) head = insert(head, x);
        int target = 7;
        List<List<int> > ans = givenSumPairs(head, target);
        Console.Write('[');
        for (int i = 0; i < ans.Count; i++) {
            Console.Write('[' + ans[i][0] + ", " + ans[i][1]
                          + ']');
            if (i + 1 != ans.Count)
                Console.Write(", ");
        }
        Console.Write(']');
    }
}
JavaScript
class Node {
    constructor(val)
    {
        this.data = val;
        this.next = this.prev = null;
    }
}

// Function to find all pairs with given sum
function givenSumPairs(head, target)
{
    let res = [];

    // Check every possible pair
    let first = head;
    while (first !== null) {
        let second = first.next;
        while (second !== null) {
            // Pair found
            if (first.data + second.data === target) {
                res.push([ first.data, second.data ]);
            }
            second = second.next;
        }
        first = first.next;
    }

    return res;
}

// Insert node at end
function insert(head, val)
{
    let newNode = new Node(val);
    if (!head)
        return newNode;
    let curr = head;
    while (curr.next !== null)
        curr = curr.next;
    curr.next = newNode;
    newNode.prev = curr;
    return head;
}

// Driver Code
let arr = [ 1, 2, 4, 5, 6, 8, 9 ];
let head = null;
for (let x of arr)
    head = insert(head, x);
let target = 7;
let ans = givenSumPairs(head, target);
console.log("[");
for (let i = 0; i < ans.length; i++) {
    console.log("[" + ans[i][0] + ", " + ans[i][1] + "]");
    if (i + 1 !== ans.length)
        console.log(", ");
}
console.log("]");

Output
[[1, 6], [2, 5]]

[Better Approach] Using Hashing - O(n log n) Time and O(n) Space

The idea is to traverse the doubly linked list once while storing the visited node values in a hash set. For each node, check whether its required complement (target - current value) is already present in the hash set. If it is, store the pair; otherwise, insert the current value into the hash set and continue.

Working of Approach:

  • Traverse the linked list from left to right.
  • Maintain a hash set of visited node values.
  • Check whether the required complement already exists.
  • Store every matching pair in the result.
C++
#include <bits/stdc++.h>
using namespace std;

class Node
{
  public:
    int data;
    Node *next, *prev;

    Node(int val)
    {
        data = val;
        next = prev = nullptr;
    }
};

// Function to find all pairs with given sum
vector<vector<int>> givenSumPairs(Node *head, int target)
{

    unordered_set<int> st;
    vector<vector<int>> res;

    // Traverse the linked list
    while (head)
    {

        int need = target - head->data;

        // Pair found
        if (st.count(need))
            res.push_back({need, head->data});

        // Insert current value into hash set
        st.insert(head->data);

        head = head->next;
    }

    // Sort pairs according to first element
    sort(res.begin(), res.end());

    return res;
}

// Insert node at end
Node *insert(Node *head, int val)
{

    Node *newNode = new Node(val);

    if (!head)
        return newNode;

    Node *curr = head;

    while (curr->next)
        curr = curr->next;

    curr->next = newNode;
    newNode->prev = curr;

    return head;
}

int main()
{

    vector<int> arr = {1, 2, 4, 5, 6, 8, 9};

    Node *head = nullptr;

    for (int x : arr)
        head = insert(head, x);

    int target = 7;

    vector<vector<int>> ans = givenSumPairs(head, target);

    cout << "[";

    for (int i = 0; i < ans.size(); i++)
    {
        cout << "[" << ans[i][0] << ", " << ans[i][1] << "]";
        if (i + 1 != ans.size())
            cout << ", ";
    }

    cout << "]";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

class Node {
    public int data;
    public Node next, prev;

    public Node(int val)
    {
        data = val;
        next = prev = null;
    }
}

public class GFG {
    // Function to find all pairs with given sum
    public static ArrayList<ArrayList<Integer> >
    givenSumPairs(Node head, int target)
    {
        HashSet<Integer> st = new HashSet<>();
        ArrayList<ArrayList<Integer> > res
            = new ArrayList<>();

        // Traverse the linked list
        while (head != null) {

            int need = target - head.data;

            // Pair found
            if (st.contains(need)) {
                ArrayList<Integer> pair = new ArrayList<>();
                pair.add(need);
                pair.add(head.data);
                res.add(pair);
            }

            // Insert current value into hash set
            st.add(head.data);

            head = head.next;
        }

        // Sort pairs according to first element
        Collections.sort(
            res,
            (a, b) -> Integer.compare(a.get(0), b.get(0)));

        return res;
    }

    // Insert node at end
    public static Node insert(Node head, int val)
    {
        Node newNode = new Node(val);

        if (head == null)
            return newNode;

        Node curr = head;

        while (curr.next != null)
            curr = curr.next;

        curr.next = newNode;
        newNode.prev = curr;

        return head;
    }

    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 4, 5, 6, 8, 9 };

        Node head = null;

        for (int x : arr)
            head = insert(head, x);

        int target = 7;

        ArrayList<ArrayList<Integer> > ans
            = givenSumPairs(head, target);

        System.out.print("[");

        for (int i = 0; i < ans.size(); i++) {
            System.out.print("[" + ans.get(i).get(0) + ", "
                             + ans.get(i).get(1) + "]");
            if (i + 1 != ans.size())
                System.out.print(", ");
        }

        System.out.print("]");
    }
}
Python
from typing import List, Tuple


class Node:
    def __init__(self, val):
        self.data = val
        self.next = None
        self.prev = None


# Function to find all pairs with given sum
def givenSumPairs(head, target) -> List[Tuple[int, int]]:
    st = set()
    res = []

    # Traverse the linked list
    while head:
        need = target - head.data

        # Pair found
        if need in st:
            res.append((need, head.data))

        # Insert current value into hash set
        st.add(head.data)

        head = head.next

    # Sort pairs according to first element
    res.sort(key=lambda x: x[0])

    return res


# Insert node at end
def insert(head, val):
    newNode = Node(val)

    if not head:
        return newNode

    curr = head

    while curr.next:
        curr = curr.next

    curr.next = newNode
    newNode.prev = curr

    return head


if __name__ == '__main__':
    arr = [1, 2, 4, 5, 6, 8, 9]

    head = None

    for x in arr:
        head = insert(head, x)

    target = 7

    ans = givenSumPairs(head, target)

    print('[', end='')

    for i in range(len(ans)):
        print(f'[{ans[i][0]}, {ans[i][1]}]', end='')
        if i + 1 != len(ans):
            print(', ', end='')

    print(']')
C#
using System;
using System.Collections.Generic;

public class Node {
    public int data;
    public Node next, prev;

    public Node(int val)
    {
        data = val;
        next = prev = null;
    }
}

public class GFG {
    // Function to find all pairs with given sum
    public List<List<int> > givenSumPairs(Node head,
                                          int target)
    {
        List<List<int> > res = new List<List<int> >();

        if (head == null)
            return res;

        Node left = head;
        Node right = head;

        // Move right to the last node
        while (right.next != null)
            right = right.next;

        // Find pairs
        while (left != right && right.next != left) {
            int sum = left.data + right.data;

            if (sum == target) {
                List<int> pair = new List<int>();
                pair.Add(left.data);
                pair.Add(right.data);
                res.Add(pair);

                left = left.next;
                right = right.prev;
            }
            else if (sum < target) {
                left = left.next;
            }
            else {
                right = right.prev;
            }
        }

        return res;
    }

    // Insert node at end
    public static Node insert(Node head, int val)
    {
        Node newNode = new Node(val);

        if (head == null)
            return newNode;

        Node curr = head;

        while (curr.next != null)
            curr = curr.next;

        curr.next = newNode;
        newNode.prev = curr;

        return head;
    }

    public static void Main()
    {
        int[] arr = { 1, 2, 4, 5, 6, 8, 9 };

        Node head = null;

        foreach(int x in arr) head = insert(head, x);

        int target = 7;

        GFG ob = new GFG();
        List<List<int> > ans
            = ob.givenSumPairs(head, target);

        Console.Write("[");

        for (int i = 0; i < ans.Count; i++) {
            Console.Write("[" + ans[i][0] + ", " + ans[i][1]
                          + "]");
            if (i + 1 != ans.Count)
                Console.Write(", ");
        }

        Console.Write("]");
    }
}
JavaScript
class Node {
    constructor(val)
    {
        this.data = val;
        this.next = null;
        this.prev = null;
    }
}

// Function to find all pairs with given sum
function givenSumPairs(head, target)
{
    let st = new Set();
    let res = [];

    // Traverse the linked list
    while (head) {
        let need = target - head.data;

        // Pair found
        if (st.has(need))
            res.push([ need, head.data ]);

        // Insert current value into hash set
        st.add(head.data);

        head = head.next;
    }

    // Sort pairs according to first element
    res.sort((a, b) => a[0] - b[0]);

    return res;
}

// Insert node at end
function insert(head, val)
{
    let newNode = new Node(val);

    if (!head)
        return newNode;

    let curr = head;

    while (curr.next)
        curr = curr.next;

    curr.next = newNode;
    newNode.prev = curr;

    return head;
}

// Driver Code
let arr = [ 1, 2, 4, 5, 6, 8, 9 ];
let head = null;
for (let x of arr)
    head = insert(head, x);
let target = 7;
let ans = givenSumPairs(head, target);
console.log("[");

for (let i = 0; i < ans.length; i++) {
    console.log(`[${ans[i][0]}, ${ans[i][1]}]`);
    if (i + 1 != ans.length)
        console.log(", ");
}
console.log("]");

Output
[[1, 6], [2, 5]]

[Expected Approach] Using Two Pointer Technique - O(n) Time and O(1) Space

The idea is to use two pointers because the doubly linked list is sorted. Place one pointer at the beginning and the other at the end of the list. Compare their sum with the target and move the appropriate pointer accordingly. Whenever the sum equals the target, store the pair and continue until the pointers meet or cross.

Working of Approach:

  • Place one pointer at the first node and the other at the last node.
  • If the sum equals the target, store the pair and move both pointers inward.
  • If the sum is smaller, move the left pointer forward.
  • Otherwise, move the right pointer backward.

Let us understand with an example:
Input: target = 7

1
  • Initialize two pointers: ptr1 at the first node (1) and ptr2 at the last node (9). Since 1 + 9 = 10 is greater than 7, move ptr2 to 8, then to 6.
  • Now 1 + 6 = 7, which matches the target. Store the pair (1, 6) and move both pointers inward to 2 and 5.
  • Again, 2 + 5 = 7, so store the pair (2, 5) and move the pointers inward to 4 and 4.
  • Both pointers now point to the same node, so the traversal stops as all possible pairs have been checked.
  • The final result is [[1, 6], [2, 5]].
C++
#include <bits/stdc++.h>
using namespace std;

// Structure of Doubly Linked List Node
class Node
{
  public:
    int data;
    Node *next, *prev;

    Node(int val)
    {
        data = val;
        next = prev = nullptr;
    }
};

vector<vector<int>> givenSumPairs(Node *head, int target)
{
    Node *ptr1 = head, *ptr2 = head;

    // Move ptr2 to the end of the linked list
    while (ptr2->next)
    {
        ptr2 = ptr2->next;
    }
    vector<vector<int>> res;

    // Find pairs with the given sum
    while (ptr1 != ptr2 && ptr2->next != ptr1)
    {
        int sum = ptr1->data + ptr2->data;

        if (sum == target)
        {
            res.push_back({ptr1->data, ptr2->data});
            ptr1 = ptr1->next;
            ptr2 = ptr2->prev;
        }
        else if (sum < target)
        {
            ptr1 = ptr1->next;
        }
        else
        {
            ptr2 = ptr2->prev;
        }
    }

    return res;
}

// Insert node at end
Node *insert(Node *head, int val)
{

    Node *newNode = new Node(val);

    if (!head)
        return newNode;

    Node *curr = head;

    while (curr->next)
        curr = curr->next;

    curr->next = newNode;
    newNode->prev = curr;

    return head;
}

int main()
{

    vector<int> arr = {1, 2, 4, 5, 6, 8, 9};

    Node *head = nullptr;

    for (int x : arr)
        head = insert(head, x);

    int target = 7;

    vector<vector<int>> ans = givenSumPairs(head, target);

    cout << "[";

    for (int i = 0; i < ans.size(); i++)
    {
        cout << "[" << ans[i][0] << ", " << ans[i][1] << "]";
        if (i + 1 != ans.size())
            cout << ", ";
    }

    cout << "]";

    return 0;
}
Java
import java.util.ArrayList;

class Node {
    public int data;
    public Node next, prev;

    public Node(int val)
    {
        data = val;
        next = prev = null;
    }
}

public class GFG {

    // Function to find all pairs with given sum
    public static ArrayList<ArrayList<Integer> >
    givenSumPairs(Node head, int target)
    {
        Node ptr1 = head, ptr2 = head;

        // Move ptr2 to the end of the linked list
        while (ptr2.next != null) {
            ptr2 = ptr2.next;
        }

        ArrayList<ArrayList<Integer> > res
            = new ArrayList<>();

        // Find pairs with the given sum
        while (ptr1 != ptr2 && ptr2.next != ptr1) {
            int sum = ptr1.data + ptr2.data;

            if (sum == target) {
                ArrayList<Integer> pair = new ArrayList<>();
                pair.add(ptr1.data);
                pair.add(ptr2.data);
                res.add(pair);

                ptr1 = ptr1.next;
                ptr2 = ptr2.prev;
            }
            else if (sum < target) {
                ptr1 = ptr1.next;
            }
            else {
                ptr2 = ptr2.prev;
            }
        }

        return res;
    }

    // Insert node at end
    public static Node insert(Node head, int val)
    {
        Node newNode = new Node(val);

        if (head == null)
            return newNode;

        Node curr = head;

        while (curr.next != null)
            curr = curr.next;

        curr.next = newNode;
        newNode.prev = curr;

        return head;
    }

    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 4, 5, 6, 8, 9 };

        Node head = null;

        for (int x : arr)
            head = insert(head, x);

        int target = 7;

        ArrayList<ArrayList<Integer> > ans
            = givenSumPairs(head, target);

        System.out.print("[");

        for (int i = 0; i < ans.size(); i++) {
            System.out.print("[" + ans.get(i).get(0) + ", "
                             + ans.get(i).get(1) + "]");
            if (i + 1 != ans.size())
                System.out.print(", ");
        }

        System.out.print("]");
    }
}
Python
class Node:
    def __init__(self, val):
        self.data = val
        self.next = None
        self.prev = None


def givenSumPairs(head, target):
    ptr1 = head
    ptr2 = head

    # Move ptr2 to the end of the linked list
    while ptr2.next:
        ptr2 = ptr2.next

    res = []

    # Find pairs with the given sum
    while ptr1 != ptr2 and ptr2.next != ptr1:
        sum = ptr1.data + ptr2.data

        if sum == target:
            res.append([ptr1.data, ptr2.data])
            ptr1 = ptr1.next
            ptr2 = ptr2.prev
        elif sum < target:
            ptr1 = ptr1.next
        else:
            ptr2 = ptr2.prev

    return res


def insert(head, val):
    newNode = Node(val)

    if not head:
        return newNode

    curr = head

    while curr.next:
        curr = curr.next

    curr.next = newNode
    newNode.prev = curr

    return head


if __name__ == '__main__':
    arr = [1, 2, 4, 5, 6, 8, 9]

    head = None

    for x in arr:
        head = insert(head, x)

    target = 7

    ans = givenSumPairs(head, target)

    print('[', end='')

    for i in range(len(ans)):
        print('[{}, {}]'.format(ans[i][0], ans[i][1]), end='')
        if i + 1 != len(ans):
            print(', ', end='')

    print(']')
C#
using System;
using System.Collections.Generic;

// Structure of Doubly Linked List Node
public class Node {
    public int data;
    public Node next, prev;

    public Node(int val)
    {
        data = val;
        next = prev = null;
    }
}

public class GFG {
    public static List<List<int> > givenSumPairs(Node head,
                                                 int target)
    {
        Node ptr1 = head, ptr2 = head;

        // Move ptr2 to the end of the linked list
        while (ptr2.next != null) {
            ptr2 = ptr2.next;
        }
        List<List<int> > res = new List<List<int> >();

        // Find pairs with the given sum
        while (ptr1 != ptr2 && ptr2.next != ptr1) {
            int sum = ptr1.data + ptr2.data;

            if (sum == target) {
                res.Add(
                    new List<int>{ ptr1.data, ptr2.data });
                ptr1 = ptr1.next;
                ptr2 = ptr2.prev;
            }
            else if (sum < target) {
                ptr1 = ptr1.next;
            }
            else {
                ptr2 = ptr2.prev;
            }
        }

        return res;
    }

    // Insert node at end
    public static Node insert(Node head, int val)
    {
        Node newNode = new Node(val);

        if (head == null)
            return newNode;

        Node curr = head;

        while (curr.next != null)
            curr = curr.next;

        curr.next = newNode;
        newNode.prev = curr;

        return head;
    }

    public static void Main()
    {
        int[] arr = { 1, 2, 4, 5, 6, 8, 9 };

        Node head = null;

        foreach(int x in arr) head = insert(head, x);

        int target = 7;

        List<List<int> > ans = givenSumPairs(head, target);

        Console.Write("[");

        for (int i = 0; i < ans.Count; i++) {
            Console.Write("[" + ans[i][0] + ", " + ans[i][1]
                          + "]");
            if (i + 1 != ans.Count)
                Console.Write(", ");
        }

        Console.Write("]");
    }
}
JavaScript
// Structure of Doubly Linked List Node
class Node {
    constructor(val)
    {
        this.data = val;
        this.next = this.prev = null;
    }
}

function givenSumPairs(head, target)
{
    let ptr1 = head, ptr2 = head;

    // Move ptr2 to the end of the linked list
    while (ptr2.next) {
        ptr2 = ptr2.next;
    }
    let res = [];

    // Find pairs with the given sum
    while (ptr1 !== ptr2 && ptr2.next !== ptr1) {
        let sum = ptr1.data + ptr2.data;

        if (sum === target) {
            res.push([ ptr1.data, ptr2.data ]);
            ptr1 = ptr1.next;
            ptr2 = ptr2.prev;
        }
        else if (sum < target) {
            ptr1 = ptr1.next;
        }
        else {
            ptr2 = ptr2.prev;
        }
    }

    return res;
}

// Insert node at end
function insert(head, val)
{
    let newNode = new Node(val);

    if (!head)
        return newNode;

    let curr = head;

    while (curr.next)
        curr = curr.next;

    curr.next = newNode;
    newNode.prev = curr;

    return head;
}

// Driver Code
let arr = [ 1, 2, 4, 5, 6, 8, 9 ];

let head = null;

for (let x of arr)
    head = insert(head, x);

let target = 7;

let ans = givenSumPairs(head, target);

console.log("[");

for (let i = 0; i < ans.length; i++) {
    console.log("[" + ans[i][0] + "," + ans[i][1] + "]");
    if (i + 1 !== ans.length)
        console.log(", ");
}

console.log("]");

Output
[[1, 6], [2, 5]]
Comment