āˆž

Algo Infinity Verse

Master Data Structures With Arrays The Foundation of DSA

|
0 Topics
0 Examples
0 Interview Questions

šŸ“¦ Learn Arrays

Build a strong foundation in arrays before moving to advanced DSA topics.

0 / 9 topics completed
0%
01

Introduction to Arrays

Arrays are one of the most important data structures in computer science. They store multiple values of the same type in contiguous memory locations, making element access extremely fast.

Why Learn Arrays?

  • Foundation of DSA — most advanced topics build on arrays
  • Fast element access — O(1) random access by index
  • Used everywhere — searching, sorting, DP, graphs
  • Frequently asked — core topic in every coding interview
C
int arr[5] = {10, 20, 30, 40, 50};
Output
Index :  0   1   2   3   4
Value : 10  20  30  40  50
šŸ’”

Arrays use 0-based indexing — the first element is at index 0, not 1. Accessing an element by index is always O(1) regardless of array size.

02

Array Basics

Arrays store elements sequentially in memory. Every element is accessed using an index. Understanding the time complexity of each operation is essential for writing efficient code.

Operation Time Complexity Notes
AccessO(1)Direct index lookup
SearchO(n)Linear scan required
InsertionO(n)Shift elements right
DeletionO(n)Shift elements left
Append (end)O(1)No shifting needed
⚔

Array size must be defined at compile time in C/C++. For dynamic sizing, use dynamic arrays (vector in C++, ArrayList in Java, or list in Python).

03

Array Traversal

Traversal means visiting every element of the array exactly once. It is the foundation of almost every array algorithm — searching, printing, and computing sums all rely on traversal.

C
int arr[5] = {10, 20, 30, 40, 50};
int n = 5;

for (int i = 0; i < n; i++)
{
    printf("arr[%d] = %d\n", i, arr[i]);
}
Output
arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40
arr[4] = 50
Practice: Traversal

Write a traversal that prints the sum and maximum element of this array:

{3, 7, 1, 9, 4, 6}
C
int arr[] = {3, 7, 1, 9, 4, 6};
int n = 6, sum = 0, max = arr[0];

for (int i = 0; i < n; i++) {
    sum += arr[i];
    if (arr[i] > max) max = arr[i];
}
printf("Sum = %d, Max = %d\n", sum, max);
/* Sum = 30, Max = 9 */
04

Insertion In Arrays

To insert an element at a given position, all elements from that position onward must be shifted one place to the right to create space.

Steps for Insertion

  • Start from the last element and shift each element right
  • Stop when you reach the target position
  • Place the new value at the target position
  • Increment the array size counter by 1
C
// Insert value at position pos in array of current size n
for (int i = n; i > pos; i--)
{
    arr[i] = arr[i - 1];   // shift right
}
arr[pos] = value;
n++;  // update size
Example
Before : 10  20  40  50   (n = 4)
Insert   30  at pos 2
After  : 10  20  30  40  50  (n = 5)
āš ļø

Always ensure the array has enough allocated capacity before inserting. Inserting into a full fixed-size array causes a buffer overflow.

05

Deletion In Arrays

Deletion requires shifting every element after the deleted position one place to the left to fill the gap. The array size shrinks by one.

⚔

Worst-case time complexity is O(n) — deleting the first element requires shifting all remaining elements.

C
// Delete element at position pos
for (int i = pos; i < n - 1; i++)
{
    arr[i] = arr[i + 1];   // shift left
}
n--;  // update size
Example
Before : 10  20  30  40  50
Delete   30  (pos = 2)
After  : 10  20  40  50
Practice: Deletion

Delete the element 50 from the array below and print the result:

{10, 30, 50, 70, 90}
C
int arr[] = {10, 30, 50, 70, 90};
int n = 5, pos = 2;  // 50 is at index 2

for (int i = pos; i < n - 1; i++)
    arr[i] = arr[i + 1];
n--;

for (int i = 0; i < n; i++)
    printf("%d ", arr[i]);
// Output: 10 30 70 90
06

Searching In Arrays

Searching means finding the position (index) of a target element inside an array. There are two fundamental approaches: Linear Search and Binary Search.

Linear Search

Scan every element from left to right until the key is found or the array is exhausted. Works on unsorted arrays.

