Intro

When manipulating data in Arrays , by either inserting or removing elements, elements need to shift elements accordingly. In some high-level languages this is abstracted away from the programmer, and is done by compiler/interpreter, while in others, you must shift elements manually.

But, where to start? Where to start iterating along the array from? It depends on where you’re shifting.

Shifting direction

The direction you’re shifting the elements, and the problem’s specs i guess, determines where to start iterating from.

Right Shift

Traverse from the end of the array and move towards the first element, decrementing the index. Why? To avoid overwriting elements before moving them, which will happen if looping from the start; whereas this approach ensures that each slot in the array gets its new value before the original is overwritten.

Left Shift

Traverse from the start of the array and move towards the last element, incrementing the index. Same logic as the Right Shift, just for the opposite case.

Quick Ref

Shift DirectionTraverseLoop IndexSet Ptr/Index To
RightEnd→Startfor(i=n-1; i>0; i--)End of array (n-1)
LeftStart→Endfor(i=0; i<n-1; i++)Start of array (0)

Examples

First time I actually had to think of this was in Comp2510 but forgot about it until I implemented the Vector class by hand in C++.

Right Shift

for (int i = size; i > index; --i) {  
    arr[i] = arr[i - 1];  
}

Left Shift

for (int i = index; i < size - 1; ++i) {  
    arr[i] = arr[i + 1];  
}

Summary

  • Shifting elements toward higher indices: Start from the end.
  • Shifting elements toward lower indices: Start from the beginning. This works in pretty much every language and for any shift size, ensuring data is copied safely without overwrites.

Keep this in mind when you’re going over Lessons Learned from Leetcode and Array Problems.


References