DSA Chapter 2: Arrays The Backbone of Data Structures (C - Edition)

 



   C - Edition

DSA Chapter 2: Arrays 

The Backbone of Data Structures

If you are new to array check these before moving forward

Introduction to Arrays, Addition of two arrays, Product of two matrices, Pointers & arrays

Example on pointer & arraysPassing arrays to functions,


What is an array?

An array in C is a collection of elements of the same type stored in contiguous memory locations. Elements are accessed by integer indices starting at 0.

Example:

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

Why Are Arrays Important?

> Fast access: O(1) — direct indexing
> Easy iteration: O(n)
> Foundation for:

  • Strings

  • Matrices

  • Hashing

  • Dynamic arrays

  • Heaps

  • Segment trees

Array Time Complexities (Interview-Must Know)

OperationTime ComplexityExplanation
AccessO(1)    Direct index lookup
SearchO(n)    Linear search
Insert at endO(1)*    Amortized (dynamic arrays)
Insert at beginningO(n)    Shifting required
Delete at beginningO(n)    Shifting required

Memory layout & indexing

  • Contiguous memory → &arr[i+1] == &arr[i] + 1 (scaled by element size).

  • Access arr[i] costs constant time O(1).

  • Element size (sizeof(type)) matters for pointer arithmetic.

Arrays vs Pointers — the relationship

  • The name arr decays to &arr[0] in most expressions (except sizeof(arr) and &arr).

  • arr[i] is equivalent to *(arr + i).

  • But arr (a fixed-size array) and int *p (pointer) are different at compile time: sizeof(arr) gives total bytes; sizeof(p) gives pointer size.

Static vs Dynamic arrays

  • Static array — compile-time or block-scoped with fixed size: int a[100];

    • Pros: simple, no malloc overhead.

    • Cons: fixed size, stack usage (if local).

  • Dynamic array — allocated at runtime: int *a = malloc(n * sizeof *a);

    • Pros: flexible, use heap.

    • Must free(a) when done.

    • Handle allocation failures: if (!a) { /* handle */ }.

Multidimensional arrays

  • 2D static array: int mat[3][4]; → contiguous storage row-major in C.

  • Access mat[i][j] → element offset i * cols + j.

  • For dynamic 2D arrays, you can allocate a single block (malloc(rows*cols*sizeof)) and index manually, or allocate array of pointers (less contiguous).

Passing arrays to functions

  • Arrays decay to pointers; function signature typical: 

    void f(int arr[], int n) 
    void f(int *arr, int n).
  • You must pass the size separately if needed.

  • For 2D static arrays you need column size: void f(int mat[][COLS]) or use pointer-to-pointer or single-block trick.

Common operations & complexity

  • Access by index: O(1).

  • Traverse/search (linear): O(n).

  • Insert/delete at arbitrary index: O(n) (shifts).

  • Insert/delete at end (if space available): O(1).

  • Sorting: depends on algorithm (e.g., quicksort average O(n log n)).

  • Space complexity: in-place ops use O(1) extra (except recursion).

Pointer arithmetic examples

int a[3] = {1,2,3};
int *p = a;        // points to a[0]
*(p + 2);          // a[2]

Important implementation patterns (C-focused)

  1. Iterate safely: always ensure index bounds. Undefined behavior on out-of-bounds.

  2. Dynamic resizing (vector-like):

    • Double capacity when full; shrink optionally.

    • Use realloc carefully (check returned pointer before replacing original).

  3. Use size_t for sizes/indices — it is unsigned and standard for sizes.

  4. Initialization: static arrays default to zero if global/static; local automatic arrays contain garbage unless initialized.

  5. Avoid returning pointer to local array — they go out of scope. Use malloc or caller-allocated buffers.

Common pitfalls

  • Off-by-one errors (loop bounds).

  • Using signed vs unsigned for indexes causing logic issues when mixing with size_t.

  • Not checking malloc/realloc result.

  • Freeing memory twice or using freed memory (use-after-free).

  • Mixing arrays with pointer arithmetic incorrectly for multi-dimensional indexing.

