Insertion and deletion
Beginner · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Putting an item into the middle of a list, or removing one, forces every item after it to shift over by one place, like kids on a crowded bench. Knowing this explains why some list operations are cheap at the end of a list and costly near the front.
Practical use cases
- Web app: Reordering a playlist or to-do list. A user drags a song to the top of their playlist of 5,000 tracks. If the playlist is a plain array, every song below the old and new positions shifts by one place. That is fine for a few hundred items, but for huge lists developers store a sort number per row or use a linked structure instead.
- Web app: Removing a cart item. A shopper deletes the second item in their cart of 12. The array removes it and the remaining items move up, so the cart displays without a gap. Using array_splice in PHP or splice in JavaScript does exactly this shifting for you.
- System: Text editor typing. When you type a letter in the middle of a long document, a simple editor must slide all the later text over by one place. Real editors use cleverer layouts, such as a gap near the cursor, so typing stays smooth even in a huge file.
The story: The Wedding Photo Squeeze
At cousin Anita's wedding, the photographer lined everyone up in a tight row on the stage. No gaps, no spare chairs. Just as he said "smile!", Uncle Pradeep rushed in. "Put me next to the bride's father!" That was position 1.
Mira watched the chaos. To make room, everyone from position 1 onwards had to move one step to the right. And if they moved from the front, they bumped into each other. The sensible way was for the last person to move first, then the next-last, then the next, until the gap opened at position 1.
Later, a shy cousin left the line from the middle. A hole appeared! The photographer shouted, "Everyone behind, step forward!" This time the person right behind the hole moved first.
Arrays are exactly this photo line. They have no gaps and every item sits at a numbered seat, so inserting or deleting in the middle means shifting the neighbours. Adding at the very end is cheap, but squeezing in near the front is a lot of walking.
How to spot this problem, and where you need it
Adding or removing items near the start or middle of a big list feels slow, or leaves gaps and wrong positions, and you want to understand why and what to do about it.
Signs you need it
- You call array_unshift, array_shift or splice inside a loop over a large array and the page slows noticeably.
- After deleting an item, the keys have gaps, or items appear in the wrong position.
- A feature lets users drag items to reorder them, and the saved order is wrong after several moves.
Where to use it in a project
- Shopping carts, playlists, to-do lists and form builders where users insert, remove and reorder items.
- Queue-like logic such as processing the oldest job first, where removing from the front is repeated many times.
The solution
Remember the cost: inserting or deleting at position p moves every item after p. For small lists, simply use splice and re-index. For long lists with many edits, avoid shifting: remove items at the end only, store an order number per row and update just the changed rows, or switch to a structure designed for edits at the front, such as a queue or a linked list.
Payoff: Before: moving one item shifts thousands of others. After: updating a single order number changes just one row.
Explain it like I am 8
Imagine kids sitting on one long bench with no space. If a new kid wants to sit in the middle, everyone on the right has to scoot over. If one kid leaves, everyone on the right scoots back to close the hole.
How it works, step by step
- Insert at index p: make room by growing the array by one seat at the end.
- Walk from the last index down to
p + 1, copyinga[i] = a[i - 1]. - Write the new value into
a[p]. - Delete at index p: walk from
pforward, copyinga[i] = a[i + 1]. - Drop the last (now duplicate) seat. Adding or removing at the end needs no shifting at all.
The code in four languages
PHP
<?php
// Insert $value at index $p by shifting the tail to the right
function insertAt(array $a, int $p, int $value): array {
$n = count($a);
$a[] = 0; // grow by one seat at the end
for ($i = $n; $i > $p; $i--) {
$a[$i] = $a[$i - 1]; // last person moves first
}
$a[$p] = $value;
return $a;
}
// Delete the item at index $p by shifting the tail to the left
function deleteAt(array $a, int $p): array {
$n = count($a);
for ($i = $p; $i < $n - 1; $i++) {
$a[$i] = $a[$i + 1]; // person behind steps forward
}
array_pop($a); // drop the leftover last seat
return $a;
}
$line = [10, 20, 30, 40];
$line = insertAt($line, 1, 99);
echo implode(', ', $line) . PHP_EOL; // 10, 99, 20, 30, 40
$line = deleteAt($line, 2);
echo implode(', ', $line) . PHP_EOL; // 10, 99, 30, 40JavaScript
// Insert value at index p by shifting the tail to the right
function insertAt(a, p, value) {
const n = a.length;
a.push(0); // grow by one seat at the end
for (let i = n; i > p; i--) {
a[i] = a[i - 1]; // last person moves first
}
a[p] = value;
return a;
}
// Delete the item at index p by shifting the tail to the left
function deleteAt(a, p) {
const n = a.length;
for (let i = p; i < n - 1; i++) {
a[i] = a[i + 1]; // person behind steps forward
}
a.pop(); // drop the leftover last seat
return a;
}
const line = [10, 20, 30, 40];
insertAt(line, 1, 99);
console.log(line.join(', ')); // 10, 99, 20, 30, 40
deleteAt(line, 2);
console.log(line.join(', ')); // 10, 99, 30, 40Java
import java.util.*;
public class Main {
// Insert value at index p by shifting the tail to the right
static int[] insertAt(int[] a, int p, int value) {
int n = a.length;
a = Arrays.copyOf(a, n + 1); // grow by one seat at the end
for (int i = n; i > p; i--) {
a[i] = a[i - 1]; // last person moves first
}
a[p] = value;
return a;
}
// Delete the item at index p by shifting the tail to the left
static int[] deleteAt(int[] a, int p) {
int n = a.length;
for (int i = p; i < n - 1; i++) {
a[i] = a[i + 1]; // person behind steps forward
}
return Arrays.copyOf(a, n - 1); // drop the leftover last seat
}
public static void main(String[] args) {
int[] line = {10, 20, 30, 40};
line = insertAt(line, 1, 99);
System.out.println(Arrays.toString(line)); // [10, 99, 20, 30, 40]
line = deleteAt(line, 2);
System.out.println(Arrays.toString(line)); // [10, 99, 30, 40]
}
}Go
package main
import "fmt"
// insertAt inserts value at index p by shifting the tail to the right.
func insertAt(a []int, p, value int) []int {
n := len(a)
a = append(a, 0) // grow by one seat at the end
for i := n; i > p; i-- {
a[i] = a[i-1] // last person moves first
}
a[p] = value
return a
}
// deleteAt deletes the item at index p by shifting the tail to the left.
func deleteAt(a []int, p int) []int {
n := len(a)
for i := p; i < n-1; i++ {
a[i] = a[i+1] // person behind steps forward
}
return a[:n-1] // drop the leftover last seat
}
func main() {
line := []int{10, 20, 30, 40}
line = insertAt(line, 1, 99)
fmt.Println(line) // [10 99 20 30 40]
line = deleteAt(line, 2)
fmt.Println(line) // [10 99 30 40]
}Time: O(n) in the middle or front, O(1) at the end · Extra space: O(1). The shifting is the cost: the closer to the front you work, the more neighbours must move.
Watch out for
- Shifting forward (left to right) when inserting. Each copy overwrites the next value before it has moved, so the line fills with one repeated value.
- Forgetting to remove or ignore the leftover last seat after a deletion.
- Assuming insertion is always cheap. At the front of a big array it moves every single item.
Quick check
- When inserting in the middle, which person should move first?
- The one at the insert spot
- Anyone
- The last one in the line
- Which is cheapest in an array?
- Add at the end
- Insert at the front
- Delete from the middle
- After deleting from the middle, what do you do with the items behind the hole?
- Leave a gap
- Shift them one step left
- Sort them