Arrays in Data Structures: Complete Guide with Types, Operations and Examples

Introduction

Arrays are one of the most important and commonly used data structures in computer science. They provide a simple way to store multiple values of the same data type under one variable name.

For example, if you want to store the marks of five students, you could create five separate variables. However, managing many individual variables becomes difficult. An array solves this problem by storing multiple values in an indexed collection.

Arrays are used in searching, sorting, mathematical calculations, matrices, and many other programming problems. Learning arrays is an important first step before moving to advanced data structures and algorithms.

What Is an Array?

An array is a data structure that stores a collection of elements, generally of the same data type, in an ordered sequence.

Each element can be accessed using an index. In many popular programming languages, array indexing starts at zero.

For example:

cpp
int marks[5] = {85, 90, 78, 92, 88};

Here:
- The array name is marks.
- The array contains five elements.
- The first element is at index 0.
- The last element is at index 4.

You can access an individual element using its index:

cpp
cout << marks[0];

The output is 85.

How Does an Array Work?

In a typical array implementation, elements are stored in contiguous memory locations. This makes it possible to calculate the address of an element directly from its index.

For a zero-indexed array, the address of an element can be calculated using:

Address = Base Address + (Index × Size of Each Element)

For example, assume:
- Base address = 1000
- Each integer occupies 4 bytes
- Required index = 3

Address = 1000 + (3 × 4)

Address = 1012

This direct address calculation is why accessing an array element by index generally takes constant time, O(1).

Types of Arrays

Arrays can be organized in different dimensions depending on the problem.

1. One-Dimensional Array

A one-dimensional array stores elements in a single sequence.

Example:

cpp
int numbers[5] = {10, 20, 30, 40, 50};

It can be visualized as:

| Index | Value |
|---|---:|
| 0 | 10 |
| 1 | 20 |
| 2 | 30 |
| 3 | 40 |
| 4 | 50 |

One-dimensional arrays are useful for storing lists of numbers, marks, prices, and other similar values.

2. Two-Dimensional Array

A two-dimensional array stores data in rows and columns. It is commonly used to represent matrices and tables.

Example:

cpp
int matrix[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};

The array looks like this:

| | Column 0 | Column 1 | Column 2 |
|---|---:|---:|---:|
| Row 0 | 1 | 2 | 3 |
| Row 1 | 4 | 5 | 6 |

You can access an element using two indices:

cpp
cout << matrix[1][2];

The output is 6.

3. Multidimensional Array

An array with three or more dimensions is called a multidimensional array.

Example:

cpp
int data[2][3][4];

Such arrays can represent more complex structured data, including multiple matrices or grouped measurements.

Basic Array Operations

Understanding common array operations is essential for solving DSA problems.

1. Traversal

Traversal means visiting each element of an array.

```cpp
#include <iostream>
using namespace std;

int main() {
int arr[5] = {10, 20, 30, 40, 50};

for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}

return 0;
}
```

Output:

text
10 20 30 40 50

Time complexity: O(n).

2. Insertion

Insertion means adding a new element at a particular position.

In a fixed-size array, elements may need to be shifted to create space.

For example, inserting 25 at index 2:

Before:

text
10 20 30 40 50

After:

text
10 20 25 30 40 50

The shifting operation can take O(n) time in the worst case.

3. Deletion

Deletion removes an element from a particular position.

For example, deleting the element at index 1:

Before:

text
10 20 30 40 50

After:

text
10 30 40 50

The remaining elements may need to shift left. Worst-case time complexity is O(n).

4. Searching

Searching means finding whether a particular value exists in an array.

Linear search checks elements one by one.

```cpp
int linearSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
return i;
}
}

return -1;
}
```

Worst-case time complexity: O(n).

If the array is sorted, binary search can be used to find an element in O(log n) time.

5. Updating

Updating means changing the value stored at an existing index.

```cpp
int arr[4] = {10, 20, 30, 40};

arr[2] = 99;
```

The updated array becomes:

text
10 20 99 40

Updating an element using its index takes O(1) time.

Time Complexity of Array Operations

The following table shows typical time complexities for common operations on a standard array.

| Operation | Time Complexity |
|---|---|
| Access by index | O(1) |
| Update by index | O(1) |
| Traversal | O(n) |
| Linear search | O(n) |
| Binary search on sorted array | O(log n) |
| Insertion at the beginning | O(n) |
| Deletion at the beginning | O(n) |
| Insertion at the end | O(1) when space is available |
| Deletion at the end | O(1) |

