👁 Preview — Study, Practice and Revise are open; mock tests and the rest of the syllabus unlock on subscription. Unlock all · ₹4,999
← Back to Linear Data Structures
Study mode

Arrays

Introduction to Arrays

Imagine you have a row of lockers, each numbered and placed side by side. You want to store your books in these lockers so that you can quickly find any book by just knowing the locker number. This is the basic idea behind an array - a fundamental linear data structure used to organize and store multiple items of the same type in a contiguous block of memory.

Arrays are essential in programming and competitive exams because they allow efficient access and management of data. However, they come with some limitations, such as a fixed size decided at the time of creation. Understanding arrays thoroughly will help you solve many problems quickly and accurately.

Array Definition and Memory Layout

An array is a collection of elements, all of the same data type, stored in contiguous memory locations. The term contiguous means that the elements are placed one after another without any gaps.

Each element in the array can be accessed directly using its index, which starts from 0. This zero-based indexing means the first element is at position 0, the second at position 1, and so on.

For example, consider an array of 5 integers representing daily expenses in INR:

  • Day 1: Rs.150
  • Day 2: Rs.200
  • Day 3: Rs.175
  • Day 4: Rs.225
  • Day 5: Rs.190

These values are stored one after another in memory, allowing quick access by index.

150 Index 0 200 Index 1 175 Index 2 225 Index 3 190 Index 4

Advantages of Arrays:

  • Constant-time access: Accessing any element by index takes the same amount of time, regardless of the array size.
  • Simple structure: Easy to understand and use for storing data.

Limitations:

  • Fixed size: The size must be known beforehand and cannot be changed dynamically.
  • Costly insertions and deletions: Inserting or deleting elements in the middle requires shifting other elements.

Address Calculation Formula

\[Address(A[i]) = Base\_Address + (i \times Size\_of\_Element)\]

Calculate the memory address of the ith element in an array

\(Base_Address\) = Starting address of the array
i = Index of the element
\(Size_of_Element\) = Size of each element in bytes

Basic Operations on Arrays

Arrays support several fundamental operations that allow us to manipulate and retrieve data efficiently. Let's explore these operations with clear explanations and examples.

Traversal

Traversal means visiting each element of the array one by one. This is often the first step in many algorithms, such as searching or finding the maximum value.

Example: To print all daily expenses stored in an array, we start from index 0 and move up to the last index.

Insertion

Insertion involves adding a new element at a specific position in the array. Since arrays have fixed size, insertion is only possible if there is space available.

When inserting at the end, the new element is simply placed at the next free index. However, inserting at the beginning or middle requires shifting all subsequent elements one position to the right to make space.

Deletion

Deletion removes an element from a specific position. After deletion, all elements to the right of that position must be shifted one position to the left to fill the gap.

Searching

Searching means finding the position of a particular element in the array. The simplest method is linear search, where we check each element from start to end until we find the target.

graph TD    Start[Start Operation] --> CheckPos{Is position valid?}    CheckPos -- No --> End[Stop: Invalid Position]    CheckPos -- Yes --> InsertShift[Shift elements right]    InsertShift --> InsertElement[Insert new element]    InsertElement --> End    StartDel[Start Deletion] --> CheckPosDel{Is position valid?}    CheckPosDel -- No --> EndDel[Stop: Invalid Position]    CheckPosDel -- Yes --> DeleteShift[Shift elements left]    DeleteShift --> EndDel

This flowchart shows the general steps for insertion and deletion in arrays.

Key Concept

Array Operations

Traversal, insertion, deletion, and searching are key operations with varying time complexities.

Worked Examples

Example 1: Finding the Maximum Element in an Array Easy
Given the array of daily expenses in INR: [150, 200, 175, 225, 190], find the maximum expense.

Step 1: Initialize a variable max with the first element: 150.

Step 2: Traverse the array from index 1 to 4, comparing each element with max.

Step 3: At index 1, 200 > 150, so update max = 200.

At index 2, 175 < 200, no change.

At index 3, 225 > 200, update max = 225.

At index 4, 190 < 225, no change.

Answer: The maximum expense is Rs.225.

Example 2: Inserting an Element at a Specific Position Medium
Given the array [10, 20, 30, 40, 50] with size 5 and capacity 6, insert the element 25 at position 3 (0-based indexing).

Step 1: Check if there is space to insert (capacity 6 > current size 5) - yes.

Step 2: Shift elements from the last index (4) to position 3 one step right:

  • Move element at index 4 (50) to index 5
  • Move element at index 3 (40) to index 4

