Data structures and algorithms (DSA) is the study of how to organise data and solve problems efficiently. The first skill isn't a data structure — it's measuring cost. Big-O notation describes how an algorithm's work grows as the input grows, so you can tell a solution that scales from one that collapses on real data. This is also the language of coding interviews.
Why complexity matters
On 10 items, almost anything is fast. On 10 million, the difference between a linear scan and a nested loop is milliseconds versus hours. We care about the trend, not the exact time — hardware varies, but growth doesn't.
Big-O notation
Big-O describes the worst-case growth, dropping constants and lower-order terms. A loop over n items is O(n); a loop inside a loop is O(n²):
# O(1) — constant: one step regardless of ndef first(items): return items[0]# O(n) — linear: work grows with ndef total(items):s = 0for x in items: # n iterationss += xreturn s# O(n^2) — quadratic: nested loop over ndef has_duplicate(items):for i in range(len(items)):for j in range(i + 1, len(items)):if items[i] == items[j]:return Truereturn False
The common classes
| Big-O | Name | Example |
|---|---|---|
O(1) | Constant | Hash-map lookup, array index |
O(log n) | Logarithmic | Binary search |
O(n) | Linear | Single loop / scan |
O(n log n) | Linearithmic | Efficient sorts (merge, quick) |
O(n²) | Quadratic | Nested loops |
O(2ⁿ) | Exponential | Naive recursion over subsets |
Space complexity
The same idea applies to memory. An algorithm that builds a new list of size n is O(n) space; one that works in place with a few variables is O(1). Interviews often ask you to trade one for the other.
Practice
For each: state the time complexity. (1) Summing a list. (2) Checking if a list contains duplicates with a nested loop. (3) The same check using a set. Notice how the set version drops from O(n²) to O(n).
Key takeaways
- 01DSA is about solving problems efficiently; Big-O measures how work grows with input size.
- 02Big-O captures worst-case growth, dropping constants and lower-order terms.
- 03Know the ladder: O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ).
- 04Nested loops multiply; halving the search space each step is O(log n).
- 05Space complexity measures extra memory — often traded against time.
