Skip to content

Arrays

The fundamental data structure for sequential data


Overview

An array is a collection of elements of the same data type stored in contiguous memory locations. This fundamental data structure forms the backbone of most programming operations and is essential for SDE interviews.

What is an Array?

Arrays store elements sequentially in memory, where each element can be accessed directly using its index. For example, an array of ten 32-bit integers with indices 0-9 stored starting at memory address 2000 would have elements at addresses 2000, 2004, 2008, ..., 2036. The element at index i has address: base_address + (i * element_size).

Memory Layout

Memory Address:  2000   2004   2008   2012   2016   2020
                +------+------+------+------+------+------+
Array:          |  10  |  20  |  30  |  40  |  50  |  60  |
                +------+------+------+------+------+------+
Index:            0      1      2      3      4      5

Key Characteristics:

  • Contiguous allocation: Elements stored next to each other in memory
  • Fixed size: Traditional arrays have a fixed size declared at initialization
  • Homogeneous: All elements must be of the same data type
  • Zero-indexed: Most languages use 0-based indexing

When to Use Arrays

Use CaseWhy Arrays Work Well
Sequential data accessO(1) access by index
Fixed-size collectionsMemory-efficient, no overhead
Cache-friendly operationsSpatial locality improves performance
Matrix/grid problemsNatural 2D representation
Implementing other structuresFoundation for stacks, queues, heaps

When to Consider Alternatives

LimitationBetter Alternative
Frequent insertions/deletions in middleLinked List
Unknown or highly variable sizeDynamic Array / List
Need fast lookups by valueHash Table
Ordered data with frequent updatesBalanced BST

Document Structure

