Interview questions · Oracle
Replace a Range of Nodes in a Linked List with Another Linked List
Given two singly linked lists and two indices i and j, replace nodes i through j of the first list with every node of the second list and return the new head. It tests careful pointer relinking, head and tail edge cases, and an empty replacement list.
You are given two singly linked lists, list1 and list2, and two indices i and j. Replace the nodes of list1 numbered i through j (inclusive) with the whole of list2, and return the head of the resulting list.
Function Signature
def replace_range(list1: ListNode, list2: Optional[ListNode], i: int, j: int) -> Optional[ListNode]:
Rules
ListNodeis a singly linked list node with an integer fieldvaland a fieldnextthat isNoneat the tail.- Nodes of
list1are numbered from0at the head. Nodesi,i + 1, ...,jare removed. - All nodes of
list2are inserted, in their original order, where the removed nodes were: nodei - 1oflist1(if it exists) is followed by the first node oflist2, and the last node oflist2is followed by nodej + 1oflist1(if it exists). list2may be empty (None); then nodesithroughjare simply deleted.- When
i = 0, the result starts with the first node oflist2, or with nodej + 1oflist1iflist2is empty. - Return the head of the result, or
Noneif the result has no nodes (possible only whenlist2is empty,i = 0andj = n - 1). - You may relink the existing nodes of both lists. The result is checked by its sequence of values from head to tail, so the answer is unique.
- In the examples a linked list is written as the array of its values from head to tail, and
[]stands forNone.
Constraints
1 <= n <= 10^4, wherenis the number of nodes inlist10 <= m <= 10^4, wheremis the number of nodes inlist20 <= i <= j < n-10^9 <= val <= 10^9for every node of both lists
Examples
Example 1
Input: list1 = [5, 8, 2, 7, 4], list2 = [11, 12], i = 1, j = 3
Output: [5, 11, 12, 4]
Nodes 1 through 3 of list1 (values 8, 2 and 7) are replaced by the two nodes of list2.
Example 2
Input: list1 = [1, 2, 3], list2 = [9, 9], i = 0, j = 0
Output: [9, 9, 2, 3]
The head of list1 is replaced, so the result starts with the first node of list2.
Example 3
Input: list1 = [1, 2, 3, 4], list2 = [], i = 2, j = 3
Output: [1, 2]
list2 is empty, so nodes 2 and 3 are deleted and node 1 becomes the tail.
Community answers
Nothing here yet.
Join in on CSWork →