Kodewick
Start learning →
Inserting and deleting in an array7 / 52

Inserting and deleting in an array

Lesson 7 of 52 · Part 2 · Arrays and linked lists · about 20 minutes

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.

datalen = 4free3791101234567
An array list: the first len slots hold the data, the rest are free for inserts (MAX drawn as 8 here)
Choose one

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?

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.

data (len = 4)3791101234↑i
1for (int i = len; i > pos; i--)2    data[i] = data[i - 1];3data[pos] = x;4len++;

Inserting 5 at index 1: shift back starting from the last element, then fill the gap
Guess the outputA wrong guess is fine

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 it

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}
Should print
3 7 9 5 11
Exercise 1

Write insert

Finish insert: put x at index pos (the checks are already written). Make the program print the line below.

It should print
1 2 4 6 8
exercise1.cpp
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}
Output
Press Run or Ctrl+Enter

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.

data (len = 5)35791101234↑i
1for (int i = pos; i < len - 1; i++)2    data[i] = data[i + 1];3len--;

Deleting the 5 at index 1: the ones after it move forward, starting from the front, then len goes down by 1
main.cpp
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}
Output
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.

Guess the outputA wrong guess is fine

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}
Choose one

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?

Choose one

For an array list with len = 5, which values of pos does insert accept? (Look at the check on its first line.)

How many move on average

In an array list of length n:

operationbest (at the end)worst (at the front)average
insert0 movesn movesn/2 moves
delete0 movesn − 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.

Choose one

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":

a3134353201234567↑i↑k
1int k = 0;2for (int i = 0; i < len; i++)3    if (a[i] != x)4        a[k++] = a[i];5len = k;

Removing every 3: i looks at each one, anything that isn't 3 goes to slot k and k moves on; i is never behind k, so nothing not yet looked at is overwritten
main.cpp
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}
Output
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.

Guess the outputA wrong guess is fine

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}
Choose one

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?

Exercise 2

Remove every negative number

In one pass, remove every number below 0 (moving the kept ones forward), then print the array.

It should print
4 5 8 3
exercise2.cpp
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}
Output
Press Run or Ctrl+Enter

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_back work 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.

main.cpp
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}
Output
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 movecost
v[i]0O(1)
push_back(x) / pop_back()0O(1) (amortised for push_back, next lesson)
insert(v.begin() + i, x)n − iO(n)
erase(v.begin() + i)n − i − 1O(n)
insert(v.begin(), x): at the frontnO(n)
erase(remove(…), v.end()): remove every xeach at most onceO(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).

Guess the outputA wrong guess is fine

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}

Summary

Take-away

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());