Video in progress
Give a Java example for each of O(1), O(log n), O(n) and O(n²).
O(1) is HashMap.get or reading an array by index; O(log n) is binary search; O(n) is one pass over a list; O(n²) is a nested loop that compares every element with every other.
📖 Answer
int x = arr[5]; // O(1) — doesn't depend on n
int i = Arrays.binarySearch(sorted, 42);// O(log n) — half is thrown away at each step
long sum = 0;
for (int v : arr) sum += v; // O(n)
for (int a = 0; a < n; a++) // O(n²)
for (int b = 0; b < n; b++)
if (arr[a] == arr[b] && a != b) dup = true;
Numbers to get a feel for it: with n = 1,000,000, log₂n ≈ 20 while n² is 10¹². The first three finish instantly, and the last one effectively never finishes.
Two more that come up often: O(n log n) is a good sort (Arrays.sort), and O(2ⁿ) is enumerating all subsets. The second one gets heavy already at n = 40.
Sign up to mark studied questions and save your progress.