Java Toolkit for DSA

Beginner · 14 min read · DSA Without Fear, The Toolkit

The collections and idioms you will use in every problem, and the pitfalls that cost marks.

You don't need all of Java for DSA — about a dozen classes and twenty methods cover nearly every interview problem. Knowing them well means you think about the algorithm, not the syntax. This lesson is that toolkit, plus the Java pitfalls that make correct ideas fail on hidden test cases.

Which structure for which job

The idioms you'll write constantly

Arrays.sort on primitives uses a dual-pivot quicksort (O(n log n) on average, not stable — stability doesn't matter for primitives); on objects it uses TimSort (O(n log n) worst case, stable).

The pitfalls that fail hidden tests

This bites when comparing values pulled from a Map<Integer, Integer> or a List<Integer>: the code passes small tests and fails large ones. Unbox first (int x = map.get(k);) or use .equals.

Interview questions

  • Why does 'Integer a = 1000, b = 1000; a == b' print false?
  • When would you use a TreeMap instead of a HashMap?

Further reading

Key takeaways

  • ArrayList, ArrayDeque, HashMap, HashSet, TreeMap/TreeSet, PriorityQueue and plain arrays cover almost every problem.
  • Know the idioms: merge for counting, computeIfAbsent for grouping, adjacency lists, int[26] for letters.
  • Compare boxed values with equals; use long for big sums and Integer.compare in comparators.
  • Watch negative %, modifying collections while iterating, and copying lists before storing them.

Previous: Recursion Without Fear