Skip to content

    Arrays

    DSA · Beginner

    Definition

    An array is a collection of elements stored in contiguous memory, where each element is accessed directly by its index.

    Arrays are the foundation of almost every data structure and appear in most coding interviews.

    Diagram

    [0] 5[1] 8[2] 2[3] 9[4] 1

    Flowchart

    Declare arrayStore elements at indexes 0..n-1Access arr[i] in O(1)Traverse with a loopInsert/delete shifts elements

    Example: Find the maximum element

    arr = [5, 8, 2, 9, 1]
    best = arr[0]
    for x in arr:
        if x > best:
            best = x
    print(best)

    Output: 9

    Complexity

    Access O(1) · Search O(n) · Insert/Delete O(n)

    Key points

    • Indexes start at 0
    • Fixed-size in C/Java, dynamic lists in Python
    • Cache-friendly due to contiguous memory

    Interview questions

    Why is array access O(1)?

    The address is computed directly: base + index × element size.

    How do you reverse an array in place?

    Swap arr[l] and arr[r] while moving two pointers toward the middle.

    Array vs linked list?

    Arrays give O(1) access; linked lists give O(1) insert/delete at a known node.

    More DSA topics