Arrays are one of the simplest and most widely used data structures in programming.
And more importantly, they're the foundation for many other data structures and algorithms you'll encounter throughout this course. Stacks, queues, heaps, hash tables, sorting, and binary search all build on them.
In this chapter, we'll understand what arrays are, how they work, the most common array operations and their time complexities, and how arrays appear in coding interviews.
An array is a data structure that stores a collection of elements in a specific order.
Think of it as a sequence of numbered slots, where each slot holds a value.
For example, suppose we're tracking the daily active users of an application over the last seven days. We could store these numbers in an array:
Each element represents the number of active users on a particular day. Monday's count is the first element, Tuesday's is the second, and so on.
Instead of managing seven separate variables like mon, tue, wed, and so on, we now have one collection that holds all seven values. And that matters even more as the data grows. If an application tracked a value for thousands or millions of items, separate variables would be impossible to manage.
Because the elements are ordered, we can access each one using its position. This position is called an index.
In most languages, all the elements of an array have the same type: an array of integers, an array of booleans, an array of strings, and so on.
One of the first things to understand about arrays is that indexing usually starts from zero.
Let's say we have an array containing five numbers: 10, 20, 30, 40, and 50.
Notice that even though the array contains five elements, its last index is four.
In general, for an array containing n elements, the valid indices range from 0 to n - 1.
This is important because trying to access an index outside this range can cause an error or undefined behavior, depending on the programming language. In Java, arr[5] on a five-element array throws an ArrayIndexOutOfBoundsException. In C or C++, it's undefined behavior: the program may read whatever happens to be in memory after the array, or crash.
Now let's understand why arrays are so efficient.
In an array, elements are stored next to each other in memory. This is known as contiguous memory allocation.
Suppose we have an array containing five integers. The computer allocates enough memory to store all five elements, one after another.
Each element takes up a fixed amount of space. For example, if each integer occupies four bytes, the five elements require twenty bytes in total.
If the array starts at memory address 1000, the elements sit at these addresses:
Because the elements are stored consecutively, the computer can calculate the exact memory location of any element.
Suppose we want to access the element at index three.
Does the computer need to go through the first three elements to reach it? Not at all. It can jump directly to the element using a simple calculation.
It takes the starting memory address of the array and adds the index multiplied by the size of each element:
For index 3, that's 1000 + 3 × 4 = 1012.
Whether we're accessing the first element, the hundredth, or even the millionth, the calculation takes essentially the same amount of work: one multiplication and one addition.
This is why accessing an array element by index takes O(1), or constant time. And it's one of the biggest advantages arrays have over many other data structures.
Now let's see how to create and work with arrays in code.
I'll use Java for the explanation, but the concepts apply to most programming languages, and the code below is shown in several of them.
Suppose we want to store five test scores. We can create an array like this:
Now we have an array containing five integers.
To access the first score, we use scores[0]. For the third score, we use scores[2]. And to access the last score, we use index four.
Pretty simple, right?
Now let's look at some common operations we can perform on arrays.
The first is updating an element.
Suppose we accidentally entered the third test score as 76, but the correct score is 80.
How do we fix it? We simply assign the new value at index two:
That's it. The old value is replaced with 80.
And just like accessing an element, updating an element at a known index takes O(1), or constant time. There's no need to shift or rearrange any other elements. We simply access the correct position and overwrite the value.
This makes arrays especially efficient when we need to frequently read or update elements by their indices.
Next, suppose we want to calculate the average test score.
This time, we can't just access a single element. We need to go through the entire array and add up all the scores. This process is called traversal.
We start at index zero, read the first value, then move to the next. And we keep going until we've visited every element.
In code, we typically use a loop to do this. For example, we can loop from index zero to the last index of the array:
The running sum goes 85, 177, 257, 356, 444, so the average is 444 / 5 = 88.8.
Since we visit each element exactly once, the time complexity is O(n), where n is the number of elements.
Array traversal is something you'll use all the time in coding interviews.
Now, let's look at another common operation: searching.
Suppose we want to check whether a score of 99 exists in our array.
How would we find it?
If the array isn't sorted, the simplest approach is to check each element one by one.
We start with the first element and compare it with 99. If it doesn't match, we move to the next. We keep doing this until we find the score or reach the end of the array.
This approach is called linear search.
On [85, 92, 80, 99, 88], the search compares 85, 92, and 80, then finds 99 at index 3 after four comparisons.
In the worst case, we might have to examine every element, so the time complexity is O(n).
Notice the difference from access: reading an element at a known index takes O(1), but finding an element by its value can take O(n).
However, if the array is sorted, we can often search much faster using Binary Search, which takes O(log n) time. It checks the middle element and throws away the half that can't contain the target. On the sorted array [80, 85, 88, 92, 99], it finds 99 in three checks. We'll explore it in a separate lesson.
Now let's look at another important operation: insertion.
Suppose we have an array containing 10, 20, 30, 40, and 50, with room for one more element. And we want to insert 25 between 20 and 30.
How do we do that? We can't just replace 30 with 25, because we'd lose the original value.
So we need to make some room.
Assuming the array has enough capacity, we first shift 30, 40, and 50 one position to the right. We start from the end, moving 50 first, then 40, then 30, so no value is overwritten before it has moved.
This creates an empty position where we can insert 25:
Pretty simple. But here's the catch.
Depending on where we insert the new element, we might have to shift a lot of existing elements.
In the worst case, inserting at the beginning means shifting every element one position to the right. That's why insertion at an arbitrary position takes O(n) time in the worst case.
Inserting at the end is the cheap case: if there's free capacity, the new element just goes into the next slot, with nothing to shift.
Now, what about deletion?
The idea is quite similar, but in reverse.
Suppose we want to remove 30 from our array. Once we remove it, we're left with a gap.
To fill that gap while maintaining the order, we shift all the elements after 30 one position to the left. Here we move 40 first, then 50:
Again, the amount of work depends on which element we're removing.
Deleting the last element doesn't require any shifting. But deleting the first element may require shifting almost every other element.
So deletion also takes O(n) time in the worst case when we need to preserve the order.
One thing to keep in mind is that fixed-size arrays don't actually shrink when we delete an element. The allocated memory stays the same. We simply keep track of how many elements are currently in use. That's why the array above still has a capacity of 6 even though only 5 elements are in use.
Traditional arrays have a fixed size. Once an array is created, we can't change its capacity.
For example, if we create an array that can hold five integers, we can't simply expand it to hold ten. The memory right after the array may already belong to something else.
So what if we don't know how many elements we'll need?
That's where dynamic arrays come in.
A dynamic array works much like a regular array, giving us fast access to elements by index, but it can also grow automatically as we add more elements.
In Java, a common example is ArrayList. Python's built-in lists work in a similar way. C++ has std::vector, C# has List<T>, Go has slices, Rust has Vec, and JavaScript arrays grow on their own.
Dynamic arrays are especially useful in real-world applications, where we often don't know in advance how much data we'll need to store.
Now let's understand how dynamic arrays grow behind the scenes.
A dynamic array keeps two numbers: its size, the number of elements currently stored, and its capacity, the number of slots it has allocated.
Suppose we create a dynamic array with an initial capacity of four elements. We add four values, and now the array is full:
What happens when we try to add a fifth element?
Since there's no space left, the dynamic array needs to grow.
To do this, it allocates a new, larger block of memory. For example, it might double its capacity from four to eight.
It then copies all four existing elements into the new memory and adds the fifth element:
The old memory can then be released.
Now, copying all those elements takes O(n) time.
So does that mean adding elements to a dynamic array is expensive?
Not really. Here's why.
The array doesn't need to resize every time we add an element. Most of the time, there's already enough space, so we simply place the new element at the end. The next three appends above fill slots 5, 6, and 7 without any copying.
This brings us to an important concept called amortized time complexity.
Most append operations take O(1) time. Occasionally, when the array is full, an append triggers resizing and takes O(n) time.
But if we double the capacity whenever the array fills up, resizing becomes less frequent as the array grows.
And when we spread the total cost of all these resizing operations across many insertions, the cost per append stays constant.
Here's a concrete example. Start with a capacity of 1 and append 16 elements, doubling whenever the array is full:
That's 16 writes plus 1 + 2 + 4 + 8 = 15 copies, 31 operations in total, or fewer than 2 per append. The same holds no matter how many elements we add, because each resize copies about as many elements as were appended since the previous one.
That's what we mean when we say appending to a dynamic array takes amortized O(1) time.
This makes dynamic arrays a great choice when we need to keep adding elements over time.
However, inserting somewhere in the middle still requires shifting existing elements, so it takes O(n) time in the worst case.
Now that we understand how arrays work, let's look at where they shine and where they fall short.
The biggest advantage of arrays is fast access. If we know the index, we can read or update an element in constant time.
Arrays are also memory-efficient and often perform very well because their elements are stored next to each other in memory.
This improves something called cache locality, making it faster for the CPU to process elements sequentially. When the CPU loads one element from memory, it loads the neighboring elements along with it, so the next few reads are already in the cache.
But arrays also have some limitations.
So arrays are a great choice when we need fast access by index or want to process elements sequentially.
But they're less convenient when we frequently need to insert or delete elements at different positions.
Here is a quick recap of time complexities of the array operations we've covered.
As for space, storing n elements in an array takes O(n) space. And if we're simply traversing the array without creating another data structure, we typically need only O(1) extra space.
Understanding these trade-offs will help you recognize when an array is the right data structure for a problem, and when you might need something else.
Arrays are one of the most common data structures you'll encounter in coding interviews.
But interviewers usually won't ask you to simply create an array or access an element.
Instead, they'll give you a problem involving a collection of values and ask you to find an efficient solution. For example:
Now, the real challenge isn't working with the array itself. It's figuring out the right approach to solve the problem efficiently.
That's where techniques like Two Pointers, Sliding Window, Prefix Sums, and Binary Search come in. You'll encounter these patterns again and again in coding interviews.
And they all build on the fundamentals we've covered in this chapter. Each of them gets its own lesson later in this course.
That's why having a strong understanding of arrays is so important before moving on to more advanced problems.
Before we wrap up, let's quickly go over a few common mistakes to watch out for.
1. Off-by-one errors. Remember, if an array has n elements, its last valid index is n - 1, not n. A loop written as i <= arr.length reads one position past the end of the array.
2. Confusing an index with a value. Another common mistake is confusing an element's index with the value stored at that index. In arr = [10, 20, 30, 40, 50], arr[2] is 30. Using 30 as if it were an index, as in arr[arr[2]], reaches far outside the array.
3. Modifying an array while iterating through it. You also need to be careful when modifying an array while iterating through it. If you don't manage the indices correctly, you might accidentally skip elements or process the same element multiple times. For example, if you remove the element at index i and then move on to i + 1, the element that just shifted into position i never gets checked. Iterating backwards, or only advancing i when nothing was removed, avoids this.
4. Mixing up capacity and size. And finally, remember that an array's capacity and the number of elements it currently holds aren't always the same. A dynamic array with capacity 8 and size 5 has only five valid elements; the last three slots are allocated but empty. This distinction becomes especially important when working with dynamic arrays.
And that brings us to the end of our introduction to arrays.
To really get comfortable with arrays, I'd recommend practicing a few basic operations yourself:
These might seem like simple exercises, but they'll help you build a strong foundation for solving more challenging array problems.
10 quizzes