Useful array techniques for DSA

  • Two pointers — often used for sorted arrays (left/right indices).

  • Sliding window — for subarray problems with sum/length constraints.

  • Prefix sum — build pref[i] = sum(arr[0..i-1]) to get range sums O(1).

  • Suffix arrays (not string SA but suffix sums) — useful for suffix queries.

  • In-place partitioning — e.g., Dutch National Flag for three-way partition (0/1/2).

  • Frequency arrays / counting sort — when value range small.

  • Hashing using arrays — direct-address tables for small ranges.

  • Bitset/bit-array — memory efficient (use unsigned long and bit ops).

  • Circular buffers / ring buffers — fixed-size queue using modulo indexing.

Strings and char arrays

  • C strings are char arrays terminated by '\0'. Always ensure termination.

  • Use strlen, strcpy, strncpy (careful), memcmp, memcpy for low-level ops.

  • For performance in DSA, prefer manual loops with bounds checks over unsafe library misuse.

Example: dynamic array (simple vector)

typedef struct {
    int *data;
    size_t size;
    size_t capacity;
} Vector;

void vector_init(Vector *v) {
    v->size = 0;
    v->capacity = 4;
    v->data = malloc(v->capacity * sizeof *v->data);
}

void vector_push(Vector *v, int x) {
    if (v->size == v->capacity) {
        size_t newcap = v->capacity * 2;
        int *tmp = realloc(v->data, newcap * sizeof *v->data);
        if (!tmp) { /* handle OOM */ return; }
        v->data = tmp;
        v->capacity = newcap;
    }
    v->data[v->size++] = x;
}

void vector_free(Vector *v) {
    free(v->data);
    v->data = NULL;
    v->size = v->capacity = 0;
}

How arrays fit into the DSA roadmap

  • Arrays → fundamental for sorting, searching, two pointers, sliding window, hashing.

  • Many more advanced DS (segment trees, Fenwick trees, suffix arrays) are built on array concepts.

  • Master arrays first; then move to linked lists → stacks/queues → trees → graphs → DP.

Most Important Array Interview Questions

These are mandatory. Companies repeatedly ask them.

  1. Find largest and smallest element

  2. Reverse an array

  3. Left rotate and right rotate array

  4. Remove duplicates

  5. Find missing number in 1…n

  6. Find the second largest element

  7. Count frequency of elements

  8. Move all zeros to end

  9. Kadane’s algorithm (max subarray sum)

  10. Two-sum problem

  11. Pair with given sum

  12. Sort 0s,1s,2s (Dutch National Flag problem)


C Edition – 20 Practice Questions 

  1. Write a C program to find the largest element in an array.

  2. Write a C program to find the smallest element in an array.

  3. Write a C program to search for an element in an array using linear search.

  4. Write a C program to reverse an array without using a second array.

  5. Write a C program to insert an element at a given position in an array.

  6. Write a C program to delete an element from a given index in an array.

  7. Write a C program to count the frequency of each element in an array.

  8. Write a C program to find the second largest element in an array.

  9. Write a C program to remove duplicate elements from an array.

  10. Write a C program to print all unique elements of an array.

  11. Write a C program to count the total number of even and odd numbers in an array.

  12. Write a C program to left rotate an array by one position.

  13. Write a C program to right rotate an array by one position.

  14. Write a C program to left rotate an array by K positions.

  15. Write a C program to merge two arrays into a third array.

  16. Write a C program to find the missing number in an array containing 1 to n.

  17. Write a C program to find the sum and average of array elements.

  18. Write a C program to check whether an array is sorted or not.

  19. Write a C program to copy all elements from one array to another.

  20. Write a C program to find the maximum subarray sum (Kadane’s algorithm).


✔ Conclusion

Arrays are the strongest base for mastering:

  • Searching

  • Sorting

  • Recursion

  • Backtracking

  • Dynamic Programming

  • Graphs

  • Trees

Mastering arrays is the first step to cracking 90% of interviews.

ALSO CHECK 

DS(Data Structure) Python Edition

DSA Series Chapter 1 Time & Space Complexity ( C Edition)






Tail Recursion Optimization: How Compilers Convert Recursion Into Iteration


Advanced Recursion: Memoization vs. Tabulation — The Deep Optimization Blueprint for Professionals


Advanced Sorting Algorithms: Merge Sort Internals — Merge Tree, Cache Behavior & Real Cost Analysis


Enjoyed this post? [Follow here] for daily coding insights.

Comments