AlgoViz

O(n) linear time

easy 13 min

O(n) means the work grows in direct proportion to the input: double the data, double the time.

See it run

Walk an [i] pointer across an array to find the maximum, search for a value and add everything up, counting one operation per element, then see how n compares with log n and n².

Operations

Find maximum

Find the largest value in the unsorted array [3, 7, 2, 9, 4, 1, 8, 5]. The maximum could be anywhere, so every element must be looked at.

Step 1 of 10

Start: max = arr[0] = 3

  1. 30max
  2. 71
  3. 22
  4. 93
  5. 44
  6. 15
  7. 86
  8. 57
max = 3ops = 0

The array is not sorted, so nothing tells us where the largest value sits. Take the first element as the best so far: max = 3. No comparisons yet, ops = 0.

Step 1: Start: max = arr[0] = 3

def find_max(arr):    if not arr:        raise ValueError("empty array")    max_val = arr[0]          # best so far    ops = 0    for i in range(1, len(arr)):        ops += 1        if arr[i] > max_val:  # one O(1) comparison per element            max_val = arr[i]    return max_val, ops
Time
O(n)
Space
O(1)
comparisons
exactly n - 1 = 7
sort first
O(n log n): slower

Start max at arr[0], not 0: an array of all negative numbers would otherwise report 0, a value that is not even in the array.

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Starting max at 0

    critical

    If every value is negative, nothing beats 0 and the function returns 0, which is not in the array. Start from the first element, or from negative infinity.

    Wrong
    max_val = 0for x in [-4, -9, -2]:    if x > max_val:        max_val = x      # never runs: returns 0
    Right
    max_val = arr[0]          # or float("-inf")for x in arr[1:]:    if x > max_val:        max_val = x      # returns -2
  • Giving up after the first mismatch

    critical

    An else branch inside the loop returns -1 as soon as one cell does not match, so only index 0 is ever checked. The not-found answer belongs after the loop.

    Wrong
    for i in range(len(arr)):    if arr[i] == target:        return i    else:        return -1        # stops after one check
    Right
    for i in range(len(arr)):    if arr[i] == target:        return ireturn -1                # only after all n checks
  • A list lookup hidden inside a loop

    critical

    x in some_list scans the list, so it is O(n) itself. Inside a loop over n items that is O(n²). A set or dict answers membership in O(1) on average.

    Wrong
    seen = []for x in items:    if x in seen:        # O(n) scan each time        return x    seen.append(x)
    Right
    seen = set()for x in items:    if x in seen:        # O(1) average        return x    seen.add(x)
  • Sorting just to find the maximum

    major

    Sorting costs O(n log n) to answer a question one pass answers in O(n). Use max() or a single loop.

    Wrong
    biggest = sorted(scores)[-1]   # O(n log n)
    Right
    biggest = max(scores)          # O(n), one pass
  • Inserting at the front of a list in a loop

    major

    list.insert(0, x) and list.pop(0) shift every other element, so each is O(n) and the loop becomes O(n²). Append and reverse once, or use collections.deque.

    Wrong
    out = []for x in data:    out.insert(0, x)     # shifts the whole list
    Right
    out = []for x in data:    out.append(x)        # O(1) amortisedout.reverse()            # one O(n) pass
  • Building a string with += in a loop

    minor

    Strings are immutable, so += may copy the whole string each time, which can make the loop O(n²). Collect the parts and join them once.

    Wrong
    s = ""for word in words:    s += word + " "
    Right
    s = " ".join(words)  # one O(n) pass

Interview tips

  • How to explain it

    • O(n) means the work grows in direct proportion to the input: double the input, double the time.
    • Each element is visited once, or a constant number of times.
    • If the work inside a single loop is O(1), the whole loop is O(n).
    • Constants drop: 3n + 5, n - 1 and n / 2 are all O(n).
  • Spot it in code

    • `for x in arr:` or `for i in range(n):` with O(1) work inside.
    • Two pointers that only move toward each other: `while left < right`.
    • A hash map pass: `seen = {}` then `if x in seen` for each element.
    • Built-ins that read everything: `sum`, `max`, `min`, `list.count`, `x in list`.
  • Memory tricks

    • N = Navigate through N items, one by one.
    • The hallway walk: you check each door once and cannot skip any.
    • Roll call, counting coins, cleaning every room: each item once.
    • Two passes, three passes, still O(n): constants do not count.
  • Watch out

    • A hidden O(n) call inside the loop (`in` on a list, `index`, `insert(0, x)`) makes it O(n²).
    • Best case O(1) for linear search is not the complexity you quote; give the worst case.
    • O(n) is optimal only when every element must be read; on sorted data a search can be O(log n).