Skip to content

What is an Array?

Data Structures·6 min·Python code

Array data structures store elements in one unbroken block of memory, and a numeric index reaches any element. Reading or writing any position costs O(1) time, but inserting or deleting in the middle costs O(n) because later elements must shift.

How an Array Stores Elements in Memory

Picture a row of identical boxes with no gaps, numbered 0, 1, 2 and so on. Every box holds one value, and you reach a value by its box number, the index. That row is an array, and its boxes sit in one unbroken block of memory.

Boxes of the same size sit side by side, so the computer never searches for element i. It computes the location directly with base address + i × element size. That one multiply and add makes arrays feel instant, and no walk through earlier elements is needed.

Why Array Access Is O(1) and Edits Are O(n)

Reading or overwriting arr[i] costs O(1) time no matter how large the array grows, thanks to the address formula. That superpower is why arrays sit underneath almost every other data structure.

Cost appears when you change the array's shape. Insert a value at the front and every existing element slides one slot right, which is O(n) work. Delete from the middle and everything after the gap slides left to close it.

Appending to the end costs O(1) except when a dynamic array resizes.

Fixed size arrays, like C arrays and Java's int[], set their length at creation. Dynamic arrays, like Python lists, JavaScript arrays and C++ vectors, grow by allocating a bigger block and copying the elements over. Copying makes one append O(n), yet over many appends the cost averages out to O(1).

Why Arrays Are the Base of Most DSA Problems

Most larger structures are arrays underneath. Hash tables use an array of buckets, heaps store trees in arrays, strings are arrays of characters and matrices are arrays of arrays. Indices, bounds and shifting carry straight into all of them.

Arrays power techniques that rely on O(1) indexing and a cache friendly layout. Binary search, two pointers, sliding window and prefix sums all live on arrays. Master the array and many interview problems share one foundation.

Test your array skills on CodeStory's array practice problems.

Dynamic Array Code Example in Python

pythonA minimal dynamic array with O(1) indexed access, O(1) amortized append and O(n) middle insert with element shifting.

class DynamicArray:
    def __init__(self):
        self._data = [None]      # fixed size backing block
        self._size = 0           # slots actually used

    def get(self, i):            # O(1), direct index
        if not 0 <= i < self._size:
            raise IndexError(i)
        return self._data[i]

    def append(self, value):     # O(1) amortized
        if self._size == len(self._data):
            self._resize(2 * len(self._data))   # double and copy, O(n)
        self._data[self._size] = value
        self._size += 1

    def insert(self, i, value):  # O(n), shift right to open a gap
        if self._size == len(self._data):
            self._resize(2 * len(self._data))
        for j in range(self._size, i, -1):
            self._data[j] = self._data[j - 1]
        self._data[i] = value
        self._size += 1

    def _resize(self, capacity):
        self._data = self._data[:self._size] + [None] * (capacity - self._size)

Try the array code in CodeStory's browser IDE, free on the platform. Open the CodeStory App

Array Time and Space Complexity

TimeAccess or update by index O(1), search O(n) unsorted or O(log n) sorted with binary search, insert or delete in the middle O(n), append O(1) amortized
SpaceO(n) to store n elements, O(1) extra space for in place operations

Index access and end append are the cheapest operations at O(1). Inserting or deleting costs O(n) in the worst case because elements must shift. Dynamic array appends are O(1) amortized, but the occasional resize that doubles capacity costs O(n).

When to Use an Array

  • You need direct access by position, whether you update or scan elements many times.
  • Your data is a sequence that you mostly append to or iterate over, and you rarely insert or delete in the middle.
  • You want compact, cache friendly storage, because a contiguous layout makes iteration quick in practice and not just on paper.
  • You apply an array technique like binary search, two pointers, sliding window or prefix sums.

Mistakes to Avoid

  • Off by one and out of bounds errors top the list, because valid indices go from 0 to n - 1. Looping while i <= n, or forgetting that the array can be empty, is the classic bug.
  • Inserting or deleting in the middle inside a loop surprises people with its slowness. Every edit costs O(n), so n edits cost O(n^2). Rebuild the array in one pass or choose another structure.
  • Append is O(1) amortized, not always O(1). One append can trigger an O(n) resize, which matters for tight latency or real time code.

Array FAQs

Is an array hard to learn?

No. Arrays are the first data structure most people learn, and the core idea of numbered boxes in a row is plain. Practice goes into avoiding off by one errors and spotting when a single pass beats a nested loop.

What is the time complexity of array operations?

Accessing or updating an element by index is O(1). Searching an unsorted array is O(n), or O(log n) if it is sorted and you use binary search. Inserting or deleting in the middle is O(n) because later elements must shift, while appending to the end is O(1) amortized.

What is the difference between an array and a linked list?

Arrays store elements in one contiguous block, so index access is O(1) but middle inserts and deletes are O(n). Linked lists store elements in separate nodes joined by pointers, so inserting or deleting at a known node is O(1), but reaching the ith element is O(n). Arrays use the cache more efficiently.

When should I use an array instead of a hash table?

Use an array when your data is naturally a sequence indexed by position and you need order or quick scanning. Use a hash table when you look things up by an arbitrary key, like a name or ID, and order does not matter. Many problems use both together.

Why is array access O(1)?

Elements sit side by side, so the computer finds element i with base address + i × element size. No search or walk is needed.

Why is inserting into the middle of an array O(n)?

Later elements must slide one slot to open a gap. Inserting at the front moves all n elements, so the cost grows with the array.

How do I practise arrays on CodeStory?

Open CodeStory's array practice problems, solve them in the browser IDE and take a spoken mock round to explain your answer.

Related Guides

Guides are step one. In a CodeStory batch you build, say your answer out loud in a scored mock round and hear what an interviewer thinks.

Talk to a Mentor

Stuck on Arrays? Get a Free Callback

Tell CodeStory which array problem stalls you, and a mentor maps your next steps.

  1. 1CodeStory finds your starting point, from your first index to interview ready.
  2. 2CodeStory explains online and campus batches, with timings for your mornings or evenings.
  3. 3You decide. No pressure, no payment on the call.

Get a Free Callback

I am a
I want to learn

CodeStory dials your number only for this callback.