Practice: analyse real code
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
In an interview, saying 'O(n log n)' without an explanation sounds like a guess. This practice lesson trains you to read real Java snippets—including tricky look-alike loops—and justify both time and space complexity in two clear sentences.
Ten snippets to analyse (Snippets 1–5: single, nested, and halving)
Work through the first five classic snippets before looking at the summary bullets below (shown after the code).
Example 1 · Proving Snippet 5 (geometric loop) and Snippet 6 (monotonic pointer) are O(n)
public class TrickyLinearSnippetsDemo { // Snippet 5: i doubles (1, 2, 4, ..., n), inner j runs i times. // Total inner steps = 1 + 2 + 4 + ... + n = 2n - 1 -> O(n)! public static int geometricInnerLoop(int n) { int steps = 0; for (int i = 1; i <= n; i *= 2) { for (int j = 0; j < i; j++) { steps++; } } return steps; }
// Snippet 6: j is initialized ONCE outside the for loop and only increments. // j++ runs at most n times across the entire method -> O(n)! public static int monotonicTwoPointerLoop(int n) { int j = 0; int innerSteps = 0; for (int i = 0; i < n; i++) { while (j < i) { j++; innerSteps++; } } return innerSteps; }
public static void main(String[] args) { System.out.println("Geometric steps (n=64) : " + geometricInnerLoop(64) + " (< 2n)"); System.out.println("Geometric steps (n=512) : " + geometricInnerLoop(512) + " (< 2n)"); System.out.println("Monotonic j++ (n=512) : " + monotonicTwoPointerLoop(512) + " (<= n)"); }}Geometric steps (n=64) : 127 (< 2n) Geometric steps (n=512) : 1023 (< 2n) Monotonic j++ (n=512) : 511 (<= n)
What this code does
- In
geometricInnerLoop(512),1 + 2 + 4 + ... + 512equals1,023(2n - 1), which is linearO(n), notO(n log n). - In
monotonicTwoPointerLoop(512), even though awhileloop sits inside aforloop,jnever resets, soj++runs only511times in total (O(n)).
- Snippet 2 (
i * i <= n): Used when checking divisors or primes up to √n. - Snippet 4 vs Snippet 5: In Snippet 4, the inner loop runs
log ntimes for each ofnouter steps (O(n log n)). In Snippet 5, the outer loop runslog ntimes and the inner loop sum is1 + 2 + 4 + ... + n < 2n(O(n)).
Snippet 1 (Constant cap): for (int i = 0; i < Math.min(n, 50); i++) runs at most 50 times -> O(1) time, O(1) space. Snippet 2 (Sqrt loop): for (int i = 1; i * i <= n; i++) stops when i = √n -> O(√n) time, O(1) space. Snippet 3 (Dependent triangle): for (i = 0..n-1) for (j = i..n-1) runs n(n+1)/2 times -> O(n²) time, O(1) space. Snippet 4 (Linear + halving): for (i = 0..n-1) for (j = 1; j < n; j *= 2) runs n × log₂(n) times -> O(n log n) time, O(1) space. Snippet 5 (Geometric series trap): for (int i = 1; i <= n; i *= 2) for (int j = 0; j < i; j++) runs 1 + 2 + 4 + … + n < 2n times in total -> O(n) time, NOT O(n log n)!
Ten snippets to analyse (Snippets 6–10: two pointers, library calls, recursion)
In Snippets 6 to 10, hidden library costs and pointer movements decide the answer, so count what each call and each pointer really does, not just the loops. Snippet 7 is the classic trap: one visible loop, with a hidden loop inside contains.
int[] nums = {4, 1, 4, 2, 1};List<Integer> list = new ArrayList<>();for (int x : nums) { if (!list.contains(x)) list.add(x); // contains scans the list: O(n) per call}// one loop, but O(n) work inside it -> O(n²) time, O(n) spaceSnippet 6 (Monotonic inner pointer): int j = 0; for (int i = 0; i < n; i++) { while (j < n && cond) j++; }. Because j is never reset to 0, j++ can execute at most n times across the entire method -> O(n) time, O(1) space! Snippet 7 (Hidden ArrayList.contains): for (int x : nums) if (!list.contains(x)) list.add(x); -> O(n²) worst-case time, O(n) space.
Snippet 8 (Sorting + two pointers): Arrays.sort(copy); while (left < right) ... -> O(n log n) time, O(n) space for copy. Snippet 9 (Halving recursion): f(n) { return f(n / 2); } -> O(log n) time, O(log n) stack space. Snippet 10 (Branching recursion): f(n) { return f(n - 1) + f(n - 1); } -> O(2ⁿ) time, but only O(n) stack space (max call depth is n).
- Snippet 6 (Monotonic
j): Whenever an inner pointer only moves forward and never resets, count the total number of timesj++can happen across the whole run (<= n). - Snippet 10 (Branching recursion): Time is total nodes in the call tree (
2^n), while stack space is the height of the tree (n).
Comparing two solutions to one problem
When two working solutions exist for the same problem, compare them across four dimensions: time complexity, extra space complexity, whether the input is mutated, and which constraint range each one fits.
Example 2 · Brute force: check every pair for a close pair (O(n²) time, O(1) space)
public class ClosePairBruteDemo { // Time: O(n^2) | Extra Space: O(1) | Good when n <= 2,000 public static boolean hasClosePairBrute(int[] nums, long d) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (Math.abs((long) nums[i] - nums[j]) <= d) { return true; } } } return false; }
public static void main(String[] args) { int[] arr = {50, 10, 90, 13}; System.out.println("Brute (d=3) : " + hasClosePairBrute(arr, 3)); System.out.println("Brute (d=1) : " + hasClosePairBrute(arr, 1)); }}Brute (d=3) : true Brute (d=1) : false
What this code does
- Solution A tries every pair of positions, so it uses no extra array memory (O(1)) but takes O(n²) time.
- It is fine for n up to about 2,000 and too slow beyond that.
Example 3 · Optimal: sort a copy and check neighbours (O(n log n) time, O(n) space)
import java.util.Arrays;
public class ClosePairSortedDemo { // Time: O(n log n) | Extra Space: O(n) for the copy | Good when n <= 100,000 public static boolean hasClosePairSorted(int[] nums, long d) { if (nums.length < 2) { return false; } int[] copy = Arrays.copyOf(nums, nums.length); Arrays.sort(copy); for (int i = 1; i < copy.length; i++) { if ((long) copy[i] - copy[i - 1] <= d) { return true; } } return false; }
public static void main(String[] args) { int[] arr = {50, 10, 90, 13}; System.out.println("Sorted (d=3): " + hasClosePairSorted(arr, 3)); System.out.println("Sorted (d=1): " + hasClosePairSorted(arr, 1)); }}Sorted (d=3): true Sorted (d=1): false
What this code does
- Solution B pays O(n) extra space for a sorted copy and brings the time down to O(n log n), which scales to n = 100,000.
- It is faster because after sorting, the closest pair must be neighbours, so one pass over n - 1 neighbours replaces checking all pairs.
Example 4 · Sqrt(n) divisor counting vs O(n) divisor counting
public class SqrtDivisorComparisonDemo { // Solution A: check every d from 1..n -> O(n) time, O(1) space public static int countDivisorsLinear(int n) { int count = 0; for (int d = 1; d <= n; d++) { if (n % d == 0) { count++; } } return count; }
// Solution B: check d only up to sqrt(n); each divisor d < sqrt(n) pairs with n / d! // Time: O(sqrt(n)) | Extra Space: O(1) public static int countDivisorsSqrt(int n) { int count = 0; for (int d = 1; (long) d * d <= n; d++) { if (n % d == 0) { if (d * d == n) { count += 1; // perfect square root (e.g. 6 * 6 = 36) counts once } else { count += 2; // both d and (n / d) are divisors } } } return count; }
public static void main(String[] args) { System.out.println("Divisors of 36 (Linear): " + countDivisorsLinear(36)); System.out.println("Divisors of 36 (Sqrt) : " + countDivisorsSqrt(36)); System.out.println("Divisors of 10^9 (Sqrt): " + countDivisorsSqrt(1_000_000_000)); }}Divisors of 36 (Linear): 9 Divisors of 36 (Sqrt) : 9 Divisors of 10^9 (Sqrt): 100
What this code does
- For
n = 1,000,000,000,countDivisorsLineartakes1,000,000,000steps, whereascountDivisorsSqrtstops at √(10⁹) ≈ 31,622 steps! - Watch the edge case on perfect squares (
36): whend * d == n(6 * 6 == 36),dandn / dare the same number, so we add1, not2.
- Always state what you gain and what you pay when moving from Solution A to Solution B.
- Mention whether sorting in place would drop Solution B's extra space to
O(log n)at the cost of mutating the caller's array.
For example, to check whether an array contains two numbers within distance d of each other (|nums[i] - nums[j]| <= d), Solution A checks all pairs in O(n²) time and O(1) space without touching the input. Solution B sorts a copy and checks adjacent elements in O(n log n) time and O(n) space. For n <= 500, both pass; for n = 100,000, only Solution B passes.
Explaining your answer interview-style
Never answer a complexity question with a bare label like 'O(n)'. Use a two-sentence interview formula: in Sentence 1, state the time complexity and name the loop or operation that drives it; in Sentence 2, state the extra space complexity and name the data structures or stack depth allocated.
For example: "The time complexity is O(n) on average because we iterate through the n-element array once and perform an O(1) average-time HashSet lookup on each element. The extra space complexity is O(n) because the HashSet stores up to n unique elements in the worst case."
- Sentence 1 (Time): 'The time complexity is O(...) because [how many times the dominant loop/call runs and how much work each step does].'
- Sentence 2 (Space): 'The extra space complexity is O(...) because [which arrays, collections, or recursive stack frames are allocated].'
Finish up
Mark complete & continue
Next: Why test your own code