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.
Time complexity
| operation | time |
|---|---|
| read or write by index | |
| insert or delete at an index | |
| search for a value | |
| append at the end | amortised |
Inserting or deleting an element requires shifting every element after it, which is why it takes time.
Deleting the last element takes time, because nothing has to shift.
Adding an element at the end does not shift anything either, but it is 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 time.
Some languages provide a separate mutable string type. In other languages, the workaround is to convert the string to an array of characters.