Array after shifting: [10, 20, 30, 40, 40, 50]

Step 3: Insert 25 at index 3.

Final array: [10, 20, 30, 25, 40, 50]

Answer: Array after insertion is [10, 20, 30, 25, 40, 50].

Example 3: Deleting an Element from an Array Medium
Given the array [5, 15, 25, 35, 45], delete the element at position 2 (0-based indexing).

Step 1: Identify the element to delete: 25 at index 2.

Step 2: Shift elements from index 3 to the end one position left:

  • Move element at index 3 (35) to index 2
  • Move element at index 4 (45) to index 3

Array after shifting: [5, 15, 35, 45, 45]

Step 3: Reduce the logical size of the array by 1 (ignore last duplicate).

Final array: [5, 15, 35, 45]

Answer: Array after deletion is [5, 15, 35, 45].

Example 4: Searching for an Element Using Linear Search Easy
Find the position of element 225 in the array [150, 200, 175, 225, 190]. If not found, print -1.

Step 1: Start from index 0 and compare each element with 225.

Index 0: 150 ≠ 225

Index 1: 200 ≠ 225

Index 2: 175 ≠ 225

Index 3: 225 = 225 -> Found!

Answer: Element 225 found at index 3.

Example 5: Using Arrays to Represent a Matrix Medium
Represent the following 3x3 matrix using a 2D array and find the element at row 2, column 3 (1-based indexing):
\[ \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{bmatrix} \]

Step 1: Declare a 2D array with 3 rows and 3 columns.

Step 2: Store the matrix elements as:

    matrix[0][0] = 1; matrix[0][1] = 2; matrix[0][2] = 3;    matrix[1][0] = 4; matrix[1][1] = 5; matrix[1][2] = 6;    matrix[2][0] = 7; matrix[2][1] = 8; matrix[2][2] = 9;    

Step 3: To access element at row 2, column 3 (1-based), convert to 0-based indices: row = 1, column = 2.

Element = matrix[1][2] = 6.

Answer: The element at row 2, column 3 is 6.

Tips & Tricks

Tip: Remember that array indices start at 0.

When to use: When accessing or iterating over array elements to avoid off-by-one errors.

Tip: For insertion or deletion in arrays, always shift elements correctly.

When to use: When performing insertion or deletion at positions other than the end.

Tip: Use linear search for unsorted arrays; binary search only for sorted arrays.

When to use: To choose the correct searching algorithm based on array order.

Tip: Visualize arrays as contiguous blocks of memory to understand address calculations.

When to use: To grasp memory allocation and optimize access.

Tip: Practice boundary cases like empty arrays or single-element arrays.

When to use: To avoid runtime errors and logical mistakes in coding.

Common Mistakes to Avoid

❌ Accessing array elements starting from index 1 instead of 0
✓ Always start indexing from 0 in arrays.
Why: Many students assume arrays start at 1 due to natural counting, causing off-by-one errors.
❌ Not shifting elements correctly during insertion or deletion
✓ Shift all subsequent elements one position right (for insertion) or left (for deletion).
Why: Forgetting to move elements leads to data overwrite or loss.
❌ Using binary search on unsorted arrays
✓ Use linear search for unsorted arrays; sort the array first if binary search is needed.
Why: Binary search requires sorted data; applying it on unsorted arrays yields incorrect results.
❌ Ignoring array size limits leading to overflow
✓ Check array bounds before insertion or access to prevent overflow or segmentation faults.
Why: Not validating indices causes runtime errors.
❌ Confusing array length with last index
✓ Remember last index = length - 1.
Why: Misunderstanding this leads to index out of range errors.
FeatureArrayLinked ListStack/Queue
MemoryContiguousNon-contiguousContiguous or linked
Access TimeO(1) by indexO(n) by positionO(1) top/front
Insertion/DeletionO(n) middle, O(1) endO(1) anywhereO(1) at ends
SizeFixed (static)DynamicFixed or dynamic
Use CaseRandom accessDynamic sizeLIFO/FIFO operations
Key Concept

Key Properties of Arrays

Fixed size, contiguous memory, zero-based indexing, constant-time access, costly middle insertions/deletions.

Curated videos per subtopic
Top YouTube explainers, AI-ranked for your exam and language. Unlocks with subscription.
Unlock

Try Practice next.

Progress tracking is paywalled — subscribe to mark subtopics as understood and save your streak.

Go to practice →
Ask a doubt
Arrays · 10 free messages
Ask me anything about this subtopic. You have 10 free messages this session — chat history isn't saved in preview.