KatInterview

Splice One Sequence Into Another by Index Range

Arrays & HashingAuto-graded · 22 test cases
EasyAuto-gradedArrays & Hashingarraystwo-pointersimplementation

Last updated

Tests careful list slicing and index boundary handling by replacing a contiguous subrange of one sequence with the full contents of a second sequence.

You have two sequences of integers, base and patch, along with two non-negative integers start and end.

Remove every element at positions start through end (inclusive, zero-indexed) from base, then insert all elements of patch in their original order at the position where those elements were removed. Return the resulting sequence.

Rules

  • Elements are zero-indexed. Positions start, start + 1, ..., end are removed from base.
  • Every element of patch is inserted, in order, exactly where the removed block was. The element at position start - 1 of base (when it exists) is immediately followed by the first element of patch, and the last element of patch is immediately followed by the element at position end + 1 of base (when it exists).
  • patch may be empty ([]); in that case the removed positions are simply deleted and no new elements are added.
  • When start = 0, the result begins with the first element of patch, or with the element at position end + 1 of base if patch is empty.
  • If the removal covers all of base and patch is empty, return [].
  • The result is the unique sequence: prefix of base before start, then all of patch, then the suffix of base after end.

Constraints

  • 1 <= len(base) <= 10^4
  • 0 <= len(patch) <= 10^4
  • 0 <= start <= end < len(base)
  • -10^9 <= val <= 10^9 for every element in both sequences

Examples

Example 1

Input: splice_sequence([5, 8, 2, 7, 4], [11, 12], 1, 3)

Output: [5, 11, 12, 4]

Example 2

Input: splice_sequence([1, 2, 3], [9, 9], 0, 0)

Output: [9, 9, 2, 3]

Example 3

Input: splice_sequence([1, 2, 3, 4], [], 2, 3)

Output: [1, 2]

Hints

Hint 1

Think of the result as three independent pieces joined together: the part of base before the removed range, the entirety of patch, and the part of base after the removed range. How do you express each piece with a slice?

Hint 2

Python list slicing handles boundary cases automatically. What does base[:0] return? What does base[len(base):] return? Convince yourself these are correct for the edge cases where start is 0 or end is the last index.

Hint 3

A single line combining three slices is all you need. There is no iteration required and no special-casing for an empty patch.