oneby7

Linked Lists Doubly linked lists

287. Pairs with a Given Sum in a Doubly Linked List

Medium

You are given head, the first node of a doubly linked list whose values are strictly increasing, and an integer target. Find every pair of nodes whose values add up to target.

Return the pairs as a list. Write each pair as [a, b] with the smaller value first, and order the pairs by a, from smallest to largest. The two values of a pair must come from two different nodes. If no pair adds up to target, return an empty list. Do not change the list.

Strictly increasing means that each value is greater than the one before it, so no value appears twice. Each node has a value, val, and two pointers. next points to the following node, and prev points to the node before it. The head's prev is null, and the last node's next is null. The comment at the top of the starter code shows the node in your language.

The examples write a list as its values from the head on, so head = [4,6,9] is the list 4 ⇄ 6 ⇄ 9.

Example 1

Input: head = [-6, -1, 2, 3, 5, 8, 13], target = 7

Output: [[-6,13],[-1,8],[2,5]]

Explanation: −6 + 13, −1 + 8 and 2 + 5 all make 7. The 3 has no partner, because the list holds no 4. The pairs are ordered by their smaller value: −6, then −1, then 2.

Example 2

Input: head = [-5, 0, 5], target = 10

Output: []

Explanation: 5 + 5 = 10, but only one node holds 5, and a node cannot pair with itself. No other two values add up to 10.

Example 3

Input: head = [-2000000000, -9, 0, 9, 2000000000] target = 0

Output: [[-2000000000,2000000000],[-9,9]]

Check your understanding

Work out the answer for this input before you write any code.

head = [-4, 0, 3, 6, 10], target = 6

Constraints

  • 1 ≤ number of nodes ≤ 105
  • -2·109 ≤ Node.val ≤ 2·109
  • -2·109 ≤ target ≤ 2·109
  • The values are strictly increasing.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.