Course contents

Collections in action: interview questions & scenarios

Premium12 questions · 12 what-if follow-ups

These are the collections-in-action questions I ask when I want to know whether you can turn a problem statement into the right data structure. The class names matter, but the real signal is whether you can explain the invariant, the output contract and the trade-off while you code.

Use this page like a mock interview: read the question, say your answer out loud first, then open the model answer. If a pattern feels slippery, go back to the 7 patterns at a glance, frequency counting and deduplication, grouping and partitioning, Top-K with a heap, stack algorithms with ArrayDeque and range queries with TreeMap.

Question 1. ScenarioCoreAsked very often

For these three prompts, which collection pattern would you reach for and why?

Tests pattern recognition, data-structure choice, trade-offs

Show answerHide answer1 follow-up

Model answer

For the first prompt, I hear frequency counting plus order. Count each product ID in a Map<String, Integer>, and keep first-seen order with a LinkedHashMap or a separate ordered list. After the scan, return the first key whose count is 1.

For the second prompt, I hear Top-K. Keep a size-20 min-heap with PriorityQueue<Request> ordered by latency. The root is the smallest latency among the current winners, so a slower request can evict it in O(log k).

For the third prompt, I hear range query over intervals. Store bookings in a TreeMap<Integer, Integer> from start to end. Check floorEntry(start) for the previous interval and ceilingEntry(start) for the next interval. Only those two neighbors can overlap the new interval.

How I’d say it in the interview

"I would translate each prompt into the operation. First unique is counting plus first-seen order. Twenty slowest is Top-K, so a bounded heap beats full sorting when the input is large. Calendar booking is ordered-neighbor lookup, so I want TreeMap and its floor and ceiling methods."

Signals depth

Separating the pattern from the collection. HashMap, PriorityQueue and TreeMap are not magic answers; each one makes a specific operation cheap.

Red flags

Starting every prompt with "I'll use a map" without saying what the key means, what the value means, or whether order matters.

Follow-ups interviewers ask next

  1. What if the latency input has only 50 samples?

    For 50 samples, I would probably sort unless the interviewer is explicitly testing heap mechanics. The heap wins when n is large and k is small; otherwise, readable code matters more.

Question 2. CodingCoreAsked very often

Write firstNonRepeatingChar(String s) for lowercase English letters.

Tests frequency counting, arrays, two-pass scan

Show answerHide answer1 follow-up

Model answer

For lowercase English letters, an int[26] is the cleanest tool. Count in one pass, then scan again and return the first character whose count is 1.

final class FirstNonRepeatingCharDemo {
    static char firstNonRepeatingChar(String s) {
        int[] counts = new int[26];
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            counts[ch - 'a']++;
        }

        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (counts[ch - 'a'] == 1) {
                return ch;
            }
        }
        return '\0';
    }

    public static void main(String[] args) {
        System.out.println(firstNonRepeatingChar("swiss")); // w
    }
}

This is O(n) time and O(1) extra space because the alphabet size is fixed at 26. If returning a sentinel feels unclear, use OptionalInt or return the index instead.

How I’d say it in the interview

"Because the input is lowercase English letters, I do not need a hash map. I count with 26 counters, then make a second pass to preserve the original order when choosing the answer."

Signals depth

Calling out why one pass is not enough if you only keep counts: the answer depends on first occurrence order, so the second scan is intentional.

Red flags

Sorting the characters, because sorting destroys the position of the first non-repeating character.

Follow-ups interviewers ask next

  1. What if the input can contain any Unicode character?

    Switch to code points and a LinkedHashMap<Integer, Integer> or another structure that preserves first-seen order. A Java char is a UTF-16 code unit, not always a full user-visible character.

Question 3. CodingCoreAsked very often

Given a list of words, group the anagrams together.

Tests grouping, canonical key, hash map

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 4. CodingCoreAsked very often

Return the top K frequent integers. How does your heap solution compare with bucket sort?

Tests frequency map, bounded heap, bucket sort trade-off

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 5. ConceptCoreCommonly asked

Kth largest element: when would you choose a min-heap over quickselect?

Tests heap, quickselect, mutation, streaming

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 6. CodingCoreAsked very often

Walk through valid parentheses and write the Java code.

Tests ArrayDeque stack, invariant, malformed input

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 7. CodingCoreAsked very often

Solve daily temperatures with a monotonic stack.

Tests monotonic stack, indexes, amortized O(n)

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 8. CodingSeniorCommonly asked

Implement MyCalendar.book(start, end) with a TreeMap.

Tests TreeMap, floorEntry, ceilingEntry, interval overlap

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 9. DesignSeniorCommonly asked

Design an event store that returns events from the last five minutes.

Tests sliding window, TreeMap, duplicate timestamps, cleanup

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 10. What does it print?CoreCommonly asked

What does this PriorityQueue code print, and why is the order surprising?

Tests heap order, iteration order, poll order

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 11. What does it print?CoreCommonly asked

What does groupingBy with TreeMap::new and counting() produce?

Tests groupingBy, map supplier, counting result type

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 12. DebuggingCoreCommonly asked

A HashSet<Customer> did not deduplicate customers with the same email. How do you debug it without changing equals and hashCode?

Tests deduplication, custom objects, equality key

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Premium question set

Keep reading with the Java Pass

The rest of this question set is part of Java One-Stop Interview Prep: in-depth explanations, diagrams, model answers and how to say them in the interview.

From ₹199 · one-time payment · No auto-renewal

Lessons in Collections in action