Problem statement

https://binarysearch.com/problems/Replace-Linked-List-on-Index/

Solution

Equal to Leetcode 1669. Merge In Between Linked Lists, but with some border cases.

Complexity

It is O(m + n) for time and O(1) for additional space.

Code

class Solution:
    def solve(self, a, b, lo, hi):
        start, temp, tempb = a, a, b

        for ind in range(hi + 1):
            if ind == lo - 1: start = temp
            temp = temp.next

        while tempb.next: tempb = tempb.next

        start.next, tempb.next = b, temp
        return a if lo else a.next