← DiffPush

Pair sum in dll

Standard Bar Linked List · Medium Problems of DLL O(n) · O(1) extra beyond the output

Two Pickers Closing in from Both Ends

A warehouse keeps its sorted roster of bin weights on a doubly linked rail, and dispatch needs every pair of bins that together hit an exact truck payload of `target`. Because the rail is two-way, one picker starts at the lightest end and another at the heaviest end, and they walk toward each other — advancing the light picker when the pair under-loads the truck and retreating the heavy picker when it over-loads. Every combination can be checked without ever comparing a bin against itself.

Input: An array head of n distinct positive node values forming a sorted doubly linked list, and an integer target.

Output: A list of [value1, value2] pairs, each summing to target, in the order the two pointers discover them.

Constraints

Examples

Example 1

Input: {"head":[1,2,4,5,6,8,9],"target":7}
Output: [[1,6],[2,5]]
The closing pointers land on (1,6) first, then (2,5); both pairs sum to 7.

Example 2

Input: {"head":[1,5,6],"target":6}
Output: [[1,5]]
Only (1,5) hits the payload; the pointer walk stops once the pickers cross.

Solve this in your browser →

Also on LeetCode ↗