FastPrepMerge a List In Between Two Positions
Problems/Merge a List In Between Two Positions

Merge a List In Between Two Positions

Walmart logoWalmart● MediumFULLTIMEONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: At a Walmart onsite for a full-time software engineer role, one round was a single linked-list task: take two lists and splice the second one into the first between two given nodes, so the second list starts at one node of the first list and its tail links back to a later node.

The report describes the splice only loosely. Practice choices here: a and b are 0-based positions in list1 and the nodes from a through b are the ones replaced; the node before a links to list2's head and list2's last node links to the node after b; a is at least 1 and b at most list1.length - 2, so list1's head and tail always stay; the function returns the head of the merged list. The signature, limits and examples are ours.

The judged task matches the report at about 80%.

You are given two singly linked lists, list1 and list2, and two positions a and b in list1. Positions are counted from 0 at the head.

Remove the nodes of list1 at positions a through b, both included, and put the whole of list2 in their place: 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.

Function

mergeInBetween(list1: ListNode, a: int, b: int, list2: ListNode) → ListNode

Examples

Example 1

list1 = [4,8,15,16,23,42]a = 2b = 3list2 = [7,7]return = [4,8,7,7,23,42]

Positions 2 and 3 hold 15 and 16. They are removed, and 7 -> 7 goes between 8 (position 1) and 23 (position 4).

Example 2

list1 = [5,6,7]a = 1b = 1list2 = [100]return = [5,100,7]

With a = b = 1 only the middle node 6 is removed and replaced by 100.

Example 3

list1 = [1,2,3,4,5,6,7]a = 1b = 5list2 = [9,8,7,6]return = [1,9,8,7,6,7]

Everything between the first and the last node of list1 is removed. The first node 1 now points to 9, and list2's last node 6 points to the old last node 7.

Constraints

  • 3 <= list1.length <= 1000
  • 1 <= list2.length <= 1000
  • 1 <= a <= b <= list1.length - 2
  • 0 <= Node.val <= 10^9

More Walmart problems

  • Merge Intervals from Start and End ListsONSITE INTERVIEW · Seen Nov 2026
  • Palindrome Check Ignoring SymbolsONSITE INTERVIEW · Seen Nov 2026
  • Largest Team Where Every Pair OverlapsOA · Seen Nov 2026
All Walmart interview questionsSee Walmart hiring insights
Saved
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
        // Write your code here.
    }
}
Checking account…