The exact performance of insertion and deletion depends on the position, available capacity, and array implementation.

Static Arrays vs Dynamic Arrays

There are two common ways to work with array-like storage.

Static Array

A static array has a fixed size determined when the array is created.

Example:

cpp
int numbers[5];

This array can hold five integers. Its capacity cannot be increased directly.

Dynamic Array

A dynamic array can grow or shrink as elements are added or removed, depending on the programming language and implementation.

In C++, the vector container provides dynamic array functionality.

```cpp
#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int> numbers = {10, 20, 30};

numbers.push_back(40);
numbers.push_back(50);

for (int value : numbers) {
cout << value << " ";
}

return 0;
}
```

Output:

text
10 20 30 40 50

Dynamic arrays are useful when the number of elements is not known in advance.

Advantages of Arrays

Arrays provide several benefits:

  1. Fast access: Elements can generally be accessed directly using an index.
  2. Simple structure: Arrays are relatively easy to understand and implement.
  3. Memory locality: Contiguous storage can improve cache performance.
  4. Easy traversal: Elements can be processed using loops.
  5. Useful foundation: Many other data structures and algorithms build on array concepts.

Disadvantages of Arrays

Arrays also have some limitations:

  1. Fixed-size arrays cannot grow beyond their allocated capacity.
  2. Inserting elements in the middle may require shifting other elements.
  3. Deleting elements may also require shifting.
  4. Traditional arrays generally store elements of the same data type.
  5. Choosing an unsuitable fixed capacity can waste memory or limit storage.

Dynamic arrays solve some capacity limitations, but resizing can still involve allocating new memory and copying elements.

Common Array Problems in DSA

Once you understand the basics, practice these problems to improve your problem-solving skills.

Beginner Problems

  • Find the largest element in an array.
  • Find the smallest element in an array.
  • Calculate the sum of all elements.
  • Reverse an array.
  • Count even and odd numbers.
  • Find the second largest element.
  • Check whether an array is sorted.

Intermediate Problems

  • Move all zeroes to the end.
  • Remove duplicates from a sorted array.
  • Rotate an array by k positions.
  • Find the missing number.
  • Find the maximum subarray sum.
  • Merge two sorted arrays.
  • Find the majority element.

Advanced Problems

  • Trapping Rain Water.
  • Product of Array Except Self.
  • Maximum Product Subarray.
  • First Missing Positive.
  • Median of Two Sorted Arrays.

These problems help develop skills such as two pointers, prefix sums, sliding windows, and efficient searching.

Practical Tips for Learning Arrays

Follow a structured approach while learning arrays:

  1. Understand indexing and array traversal.
  2. Practice insertion, deletion, and searching.
  3. Learn the difference between static and dynamic arrays.
  4. Study time and space complexity for each operation.
  5. Solve beginner-level problems before moving to intermediate problems.
  6. Practice optimized solutions using techniques such as two pointers and sliding windows.

Try solving each problem independently before checking another solution. This builds stronger problem-solving habits.

Frequently Asked Questions

What is an array in DSA?

An array is a data structure that stores multiple elements in an ordered collection. Elements are accessed using their indices.

Why does array indexing start from zero?

In many programming languages, zero-based indexing makes address calculation straightforward because the first element is at an offset of zero from the base address.

What is the time complexity of accessing an array element?

Accessing an element by its index generally takes O(1) time in a standard array.

Can an array store different data types?

Traditional arrays generally store elements of the same data type. Some languages provide other collection types that can hold mixed values.

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

Arrays generally provide fast indexed access and contiguous storage. Linked lists use connected nodes and typically require sequential traversal to reach an element. Their insertion, deletion, and memory characteristics are different.

Are arrays important for coding interviews?

Yes. Array problems are common in coding interviews and are used to test searching, sorting, traversal, two-pointer techniques, and other problem-solving skills.

Conclusion

Arrays are a fundamental data structure in DSA. They make it possible to store and access collections of elements efficiently. Understanding array indexing, memory representation, traversal, insertion, deletion, searching, and complexity provides a strong foundation for more advanced topics.

Practice array problems regularly and learn to recognize patterns such as two pointers, sliding windows, and prefix sums. These skills will help you solve more complex DSA problems.

✓

You’ve reached the end of this guide. Explore more tutorials on PrimeProblem.