Inserting and deleting in an array
Inserting or deleting in an array shifts every later element: inserting shifts back from the end, deleting shifts forward from the front, half move on average, O(n); on a vector, insert and erase do the same.
Getting an element of an array by index is O(1), but to insert one or delete one in the middle, the elements after it have to move one by one. This lesson writes an "array list" in C++ and looks closely at the moving: which way, starting from which end, and how many on average. A vector's insert and erase do exactly the same.
An array list: an array plus a length
A fixed array's size is set. To insert and delete, also keep "how many slots are in use", and write inserting and deleting as member functions:
1const int MAX = 10;2 3struct SqList {4 int data[MAX]; // room for MAX5 int len = 0; // how many are in it now6 7 bool insert(int pos, int x); // insert x at index pos8 bool erase(int pos); // delete the element at index pos9};
The data is in data[0] to data[len - 1]; the slots after that are empty, kept for inserting. Inside a member function, data and len mean this list's own.
An array list holds 3 7 9 11, and len is 4. You add one more value at the end. Which slot does it go in?
data[0] to data[len - 1], so the next free slot is data[len], here data[4]. Once it is in, len becomes 5.Inserting: shift back, starting from the end
To insert 5 at index 1: move index 1 and everything after it back one slot, which frees index 1, put 5 there, and add 1 to len.
i1for (int i = len; i > pos; i--)2 data[i] = data[i - 1];3data[pos] = x;4len++;
What does it print if the shifting starts from the front?
1#include <iostream>2using namespace std;3 4int main() {5 int a[5] = {3, 7, 9, 11};6 int len = 4, pos = 1;7 for (int i = pos; i < len; i++) // shifting from the front8 a[i + 1] = a[i];9 a[pos] = 5;10 for (int i = 0; i <= len; i++)11 cout << a[i] << " ";12 cout << "\n";13 return 0;14}
Change only pos in the green box so 5 lands between 9 and 11 and the program prints 3 7 9 5 11.
1#include <iostream>2using namespace std;3 4int main() {5 int a[6] = {3, 7, 9, 11};6 int len = 4, pos = , x = 5;7 for (int i = len; i > pos; i--)8 a[i] = a[i - 1];9 a[pos] = x;10 len++;11 for (int i = 0; i < len; i++)12 cout << a[i] << " ";13 cout << "\n";14 return 0;15}
3 7 9 5 11
pos = 3. This time only 11 has to move back, so 1 moved.Write insert
✓Finish insert: put x at index pos (the checks are already written). Make the program print the line below.
1 2 4 6 8
1#include <iostream>2using namespace std;3 4const int MAX = 10;5 6struct SqList {7 int data[MAX];8 int len = 0;9 10 bool insert(int pos, int x) {11 if (pos < 0 || pos > len || len == MAX) return false;12 // shift back from the end, put x in, add 1 to len13 return true;14 }15};16 17int main() {18 SqList L;19 L.data[0] = 2;20 L.data[1] = 4;21 L.data[2] = 8;22 L.len = 3;23 L.insert(2, 6);24 L.insert(0, 1);25 for (int i = 0; i < L.len; i++)26 cout << L.data[i] << " ";27 cout << "\n";28 return 0;29}
Deleting: shift forward, starting from the front
Deleting the element at index pos is the other way round: the elements after it each move forward one slot, covering it, and len goes down by 1. This time the shifting goes from the front.
i1for (int i = pos; i < len - 1; i++)2 data[i] = data[i + 1];3len--;
1#include <iostream>2using namespace std;3 4const int MAX = 10;5 6struct SqList {7 int data[MAX];8 int len = 0;9 10 bool insert(int pos, int x) {11 if (pos < 0 || pos > len || len == MAX) return false;12 for (int i = len; i > pos; i--)13 data[i] = data[i - 1];14 data[pos] = x;15 len++;16 return true;17 }18 19 bool erase(int pos) {20 if (pos < 0 || pos >= len) return false;21 for (int i = pos; i < len - 1; i++)22 data[i] = data[i + 1];23 len--;24 return true;25 }26 27 void show() const {28 for (int i = 0; i < len; i++)29 cout << data[i] << " ";30 cout << "(len = " << len << ")\n";31 }32};33 34int main() {35 SqList L;36 int init[] = {3, 7, 9, 11};37 for (int x : init)38 L.insert(L.len, x); // at the end: nothing has to move39 L.show();40 L.insert(1, 5);41 L.show();42 L.erase(3);43 L.show();44 cout << L.erase(8) << "\n"; // a bad position: returns false, prints 045 return 0;46}
3 7 9 11 (len = 4) 3 5 7 9 11 (len = 5) 3 5 7 11 (len = 4) 0
Note the checks at the top of both functions: a bad position, or no room left, returns false. The array won't check for you, so in an array list these lines can't be left out.
What if a delete shifted from the back to the front? What would this print?
1#include <iostream>2using namespace std;3 4int main() {5 int a[5] = {3, 5, 7, 9, 11};6 int len = 5, pos = 1;7 for (int i = len - 2; i >= pos; i--)8 a[i] = a[i + 1];9 len--;10 for (int i = 0; i < len; i++)11 cout << a[i] << " ";12 cout << "\n";13 return 0;14}
The array list is [5 8 1 6 3] (len = 5). After deleting the element at index 1, what does it look like, and how many elements moved?
For an array list with len = 5, which values of pos does insert accept? (Look at the check on its first line.)
pos = len = 5, and nothing has to move. So insert takes pos from 0 to len, while erase can only remove an element that exists, so its pos runs from 0 to len − 1. Exams love this difference.How many move on average
In an array list of length n:
| operation | best (at the end) | worst (at the front) | average |
|---|---|---|---|
| insert | 0 moves | n moves | n/2 moves |
| delete | 0 moves | n − 1 moves | (n − 1)/2 moves |
So inserting and deleting in an array list are O(n), and getting by position is O(1).
Often asked: textbooks count positions from 1, so "insert at position i" is index i − 1 of the array. Average moves: n/2 to insert, (n − 1)/2 to delete.
In an array list of length n, how many elements move when you insert at position i (counting from 1, as textbooks do)?
Removing every x in one pass
To remove every element equal to x, you could call erase each time you find one, but each call shifts, and the worst case is O(n²). Better: one pass, with k remembering "which slot the next kept element goes in":
i↑k1int k = 0;2for (int i = 0; i < len; i++)3 if (a[i] != x)4 a[k++] = a[i];5len = k;
1#include <iostream>2using namespace std;3 4int main() {5 int a[8] = {3, 1, 3, 4, 3, 5, 3, 2};6 int len = 8, x = 3;7 int k = 0; // how many are kept, and where the next one goes8 for (int i = 0; i < len; i++)9 if (a[i] != x)10 a[k++] = a[i]; // not x: keep it, move it forward11 len = k;12 for (int i = 0; i < len; i++)13 cout << a[i] << " ";14 cout << "\n";15 return 0;16}
1 4 5 2
One pass, each element moved at most once: O(n) time, O(1) extra space. This is a very common exam question.
After the removal, print all 8 slots (not just the first len). What do you see?
1#include <iostream>2using namespace std;3 4int main() {5 int a[8] = {3, 1, 3, 4, 3, 5, 3, 2};6 int len = 8, x = 3, k = 0;7 for (int i = 0; i < len; i++)8 if (a[i] != x)9 a[k++] = a[i];10 len = k;11 for (int i = 0; i < 8; i++)12 cout << a[i] << " ";13 cout << "\n";14 return 0;15}
Remove every 2 from [2 7 2 2 5 7] (the same single pass, keeping values at a[k]). Afterwards, what is k, and what are the first k slots?
Remove every negative number
✓In one pass, remove every number below 0 (moving the kept ones forward), then print the array.
4 5 8 3
1#include <iostream>2using namespace std;3 4int main() {5 int a[7] = {4, -1, 5, -9, -2, 8, 3};6 int len = 7;7 int k = 0;8 // one pass: keep the ones that aren't below 0, put them in a[k]9 len = k;10 for (int i = 0; i < len; i++)11 cout << a[i] << " ";12 cout << "\n";13 return 0;14}
With the STL
A vector is an array list that can grow (the next lesson shows how). Its insert and erase do exactly the moving from the earlier levels of this lesson:
v.insert(v.begin() + i, x): moves index i and everything after it back one slot, then puts x in.v.erase(v.begin() + i): moves everything after index i forward one slot.push_back/pop_backwork at the end, so nothing moves.
Positions are given as iterators: v.begin() points at the first element, v.begin() + i at index i. To remove every x, the standard library also does "one pass, move forward": remove(v.begin(), v.end(), x) is the k loop from the "delete every x" level, moving the kept ones to the front and returning the new end; then erase cuts off the rest.
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6void show(const vector<int>& v) {7 for (int x : v)8 cout << x << " ";9 cout << "(size = " << v.size() << ")\n";10}11 12int main() {13 vector<int> v = {3, 7, 9, 11};14 v.insert(v.begin() + 1, 5); // insert 5 at index 1: 7 9 11 move back15 show(v);16 v.erase(v.begin() + 3); // delete the 9 at index 3: 11 moves forward17 show(v);18 v.push_back(20); // at the end: nothing moves19 show(v);20 21 vector<int> w = {3, 1, 3, 4, 3, 5, 3, 2};22 w.erase(remove(w.begin(), w.end(), 3), w.end()); // remove every 323 show(w);24 return 0;25}
3 5 7 9 11 (size = 5) 3 5 7 11 (size = 4) 3 5 7 11 20 (size = 5) 1 4 5 2 (size = 4)
| operation (n elements) | how many move | cost |
|---|---|---|
v[i] | 0 | O(1) |
push_back(x) / pop_back() | 0 | O(1) (amortised for push_back, next lesson) |
insert(v.begin() + i, x) | n − i | O(n) |
erase(v.begin() + i) | n − i − 1 | O(n) |
insert(v.begin(), x): at the front | n | O(n) |
erase(remove(…), v.end()): remove every x | each at most once | O(n) |
After an insert or erase, iterators, pointers and references past that position can't be used any more: the elements have moved.
In interviews: "Why is inserting into the middle of a vector slow": the elements after it move one by one, O(n). Calling erase one at a time in a loop is O(n²); to remove every element that matches, use erase-remove (or C++20's erase_if), O(n). For many inserts at the front, use a deque (O(1) at both ends).
remove and erase delete every 4 in two steps. What does it print?
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7 vector<int> v = {4, 1, 4, 2, 4};8 auto it = remove(v.begin(), v.end(), 4);9 cout << (it - v.begin()) << " " << v.size() << " ";10 v.erase(it, v.end());11 cout << v.size() << "\n";12 return 0;13}
remove only does "one pass, move the keepers forward": it moves the 1 and the 2 to the front and returns the new end (index 2), without changing size, which is still 5. erase(it, v.end()) is what really drops the last 3, so size becomes 2. Writing remove without erase is a common mistake.Summary
Array list: insert shifts back from the end, delete shifts forward from the front
- getting is O(1); inserting and deleting move half on average, O(n)
- check the position and the room first: the array won't
- removing every x: one pass, move the kept ones forward, O(n)
- vector's insert / erase move elements too: O(n); push_back / pop_back at the end don't
1for (int i = len; i > pos; i--) data[i] = data[i - 1]; // insert2for (int i = pos; i < len - 1; i++) data[i] = data[i + 1]; // delete3for (int i = 0; i < len; i++) if (a[i] != x) a[k++] = a[i];4v.erase(remove(v.begin(), v.end(), x), v.end());