O(n) linear time
easy 13 minO(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
- 30max
- 71
- 22
- 93
- 44
- 15
- 86
- 57
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
criticalIf 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.
Wrongmax_val = 0for x in [-4, -9, -2]: if x > max_val: max_val = x # never runs: returns 0Rightmax_val = arr[0] # or float("-inf")for x in arr[1:]: if x > max_val: max_val = x # returns -2Giving up after the first mismatch
criticalAn 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.
Wrongfor i in range(len(arr)): if arr[i] == target: return i else: return -1 # stops after one checkRightfor i in range(len(arr)): if arr[i] == target: return ireturn -1 # only after all n checksA list lookup hidden inside a loop
criticalx in some_listscans 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.Wrongseen = []for x in items: if x in seen: # O(n) scan each time return x seen.append(x)Rightseen = set()for x in items: if x in seen: # O(1) average return x seen.add(x)Sorting just to find the maximum
majorSorting costs O(n log n) to answer a question one pass answers in O(n). Use max() or a single loop.
Wrongbiggest = sorted(scores)[-1] # O(n log n)Rightbiggest = max(scores) # O(n), one passInserting at the front of a list in a loop
majorlist.insert(0, x)andlist.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.Wrongout = []for x in data: out.insert(0, x) # shifts the whole listRightout = []for x in data: out.append(x) # O(1) amortisedout.reverse() # one O(n) passBuilding a string with += in a loop
minorStrings are immutable, so += may copy the whole string each time, which can make the loop O(n²). Collect the parts and join them once.
Wrongs = ""for word in words: s += word + " "Rights = " ".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).