ProblemDifficultyPatternLink
Move ZerosEasyTwo PointerLink
Remove Duplicates from Sorted ArrayEasyTwo PointerLink
Best Time to Buy and Sell StockEasyOne PassLink
Contains DuplicateEasyHash SetLink
Two SumEasyHash MapLink
Maximum Subarray (Kadane's)MediumDynamic ProgrammingLink
Three SumMediumTwo Pointer + SortLink
Container With Most WaterMediumTwo PointerLink
Product of Array Except SelfMediumPrefix/SuffixLink
Merge IntervalsMediumSorting + GreedyLink
Rotate ArrayMediumReverse TechniqueLink
Find Peak ElementMediumBinary SearchLink
Search in Rotated Sorted ArrayMediumBinary SearchLink
Subarray Sum Equals KMediumPrefix Sum + HashLink
Sliding Window MaximumHardMonotonic DequeLink
Trapping Rain WaterHardTwo Pointer / StackLink
First Missing PositiveHardIndex MarkingLink
Median of Two Sorted ArraysHardBinary SearchLink

Array Operations Complexity

OperationTime ComplexitySpace ComplexityNotes
Access by indexO(1)O(1)Direct memory calculation
Search (unsorted)O(n)O(1)Linear scan required
Search (sorted)O(log n)O(1)Binary search
Insert at endO(1) amortizedO(1)O(n) when resizing needed
Insert at beginningO(n)O(1)Shift all elements right
Insert at middleO(n)O(1)Shift elements after position
Delete at endO(1)O(1)Simply decrease length
Delete at beginningO(n)O(1)Shift all elements left
Delete at middleO(n)O(1)Shift elements after position
Copy arrayO(n)O(n)Must copy each element
Resize (dynamic)O(n)O(n)Copy to new array

Static vs Dynamic Arrays

FeatureStatic ArrayDynamic Array (Python List)
SizeFixed at creationGrows/shrinks automatically
MemoryExact allocationOver-allocates for growth
Insert (end)N/A or O(n)O(1) amortized
Memory overheadNone~12.5% extra capacity

Common Array Patterns

Pattern Selection Flowchart

Pattern Quick Reference

PatternWhen to UseExample ProblemsTime Complexity
Two PointersSorted array, pair findingTwo Sum II, 3Sum, Container WaterO(n)
Sliding WindowContiguous subarray/substringMax Sum Subarray, Longest SubstringO(n)
Prefix SumRange sum queries, subarray sumsSubarray Sum Equals K, Range SumO(n) preprocessing
Binary SearchSorted array, find target/boundarySearch Rotated, Peak ElementO(log n)
Hash Map/SetValue lookup, frequency countingTwo Sum, Contains DuplicateO(n) with O(n) space
In-place SwapRearrange without extra spaceMove Zeros, Dutch National FlagO(n)
Kadane's AlgorithmMaximum subarray sumMaximum SubarrayO(n)
Monotonic Stack/DequeNext greater/smaller, sliding maxSliding Window MaximumO(n)

Python Array Tips

List vs Array Module vs NumPy

python
# Python List (most common for interviews)
arr = [1, 2, 3, 4, 5]           # Dynamic, heterogeneous allowed
arr.append(6)                   # O(1) amortized
arr.pop()                       # O(1) from end
arr.insert(0, 0)                # O(n) - shifts elements

# array module (typed, more memory efficient)
import array
arr = array.array('i', [1, 2, 3])  # 'i' = signed int

# NumPy (for numerical computing, rarely in interviews)
import numpy as np
arr = np.array([1, 2, 3])       # Vectorized operations

Essential List Methods

python
# Creation
arr = [0] * n                   # Array of n zeros
arr = [[0] * cols for _ in range(rows)]  # 2D array (CORRECT)
arr = [[0] * cols] * rows       # WRONG - creates references!

# Slicing
arr[start:end]                  # Elements from start to end-1
arr[start:end:step]             # With step
arr[::-1]                       # Reverse array
arr[::2]                        # Every other element

# Common Operations
arr.append(x)                   # Add to end - O(1) amortized
arr.pop()                       # Remove from end - O(1)
arr.pop(0)                      # Remove from front - O(n)
arr.insert(i, x)                # Insert at index - O(n)
arr.remove(x)                   # Remove first occurrence - O(n)
arr.index(x)                    # Find index of x - O(n)
arr.count(x)                    # Count occurrences - O(n)
arr.sort()                      # In-place sort - O(n log n)
sorted(arr)                     # Returns new sorted list
arr.reverse()                   # In-place reverse - O(n)
reversed(arr)                   # Returns iterator

# List Comprehensions (Pythonic)
squares = [x**2 for x in range(10)]
evens = [x for x in arr if x % 2 == 0]
flattened = [x for row in matrix for x in row]

Common Interview Idioms

python
# Two Pointers Template
def two_pointer_template(arr):
    left, right = 0, len(arr) - 1
    while left < right:
        # Process arr[left] and arr[right]
        if condition:
            left += 1
        else:
            right -= 1

# Sliding Window Template (Variable Size)
def sliding_window_template(arr, target):
    left = 0
    window_sum = 0
    result = 0

    for right in range(len(arr)):
        window_sum += arr[right]  # Expand window

        while window_sum > target:  # Shrink window
            window_sum -= arr[left]
            left += 1

        result = max(result, right - left + 1)

    return result

# Prefix Sum Template
def prefix_sum_template(arr):
    prefix = [0]
    for num in arr:
        prefix.append(prefix[-1] + num)
    # Sum of arr[i:j] = prefix[j] - prefix[i]
    return prefix

Interview Focus Areas

Based on recent SDE interview patterns (2025-2026), these array topics are most frequently tested:

High Priority Topics

  1. Two Sum Variants - The classic "find pairs that sum to target" appears in multiple forms
  2. Subarray Problems - Finding contiguous subarrays with specific properties (max sum, equals K)
  3. Merge Intervals - Combining overlapping intervals, meeting room scheduling
  4. Sliding Window - Both fixed and variable window sizes
  5. Binary Search on Arrays - Especially in rotated/modified sorted arrays

Common Google Array Questions (2025-2026)

Question TypeExample ProblemKey Insight
Pair Sum"Find two indices where values sum to target"Hash map for O(n)
Maximum Subarray"Find contiguous subarray with largest sum"Kadane's algorithm
Merge Intervals"Merge all overlapping intervals"Sort by start, then merge
Split Array"Count ways to split array so concatenation is sorted"Recent OA question
Array Manipulation"Flip at most one element to minimize absolute sum"Consider each flip

What Interviewers Look For

  1. Clarifying Questions

    • Are there duplicates?
    • Can I modify the input array?
    • What about empty arrays or single elements?
    • Are values bounded? Positive only?
  2. Problem-Solving Approach

    • Start with brute force, then optimize
    • Discuss time/space tradeoffs
    • Consider edge cases before coding
  3. Code Quality

    • Clean, readable code
    • Meaningful variable names
    • Handle edge cases explicitly
  4. Testing

    • Walk through example inputs
    • Test edge cases (empty, single element, all same values)
    • Verify with larger inputs mentally

Interview Strategy for Array Problems


Practice Progression

Week 1: Foundations

DayFocusProblems
1Basic OperationsTwo Sum, Contains Duplicate, Remove Duplicates
2Two PointersMove Zeros, Three Sum, Container With Most Water
3Sliding WindowMax Sum Subarray Size K, Longest Substring Without Repeating

Week 2: Intermediate

DayFocusProblems
4Prefix SumSubarray Sum Equals K, Product Except Self
5Binary SearchSearch in Rotated, Find Peak, First Bad Version
6Sorting-BasedMerge Intervals, Meeting Rooms, Sort Colors

Week 3: Advanced

DayFocusProblems
7Monotonic StackNext Greater Element, Trapping Rain Water
8Advanced PatternsSliding Window Maximum, First Missing Positive
9Mixed PracticeRandom selection from all patterns

Quick Reference Card

Time Complexity Cheat Sheet

Access:     O(1)     - arr[i]
Search:     O(n)     - unsorted, O(log n) sorted
Insert:     O(n)     - worst case, O(1) amortized at end
Delete:     O(n)     - worst case, O(1) at end
Sort:       O(n log n) - comparison-based

Pattern Recognition Triggers

If you see...Think about...
"Sorted array"Binary Search, Two Pointers
"Subarray"Sliding Window, Prefix Sum
"Pairs that sum"Hash Map, Two Pointers
"Contiguous"Sliding Window, Kadane's
"In-place"Two Pointers, Swap technique
"Next greater/smaller"Monotonic Stack
"K largest/smallest"Heap, QuickSelect

Resources

Further Reading


Last updated: January 2026

Arrays are the foundation of technical interviews. Master the patterns here, and you'll find that many "hard" problems become manageable applications of these core techniques.