Tensorum

Array

Hashing, prefix sums, two pointers, matrices and the array patterns behind most interview questions.

DSABeginner29 hrs11 patterns · 54 problems
0%
your progress

Core idea

Trade space for time with a hash map, or exploit order with sorting, two pointers and prefix sums. Ask: can one pass with the right auxiliary structure replace the nested loop?

Reach for it when

  • Input is a list/sequence and you need pairs, ranges or counts
  • Brute force is O(n²) over pairs or subarrays
  • Order matters (prefix sums) or doesn't (sort first, hash)

Template

def subarray_sum_equals_k(nums, k):
    seen = {0: 1}          # prefix sum -> count
    total = count = 0
    for x in nums:
        total += x
        count += seen.get(total - k, 0)
        seen[total] = seen.get(total, 0) + 1
    return count

Complexity

Usually O(n) time with O(n) hash space, or O(n log n) after sorting with O(1) extra.

Common pitfalls

  • Forgetting the empty-prefix base case {0: 1}
  • Two pointers on unsorted data
  • Mutating the array while iterating over it

Recognition cues

Two PointersPrefix SumKadaneSliding WindowSortingMatrixCyclic SortHashing