Write an implementation of the memcpy function that copies n elements from a source position to a destination position within the same array, handling overlapping memory regions the way memmove does.
Given an integer array nums, a destination index dest, a source index src, and a count n, copy n elements starting from index src to the positions starting at index dest. The copy must handle overlapping regions correctly: if the source and destination regions overlap, the original source values must be preserved during the copy.
Return the modified array after the copy operation.
Function Signature
def memcpy(nums: list[int], dest: int, src: int, n: int) -> list[int]:
Rules
-
Modify
nums
in place and return it.
-
After the call,
nums[dest + i]
holds the value that
nums[src + i]
had before the call, for every
0 <= i < n
.
-
Every index outside
dest
to
dest + n - 1
keeps its original value.
Constraints
-
1 <= nums.length <= 10^4
-
0 <= dest, src <= nums.length - 1
-
1 <= n <= nums.length
-
src + n <= nums.length
-
dest + n <= nums.length
-
-10^4 <= nums[i] <= 10^4
Examples
Input: nums = [1,2,3,4,5,6,7,8], dest = 2, src = 0, n = 4
Output: [1,2,1,2,3,4,7,8]
The source region is indices 0 to 3 (values 1, 2, 3, 4) and the destination region is indices 2 to 5, so they overlap. Those four original values land in indices 2 to 5, and indices 0, 1, 6 and 7 are unchanged.
Input: nums = [10,20,30,40,50], dest = 0, src = 2, n = 3
Output: [30,40,50,40,50]
The source values 30, 40, 50 (indices 2 to 4) move to indices 0 to 2. The regions overlap at index 2, and indices 3 and 4 keep 40 and 50.
Input: nums = [1,2,3,4,5], dest = 3, src = 0, n = 2
Output: [1,2,3,1,2]
The source region (indices 0 and 1) and the destination region (indices 3 and 4) do not overlap, so the values 1 and 2 are copied directly into indices 3 and 4.