Data Structures & Algorithms COURSE·LESSON 02 OF 1710 completed

Big O, Space, and Input Constraints

Goal: Estimate whether an algorithm fits before implementing it.

Big O describes how work grows as input size grows, ignoring machine-specific constants. If one pass does c operations per item, the work is O(n). Two nested passes over n items are O(n²); sorting followed by a scan is O(n log n). A binary search is O(log n) because each step halves the remaining range.

Count the work

  • Sequential blocks add: O(n)+O(n log n) simplifies to O(n log n).
  • Nested loops multiply when both ranges scale with input: O(n·m).
  • A hash operation is expected O(1), not a universal worst-case guarantee.
  • Recursive stack depth is space: a balanced tree is O(log n), a skewed tree O(n).
  • Report auxiliary space separately from required output. Returning n results still requires O(n) output storage.

Translate constraints into a design hint

Very large n rules out quadratic work; a small fixed alphabet may allow a frequency array; a sorted array invites binary search or two pointers; a value range of [1,n] may expose index/cycle structure. Constraints are part of the algorithm.

Interview checklist

Say: “The sort costs O(n log n), then the sweep is O(n), so total time is O(n log n). The output is O(n); the algorithm itself uses O(1) extra state.” Be precise about expected hash costs, recursion, and mutation.

Quick examples

| Operation | Complexity | |---|---| | Read an array element by index | O(1) | | Search an unsorted array | O(n) | | Insert into a hash set, expected | O(1) | | Sort n values | O(n log n) | | Explore every subset | O(2ⁿ) |

Learn at your own pace0 / 171 lessons complete