Profile

Unblock all features

Sign in to track progress and visualise your code.

ntree.ai
Fundamentals

Arrays and strings

Array

An array is a data structure that stores its elements one after another in one block of memory, and all of them have the same size.

Because of how data is stored, each element can be accessed by its index in constant time. We only need to remember the address of the first element and the size of an element. Then the address of the element at index i is the address of the first element plus i times the size of an element.

RAM
0x1000 0x1004 0x1008 0x100C
other data
7
3
9
4
other data
7
3
9
4
0123

Time complexity

operationtime
read or write by indexO(1)O(1)
insert or delete at an indexO(n)O(n)
search for a valueO(n)O(n)
append at the endO(1)O(1) amortised

Inserting or deleting an element requires shifting every element after it, which is why it takes O(n)O(n) time.

Deleting the last element takes O(1)O(1) time, because nothing has to shift.

Adding an element at the end does not shift anything either, but it is O(1)O(1) amortised, because when the array reaches its capacity, all the elements are moved to a new, larger array.

Most languages provide this as a dynamic array, so it is rarely asked to be implemented in an interview, but you need to understand the time complexity of these operations.

String

A string is stored like an array of characters, next to each other in memory.

The difference is that in most languages, strings are immutable, so every change creates a new string by copying the old one, which takes O(n)O(n) time.

Some languages provide a separate mutable string type. In other languages, the workaround is to convert the string to an array of characters.

Was this lesson helpful?