Merge In Between Linked Lists

MediumLinked Listlinked list

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given the heads of two singly linked lists, list1 and list2, along with two integers a and b that are 0-indexed positions in list1. Delete every node of list1 whose position is between a and b inclusive, and splice the entire list2 into the gap: the node at position a - 1 must point to the head of list2, and the last node of list2 must point to the node that was at position b + 1. Return the head of the resulting list. It is guaranteed that a >= 1 and b <= list1.length - 2, so the head and tail of list1 always survive. Aim for O(n + m) time and O(1) extra space.

Examples

Input: list1 = [4,8,15,16,23,42], a = 2, b = 3, list2 = [7,7,7]
Output: [4,8,7,7,7,23,42]
The nodes at positions 2 and 3 (values 15 and 16) are cut out. Node 8 now links to the first 7, and the last 7 links to 23.
Input: list1 = [1,2,3,4,5,6,7], a = 1, b = 5, list2 = [90,91]
Output: [1,90,91,7]
Positions 1 through 5 (values 2..6) are removed and replaced by the two nodes of `list2`.

Constraints

  • 3 <= list1.length <= 10^4
  • 1 <= a <= b < list1.length - 1
  • 1 <= list2.length <= 10^4
  • -10^6 <= Node.val <= 10^6

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.