Skip to content

Instantly share code, notes, and snippets.

@timxor
Created November 23, 2025 08:25
Show Gist options
  • Select an option

  • Save timxor/b1ae0cbc4189e35e69099c3da0beb05b to your computer and use it in GitHub Desktop.

Select an option

Save timxor/b1ae0cbc4189e35e69099c3da0beb05b to your computer and use it in GitHub Desktop.
Backward copy processes right-to-left and handles overlapping ranges correctly by reading from the end first, ensuring source data isn't overwritten before being copied.
// Backward Copy (right-to-left)
// REQUIRED when source and destination ranges overlap
// and destination starts before source ends
public static void backwardCopy(int[] arr, int srcStart, int destStart, int length) {
for (int i = length - 1; i >= 0; i--) {
arr[destStart + i] = arr[srcStart + i];
}
}
// Example: Copy with overlapping ranges
// Original: [1, 2, 3, 4, 5]
// Copy indices 0-2 to indices 1-3 (destination overlaps source)
// Forward copy would corrupt: [1, 1, 2, 3, 5] (WRONG - data lost)
// Backward copy preserves: [1, 1, 2, 3, 4] (CORRECT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment