Array and Strings: A gentle refresher

An array is a data structure that contains a group of elements of the same data type. Arrays are commonly used to organize data so that a related set of values can be easily searched and sorted. A single block of memory depending on the number of elements gets assigned to the array. The elements are not dispersed across memory, they are kept near each other and thus make an array a contiguous collection

Arrays are sometimes classified as a homogenous data structure because in certain static languages like Java, the elements must be of the same type.

int array [] = {1,2,3,4,5}

This is not true for certain dynamic languages such as Javascript where we can have something like

const arr = [1, 'string', false]

Attention has to be paid to the number of rows and columns needed to be utilized for the array such that if you do not completely use that space, you will be wasting that memory.

Time complexity

The beauty of arrays is how fast you can access the elements. This is because arrays utilize indices. An index refers to the location where the value is stored in an array. If we know the index of a particular element we can look it up in O(1) time.

Suppose you want to add an element to a particular index then you have to shift the other elements to the right. This makes the time complexity of an insert operation to be O(n).

Search also has a time complexity of O(n) since if we assume we have an array with 100 elements and we want to access the 99th element, we would have to loop through till we get to the element.

Strings

A string allows you to store a sequence of characters. Strings are of variable length since you can increase the length of the string by adding more content.

Differences between arrays and strings

Data Type

  • An array can be created to store, access, or represent multiple elements of the same or different data types. Strings can only hold character data.

Storage

Arrays can be of either fixed length or variable length. Fixed-length arrays are mostly found in static languages while variable-length arrays are found in languages like Python and Javascript.

Here's an example: you need to instantiate an array to store 100 employee numbers. To declare it, you'd need the size along with the variable name when the array is defined: employee_number_array[100]

Strings however are of variable size and memory is allocated for them at runtime.