Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Efficiency & Big-O — Measuring Speed From Zero

Give an example where choosing the right data structure changes the Big-O.

Level II · JuniorEfficiency & Big-O — Measuring Speed From Zero
Short answer

Checking membership: `ArrayList.contains` scans the list, so doing it inside a loop is O(n^2); switching to a `HashSet`, whose contains is O(1) average, makes the same task O(n).

Explanation

Likewise, searching an unsorted array is O(n) but binary search on a SORTED array is O(log n). The algorithm's complexity often comes down to which structure you store the data in, not how tightly you write the loop.

Common mistakes
  • Giving an example without naming both complexities.
  • Forgetting the trade-off of extra memory for a HashSet.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Efficiency & Big-O — Measuring Speed From Zero.

Practise free

More on Efficiency & Big-O — Measuring Speed From Zero