Count triplets in a sorted DLL whose sum is equal to given value “X”

Pattern: Doubly and circular lists

medium

Fix the smallest value of the triplet, one node at a time. For the rest of the list, run the two-pointer pair search for x minus that value. O(n²) in total.

The problem

Given the head of a sorted doubly linked list of different whole numbers and a value x, count the triplets of nodes whose values add up to x. For example, 1 ⇄ 2 ⇄ 4 ⇄ 5 ⇄ 6 ⇄ 8 ⇄ 9 with x = 17 gives 2: (2, 6, 9) and (4, 5, 8).

The link above is a GeeksforGeeks article. The function name countTriplets is this guide's own. In this guide's code the node type is DNode.

Think first

  • If you fix one value, what is left to find?
  • Which earlier problem finds pairs with a given sum in a sorted DLL?
  • How do you avoid counting the same triplet twice?

Hints

    Brute force, and why it fails

    Try every three nodes: O(n³). A hash set of values for each pair is O(n²) time with O(n) memory. Fixing one value and using two pointers is O(n²) time and O(1) memory.

    The key insight

    A triplet search is a pair search inside a loop. Sorting (here, given) is what makes the inner pair search linear.

    Dry run

    10first
    21left
    42 
    53 
    64 
    85 
    96right

    The list is 1 ⇄ 2 ⇄ 4 ⇄ 5 ⇄ 6 ⇄ 8 ⇄ 9 and x = 17. Fix first = 1, so a pair from 2 to 9 must sum to 16.

    Step 1 of 4

    The plan

    tail = last node, count = 0
    for each node first:
        left = first.next, right = tail
        while left and right and left != right and right.next != left:
            s = first.val + left.val + right.val
            if s == x: count = count + 1; left = left.next; right = right.prev
            else if s < x: left = left.next
            else: right = right.prev
    return count
    

    Complexity

    Time
    O(n²)
    Space
    O(1)

    n choices of first, each with a linear pair search.

    Edge cases

    • Fewer than three nodes: 0.
    • No triplet: 0.
    • Negative values work the same way.
    I've built my logic, show the code

    Java

    class Solution {
        public int countTriplets(DNode head, int x) {
            if (head == null) return 0;
            DNode tail = head;
            while (tail.next != null) tail = tail.next;
            int count = 0;
            for (DNode first = head; first != null; first = first.next) {   // fix the smallest value
                DNode left = first.next, right = tail;   // two-pointer search for the other two
                while (left != null && right != null && left != right && right.next != left) {
                    int sum = first.val + left.val + right.val;
                    if (sum == x) { count++; left = left.next; right = right.prev; }
                    else if (sum < x) left = left.next;
                    else right = right.prev;
                }
            }
            return count;
        }
    }

    C++

    class Solution {
    public:
        int countTriplets(DNode* head, int x) {
            if (head == NULL) return 0;
            DNode* tail = head;
            while (tail->next != NULL) tail = tail->next;
            int count = 0;
            for (DNode* first = head; first != NULL; first = first->next) {   // fix the smallest value
                DNode *left = first->next, *right = tail;   // two-pointer search for the other two
                while (left != NULL && right != NULL && left != right && right->next != left) {
                    int sum = first->val + left->val + right->val;
                    if (sum == x) { count++; left = left->next; right = right->prev; }
                    else if (sum < x) left = left->next;
                    else right = right->prev;
                }
            }
            return count;
        }
    };

    Python

    from lib import DNode
    
    class Solution:
        def countTriplets(self, head: DNode, x: int) -> int:
            if head is None:
                return 0
            tail = head
            while tail.next is not None:
                tail = tail.next
            count, first = 0, head
            while first is not None:                # fix the smallest value
                left, right = first.next, tail      # two-pointer search for the other two
                while left is not None and right is not None and left is not right and right.next is not left:
                    total = first.val + left.val + right.val
                    if total == x:
                        count += 1
                        left, right = left.next, right.prev
                    elif total < x:
                        left = left.next
                    else:
                        right = right.prev
                first = first.next
            return count

    Common mistakes

    • Starting left at the head, which reuses first or counts triplets in several orders.
    • Missing the crossing stop condition.
    • Counting a triplet and moving only one pointer.

    Similar problems