C
int linearSearch(int arr[], int n, int key)
{
    for (int i = 0; i < n; i++)
    {
        if (arr[i] == key)
            return i;   // found: return index
    }
    return -1;          // not found
}
Example
Array  : 10  20  30  40  50
Key    : 40
Output : Found at index 3
šŸ”

Linear Search: O(n) time, O(1) space. For sorted arrays, Binary Search achieves O(log n) by halving the search space each step.

Practice: Searching

Find the position of 75 in the array below using Linear Search:

{25, 50, 75, 100, 125}
C
int arr[] = {25, 50, 75, 100, 125};
int n = 5, key = 75;

int result = linearSearch(arr, n, key);
if (result != -1)
    printf("Found at index %d\n", result);
else
    printf("Not found\n");
// Output: Found at index 2
07

Sorting Arrays

Sorting arranges elements in ascending or descending order. It is a prerequisite for Binary Search and many other efficient algorithms.

Algorithm Best Average Worst
Bubble SortO(n)O(n²)O(n²)
Selection SortO(n²)O(n²)O(n²)
Insertion SortO(n)O(n²)O(n²)
Merge SortO(n log n)O(n log n)O(n log n)
Quick SortO(n log n)O(n log n)O(n²)

Bubble Sort — Compare Adjacent Pairs

Repeatedly swap adjacent elements if they are in the wrong order. The largest element "bubbles up" to the end in each pass.

C — Bubble Sort
for (int i = 0; i < n - 1; i++)
{
    for (int j = 0; j < n - i - 1; j++)
    {
        if (arr[j] > arr[j + 1])
        {
            int temp   = arr[j];
            arr[j]     = arr[j + 1];
            arr[j + 1] = temp;
        }
    }
}
Practice: Sorting

Sort the following array in ascending order using Bubble Sort and trace the first pass:

{64, 34, 25, 12, 22}
C
/* First pass trace:
   64 34 25 12 22
   34 64 25 12 22  (swap 64,34)
   34 25 64 12 22  (swap 64,25)
   34 25 12 64 22  (swap 64,12)
   34 25 12 22 64  (swap 64,22) ← 64 is in final position

   After all passes: 12 22 25 34 64 */

int arr[] = {64, 34, 25, 12, 22};
int n = 5;
bubbleSort(arr, n);   // use the function above
08

2D Arrays

A 2D Array is a collection of rows and columns — essentially an array of arrays. It is the natural way to represent matrices, grids, and board-based problems.

Common Use Cases

2D arrays are used in matrix math, image pixel buffers, game boards, graph adjacency matrices, and dynamic programming tables.

C
int matrix[3][3] =
{
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

// Print the matrix
for (int r = 0; r < 3; r++) {
    for (int c = 0; c < 3; c++)
        printf("%d ", matrix[r][c]);
    printf("\n");
}
Matrix Output
1  2  3
4  5  6
7  8  9
🧩

Access any element with matrix[row][col]. Row-major storage means matrix[0][0], matrix[0][1], matrix[0][2] are contiguous in memory.

09

Array Interview Tips

Arrays appear in nearly every technical interview. Here is what you need to master to solve them confidently.

Must-Know Techniques

  • Two Pointers — solve in-place problems in O(n)
  • Sliding Window — max/min subarray of fixed or variable size
  • Prefix Sum — range sum queries in O(1) after O(n) prep
  • Kadane's Algorithm — maximum subarray sum in O(n)
  • Binary Search — O(log n) search on sorted arrays
  • Always clarify: is the array sorted? Can you modify it in-place?
  • Watch for off-by-one errors at boundaries.
  • Consider edge cases: empty array, single element, all duplicates.
  • Know time and space complexity of every built-in sort.
  • Practice at least one array problem every day until interviews.
Classic Interview Problem

Maximum Subarray (Kadane's Algorithm): Find the contiguous subarray with the largest sum.

Input : {-2, 1, -3, 4, -1, 2, 1, -5, 4}
Output: 6  (subarray [4, -1, 2, 1])
C
int maxSubArray(int arr[], int n)
{
    int maxSum  = arr[0];
    int current = arr[0];

    for (int i = 1; i < n; i++)
    {
        // Either extend the current subarray or start fresh
        current = (arr[i] > current + arr[i]) ? arr[i] : current + arr[i];
        if (current > maxSum) maxSum = current;
    }
    return maxSum;
}
// Returns 6 for the example above