Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • About
  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: 8+ Years (Senior & Lead)

Revise the 5–8 Years Tier

  • Revise: Advanced Core Java & Design Patterns (5–8 Years Tier)
  • Revise: Spring Boot Internals & Spring Security (5–8 Years Tier)
  • Revise: Microservices & Microservice Patterns (5–8 Years Tier)

Expert Core Java

  • Tricky Java Output, Operators & OOP Edge Cases — Interview Questions
  • Tricky Exceptions, Memory & Keyword Questions — Interview Questions
  • Classic Java Language Questions, Senior-Grade Answers — Interview Questions
  • Classic Collections, Threads & JDK APIs, Senior-Grade Answers — Interview Questions
  • Reflection, Dynamic Proxies, final & Modern OOP Design — Interview Questions

JVM Internals & Performance

  • Class Loading, Bytecode & Object Layout — Interview Questions
  • JIT Compilation & Runtime Optimisations — Interview Questions
  • Garbage Collectors Deep Dive — Interview Questions
  • JVM Tuning, GC Logs & Memory Footprint — Interview Questions
  • Memory Leaks, OutOfMemoryErrors & Profiling Tools — Interview Questions
  • Modules, Agents & Advanced JVM APIs — Interview Questions

Collections & Concurrency at Scale

  • Collections Internals & Complexity — Interview Questions
  • Iterators, Comparators & Ordering Contracts — Interview Questions
  • Concurrent Collections, Queues & Lock-Free Structures — Interview Questions
  • Threads, Executors & ForkJoin Internals — Interview Questions
  • Locks, Atomics, CAS & Synchronizers — Interview Questions
  • Java Memory Model, volatile, Fences & ThreadLocal — Interview Questions
  • Deadlock, Livelock, Starvation & Concurrent Design — Interview Questions
  • CompletableFuture, Parallel Streams & Non-Blocking I/O — Interview Questions

Modern Java (8 to 21+)

  • Lambdas & Functional Interfaces Internals — Interview Questions
  • Streams & Collectors Deep Dive — Interview Questions
  • Optional & Interface Default/Static Methods — Interview Questions
  • Java 9–25 Features & Virtual Threads — Interview Questions

Design Patterns, SOLID & Clean Code

  • Design Pattern Trade-offs & Combinations — Interview Questions
  • SOLID, Clean Code & Anti-Patterns — Interview Questions

Spring & Spring Boot Internals

  • IoC, Dependency Injection & Bean Lifecycle Internals — Interview Questions
  • Spring AOP, Proxies & @Async Internals — Interview Questions
  • Spring Configuration, Auto-Configuration & Custom Starters — Interview Questions
  • Spring MVC & REST Internals, Exception Frameworks — Interview Questions
  • Spring Security Advanced Internals — Interview Questions
  • Spring WebFlux, Reactor & R2DBC — Interview Questions
  • Spring Cloud, Observability & Distributed Tracing — Interview Questions
  • Spring Boot 3, Native Images & Production Scenarios — Interview Questions

JPA, Hibernate & Databases at Scale

  • Spring Data JPA — Queries, Projections, Custom Repositories & Locking — Interview Questions
  • JPA Entity Mapping, Associations & Cascades — Interview Questions
  • JPQL vs Native Queries in Depth — Interview Questions
  • Hibernate Caching — First-Level, Second-Level & Query Cache — Interview Questions
  • Lazy vs Eager Loading, LazyInitializationException & N+1 — Interview Questions
  • JPA Transactions, Propagation, Isolation & Dirty Checking — Interview Questions
  • SQL vs NoSQL, Indexing & Query Tuning — Interview Questions
  • Database Scaling, Replication, Pooling & Consistency Models — Interview Questions
  • Redis, Search, Time-Series, CDC & Transactional Data Modelling — Interview Questions

Testing Strategy & API Design

  • Spring Boot Test Slices, Context & Test Strategy — Interview Questions
  • Testing Web, Persistence, Security, Async & Messaging in Spring Boot — Interview Questions
  • JUnit 5 & Mockito, Advanced — Interview Questions
  • MockMvc, WebTestClient & Testcontainers in Depth — Interview Questions
  • REST Principles, Status Codes & Resource Design — Interview Questions
  • OpenAPI, Validation Errors, API Versioning & GraphQL — Interview Questions

Build, DevOps & Cloud

  • Maven & Gradle at Scale — Interview Questions
  • Git, CI/CD Pipelines & Release Safety — Interview Questions
  • Docker & Kubernetes for Java Engineers — Interview Questions
  • Quality Gates, Artifact Repositories & Secrets Management — Interview Questions
  • AWS Deployment & Scaling for Spring Boot — Interview Questions
  • Multi-Cloud Deployment, High Availability, Cost & Cloud Troubleshooting — Interview Questions
  • Protocols, Supply-Chain Security, SRE Metrics & Platform Engineering — Interview Questions

Kafka & Messaging

  • Kafka Internals & Delivery Semantics — Interview Questions
  • Spring Kafka — Error Handling, DLQs, Schemas & Operations — Interview Questions
  • RabbitMQ, JMS & Messaging Models — Interview Questions

Microservices & Architecture

  • Distributed Systems Fundamentals — CAP, Consistency, Availability & SLOs — Interview Questions
  • DDD, Hexagonal Architecture & Service Boundaries — Interview Questions
  • Event-Driven Architecture, CQRS, Event Sourcing, Sharding & Idempotency — Interview Questions
  • Rate Limiting, Resilience, Caching at Scale & Chaos Engineering — Interview Questions
  • Files, Documents & Internationalisation in Java Backends — Interview Questions
  • WebSockets, Schedulers, Notifications & Real-Time Pipelines — Interview Questions

System Design Scenarios

  • Booking Systems, CRS, Inventory & Concurrency Control — Interview Questions
  • Dynamic Pricing & Rule Engines — Interview Questions
  • Partner Integrations — OTA Sync, Retries, Webhooks, Reconciliation & Bulk Data — Interview Questions
  • Designing Caches & Rate Limiters — Interview Questions
  • Event-Driven Architecture, Kafka at Scale, IoT & Real-Time Pipelines — Interview Questions
  • Observability, Logging, Alerting & Audit Systems — Interview Questions
  • Multi-Tenant SaaS, Identity & Platform Services — Interview Questions
  • Search, Notifications, Chat, Fraud Detection & Workflows — Interview Questions
  • Extreme Scale, 99.99% Availability, DR & Project Deep-Dive Stories — Interview Questions

Security for Senior Engineers

  • Tokens, OAuth2 PKCE, Web Attacks & API Security — Interview Questions
  • TLS, mTLS, Zero Trust, Secrets, DDoS & Privacy Compliance — Interview Questions

AI & LLM Integration

  • LLM Integration in Java — Spring AI, Bedrock, Prompts, Streaming & Orchestration — Interview Questions
  • RAG, Embeddings, Vector Databases & Conversational Memory — Interview Questions
  • AI Security, Guardrails, Cost & Operations — Interview Questions

DSA Coding Round

  • Array Problems — Rotation, Subarrays, Intervals, In-Place Tricks — Interview Questions
  • String Problems & Sliding Window — Interview Questions
  • Backtracking & Recursion — Interview Questions
  • Linked Lists, LRU & LFU Caches — Interview Questions
  • Stacks, Queues & Monotonic Stacks — Interview Questions
  • Binary Trees & BSTs — Interview Questions
  • Graph Algorithms — Interview Questions
  • Dynamic Programming — Interview Questions
  • Heaps & Greedy Algorithms — Interview Questions
  • Bit Manipulation & Math — Interview Questions
  • Concurrency Coding Round — Thread Pool, Blocking Queue, Latch, Future, File Processor — Interview Questions
  • Low-Level Design (Machine Coding) Problems — Interview Questions

Leadership & Behavioural

  • Leadership Style, Motivation & Team Health — Interview Questions
  • Delivery, Planning & Decisions Under Uncertainty — Interview Questions
  • Problem Solving, Growth & Career Stories — Interview Questions
  • Stakeholder Communication, Ethics & Compliance — Interview Questions
  • Mentoring, Knowledge Sharing & Code Reviews — Interview Questions
  • Agile & Scrum Practices for Senior Engineers — Interview Questions
  • Architecture Decision-Making — Interview Questions
  • Conflict Resolution & Difficult Conversations — Interview Questions
Chaturmind
← Java Interview Prep: 8+ Years (Senior & Lead)

Revise the 5–8 Years Tier

  • Revise: Advanced Core Java & Design Patterns (5–8 Years Tier)
  • Revise: Spring Boot Internals & Spring Security (5–8 Years Tier)
  • Revise: Microservices & Microservice Patterns (5–8 Years Tier)

Expert Core Java

  • Tricky Java Output, Operators & OOP Edge Cases — Interview Questions
  • Tricky Exceptions, Memory & Keyword Questions — Interview Questions
  • Classic Java Language Questions, Senior-Grade Answers — Interview Questions
  • Classic Collections, Threads & JDK APIs, Senior-Grade Answers — Interview Questions
  • Reflection, Dynamic Proxies, final & Modern OOP Design — Interview Questions

JVM Internals & Performance

  • Class Loading, Bytecode & Object Layout — Interview Questions
  • JIT Compilation & Runtime Optimisations — Interview Questions
  • Garbage Collectors Deep Dive — Interview Questions
  • JVM Tuning, GC Logs & Memory Footprint — Interview Questions
  • Memory Leaks, OutOfMemoryErrors & Profiling Tools — Interview Questions
  • Modules, Agents & Advanced JVM APIs — Interview Questions

Collections & Concurrency at Scale

  • Collections Internals & Complexity — Interview Questions
  • Iterators, Comparators & Ordering Contracts — Interview Questions
  • Concurrent Collections, Queues & Lock-Free Structures — Interview Questions
  • Threads, Executors & ForkJoin Internals — Interview Questions
  • Locks, Atomics, CAS & Synchronizers — Interview Questions
  • Java Memory Model, volatile, Fences & ThreadLocal — Interview Questions
  • Deadlock, Livelock, Starvation & Concurrent Design — Interview Questions
  • CompletableFuture, Parallel Streams & Non-Blocking I/O — Interview Questions

Modern Java (8 to 21+)

  • Lambdas & Functional Interfaces Internals — Interview Questions
  • Streams & Collectors Deep Dive — Interview Questions
  • Optional & Interface Default/Static Methods — Interview Questions
  • Java 9–25 Features & Virtual Threads — Interview Questions

Design Patterns, SOLID & Clean Code

  • Design Pattern Trade-offs & Combinations — Interview Questions
  • SOLID, Clean Code & Anti-Patterns — Interview Questions

Spring & Spring Boot Internals

  • IoC, Dependency Injection & Bean Lifecycle Internals — Interview Questions
  • Spring AOP, Proxies & @Async Internals — Interview Questions
  • Spring Configuration, Auto-Configuration & Custom Starters — Interview Questions
  • Spring MVC & REST Internals, Exception Frameworks — Interview Questions
  • Spring Security Advanced Internals — Interview Questions
  • Spring WebFlux, Reactor & R2DBC — Interview Questions
  • Spring Cloud, Observability & Distributed Tracing — Interview Questions
  • Spring Boot 3, Native Images & Production Scenarios — Interview Questions

JPA, Hibernate & Databases at Scale

  • Spring Data JPA — Queries, Projections, Custom Repositories & Locking — Interview Questions
  • JPA Entity Mapping, Associations & Cascades — Interview Questions
  • JPQL vs Native Queries in Depth — Interview Questions
  • Hibernate Caching — First-Level, Second-Level & Query Cache — Interview Questions
  • Lazy vs Eager Loading, LazyInitializationException & N+1 — Interview Questions
  • JPA Transactions, Propagation, Isolation & Dirty Checking — Interview Questions
  • SQL vs NoSQL, Indexing & Query Tuning — Interview Questions
  • Database Scaling, Replication, Pooling & Consistency Models — Interview Questions
  • Redis, Search, Time-Series, CDC & Transactional Data Modelling — Interview Questions

Testing Strategy & API Design

  • Spring Boot Test Slices, Context & Test Strategy — Interview Questions
  • Testing Web, Persistence, Security, Async & Messaging in Spring Boot — Interview Questions
  • JUnit 5 & Mockito, Advanced — Interview Questions
  • MockMvc, WebTestClient & Testcontainers in Depth — Interview Questions
  • REST Principles, Status Codes & Resource Design — Interview Questions
  • OpenAPI, Validation Errors, API Versioning & GraphQL — Interview Questions

Build, DevOps & Cloud

  • Maven & Gradle at Scale — Interview Questions
  • Git, CI/CD Pipelines & Release Safety — Interview Questions
  • Docker & Kubernetes for Java Engineers — Interview Questions
  • Quality Gates, Artifact Repositories & Secrets Management — Interview Questions
  • AWS Deployment & Scaling for Spring Boot — Interview Questions
  • Multi-Cloud Deployment, High Availability, Cost & Cloud Troubleshooting — Interview Questions
  • Protocols, Supply-Chain Security, SRE Metrics & Platform Engineering — Interview Questions

Kafka & Messaging

  • Kafka Internals & Delivery Semantics — Interview Questions
  • Spring Kafka — Error Handling, DLQs, Schemas & Operations — Interview Questions
  • RabbitMQ, JMS & Messaging Models — Interview Questions

Microservices & Architecture

  • Distributed Systems Fundamentals — CAP, Consistency, Availability & SLOs — Interview Questions
  • DDD, Hexagonal Architecture & Service Boundaries — Interview Questions
  • Event-Driven Architecture, CQRS, Event Sourcing, Sharding & Idempotency — Interview Questions
  • Rate Limiting, Resilience, Caching at Scale & Chaos Engineering — Interview Questions
  • Files, Documents & Internationalisation in Java Backends — Interview Questions
  • WebSockets, Schedulers, Notifications & Real-Time Pipelines — Interview Questions

System Design Scenarios

  • Booking Systems, CRS, Inventory & Concurrency Control — Interview Questions
  • Dynamic Pricing & Rule Engines — Interview Questions
  • Partner Integrations — OTA Sync, Retries, Webhooks, Reconciliation & Bulk Data — Interview Questions
  • Designing Caches & Rate Limiters — Interview Questions
  • Event-Driven Architecture, Kafka at Scale, IoT & Real-Time Pipelines — Interview Questions
  • Observability, Logging, Alerting & Audit Systems — Interview Questions
  • Multi-Tenant SaaS, Identity & Platform Services — Interview Questions
  • Search, Notifications, Chat, Fraud Detection & Workflows — Interview Questions
  • Extreme Scale, 99.99% Availability, DR & Project Deep-Dive Stories — Interview Questions

Security for Senior Engineers

  • Tokens, OAuth2 PKCE, Web Attacks & API Security — Interview Questions
  • TLS, mTLS, Zero Trust, Secrets, DDoS & Privacy Compliance — Interview Questions

AI & LLM Integration

  • LLM Integration in Java — Spring AI, Bedrock, Prompts, Streaming & Orchestration — Interview Questions
  • RAG, Embeddings, Vector Databases & Conversational Memory — Interview Questions
  • AI Security, Guardrails, Cost & Operations — Interview Questions

DSA Coding Round

  • Array Problems — Rotation, Subarrays, Intervals, In-Place Tricks — Interview Questions
  • String Problems & Sliding Window — Interview Questions
  • Backtracking & Recursion — Interview Questions
  • Linked Lists, LRU & LFU Caches — Interview Questions
  • Stacks, Queues & Monotonic Stacks — Interview Questions
  • Binary Trees & BSTs — Interview Questions
  • Graph Algorithms — Interview Questions
  • Dynamic Programming — Interview Questions
  • Heaps & Greedy Algorithms — Interview Questions
  • Bit Manipulation & Math — Interview Questions
  • Concurrency Coding Round — Thread Pool, Blocking Queue, Latch, Future, File Processor — Interview Questions
  • Low-Level Design (Machine Coding) Problems — Interview Questions

Leadership & Behavioural

  • Leadership Style, Motivation & Team Health — Interview Questions
  • Delivery, Planning & Decisions Under Uncertainty — Interview Questions
  • Problem Solving, Growth & Career Stories — Interview Questions
  • Stakeholder Communication, Ethics & Compliance — Interview Questions
  • Mentoring, Knowledge Sharing & Code Reviews — Interview Questions
  • Agile & Scrum Practices for Senior Engineers — Interview Questions
  • Architecture Decision-Making — Interview Questions
  • Conflict Resolution & Difficult Conversations — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 8+ Years (Senior & Lead)DSA Coding Round
✓ FreeAdvanced· 12 min read

Heaps & Greedy Algorithms — Interview Questions

Java solutions for heap and greedy problems — the k-th largest element, top-K frequent elements, merging K sorted arrays, task scheduler, reorganizing a string, Huffman coding, the IPO problem, meeting rooms II, fractional knapsack, gas station, minimum platforms, connecting ropes at minimum cost, the median from a data stream, the smallest range covering K lists, and the skyline problem.

Published September 25, 2026


How to use this lesson

  • Heaps (PriorityQueue in Java, a min-heap by default) answer "repeatedly give me the smallest or largest" in O(log n) per operation. Use a size-k heap for top-K problems (O(n log k)), and two heaps for medians.
  • Greedy algorithms make the locally best choice. Always justify it (an exchange argument: swapping in a different choice can't improve the result), and know when greedy fails (0/1 knapsack, for example, needs DP).

Learn it in depth → Top K Elements

Q1. The k-th largest element.

Short answer:

  • A min-heap of size k: push each element, and pop when the size exceeds k. The top is the answer. O(n log k), and it works on streams.
  • Quickselect: average O(n), worst case O(n²) (use a random pivot).

(Practice)

int findKthLargest(int[] a, int k) {
    PriorityQueue<Integer> pq = new PriorityQueue<>();
    for (int x : a) { pq.offer(x); if (pq.size() > k) pq.poll(); }
    return pq.peek();
}

Q2. Top-K frequent elements.

Short answer: Count the frequencies in a HashMap, then either:

  • a min-heap of size k by frequency: O(n log k);
  • or bucket sort by frequency (index = frequency, at most n buckets), collecting from the highest bucket down: O(n).

(Top K Frequent Elements)

int[] topKFrequent(int[] a, int k) {
    Map<Integer, Integer> freq = new HashMap<>();
    for (int x : a) freq.merge(x, 1, Integer::sum);
    List<Integer>[] buckets = new List[a.length + 1];
    freq.forEach((x, f) -> (buckets[f] == null ? buckets[f] = new ArrayList<>() : buckets[f]).add(x));
    int[] res = new int[k]; int i = 0;
    for (int f = a.length; f > 0 && i < k; f--) if (buckets[f] != null) for (int x : buckets[f]) if (i < k) res[i++] = x;
    return res;
}

Q3. Merge K sorted arrays.

Short answer: Use a min-heap of (value, arrayIndex, elementIndex), seeded with the first element of each array. Pop the smallest, and push the next element from the same array. O(N log K).

List<Integer> mergeKSorted(int[][] arrays) {
    PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(e -> arrays[e[0]][e[1]]));
    for (int i = 0; i < arrays.length; i++) if (arrays[i].length > 0) pq.add(new int[]{i, 0});
    List<Integer> out = new ArrayList<>();
    while (!pq.isEmpty()) {
        int[] e = pq.poll(); out.add(arrays[e[0]][e[1]]);
        if (e[1] + 1 < arrays[e[0]].length) pq.add(new int[]{e[0], e[1] + 1});
    }
    return out;
}

Q4. Task scheduler (with a cooldown n).

Short answer: Use the formula:

  • Let maxF be the highest task frequency, and countMax the number of tasks with that frequency.
  • The answer is max(tasks.length, (maxF - 1) * (n + 1) + countMax): the most frequent tasks define the frames, and the idle slots fill the gaps.

O(n). (Simulation with a max-heap plus a cooldown queue also works, and returns the actual schedule.)

int leastInterval(char[] tasks, int n) {
    int[] f = new int[26]; for (char t : tasks) f[t - 'A']++;
    int maxF = Arrays.stream(f).max().getAsInt();
    int countMax = (int) Arrays.stream(f).filter(x -> x == maxF).count();
    return Math.max(tasks.length, (maxF - 1) * (n + 1) + countMax);
}

Q5. Reorganize a string (no two adjacent characters equal).

Short answer: If any character appears more than (n+1)/2 times, it's impossible. Otherwise, use a max-heap by count: repeatedly take the two most frequent characters and append them, then push them back with decremented counts. O(n log 26). (Alternative: place the most frequent character at the even indices, then fill the rest.)

String reorganizeString(String s) {
    int[] cnt = new int[26]; for (char c : s.toCharArray()) cnt[c - 'a']++;
    PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[1] - a[1]);
    for (int i = 0; i < 26; i++) if (cnt[i] > 0) {
        if (cnt[i] > (s.length() + 1) / 2) return "";
        pq.add(new int[]{i, cnt[i]});
    }
    StringBuilder sb = new StringBuilder();
    while (pq.size() >= 2) {
        int[] a = pq.poll(), b = pq.poll();
        sb.append((char) ('a' + a[0])).append((char) ('a' + b[0]));
        if (--a[1] > 0) pq.add(a); if (--b[1] > 0) pq.add(b);
    }
    if (!pq.isEmpty()) sb.append((char) ('a' + pq.poll()[0]));
    return sb.toString();
}

Q6. Huffman coding. Connecting ropes at minimum cost.

Short answer: Both use the same greedy: repeatedly combine the two smallest items (with a min-heap), and push back their sum.

  • Ropes: the cost is the sum of all the merge results.
  • Huffman: build a tree where the merged nodes become internal nodes; the codes are the paths (left = 0, right = 1). It produces an optimal prefix-free code: frequent symbols get short codes.

O(n log n). Merging the smallest first is optimal, because small items then get added into the most merges.

long connectRopes(int[] ropes) {
    PriorityQueue<Long> pq = new PriorityQueue<>();
    for (int r : ropes) pq.add((long) r);
    long cost = 0;
    while (pq.size() > 1) { long s = pq.poll() + pq.poll(); cost += s; pq.add(s); }
    return cost;
}
record HNode(char ch, int freq, HNode left, HNode right) {}
Map<Character, String> huffman(Map<Character, Integer> freq) {
    PriorityQueue<HNode> pq = new PriorityQueue<>(Comparator.comparingInt(HNode::freq));
    freq.forEach((c, f) -> pq.add(new HNode(c, f, null, null)));
    while (pq.size() > 1) { HNode a = pq.poll(), b = pq.poll(); pq.add(new HNode('\0', a.freq() + b.freq(), a, b)); }
    Map<Character, String> codes = new HashMap<>();
    assign(pq.poll(), "", codes);
    return codes;
}
void assign(HNode n, String code, Map<Character, String> codes) {
    if (n == null) return;
    if (n.left() == null && n.right() == null) { codes.put(n.ch(), code.isEmpty() ? "0" : code); return; }
    assign(n.left(), code + "0", codes); assign(n.right(), code + "1", codes);
}

Q7. The IPO problem (maximising capital with k projects).

Short answer: Sort the projects by required capital. Repeat k times:

  1. push every project you can now afford into a max-heap by profit;
  2. take the most profitable one (if the heap is empty, stop), and add its profit to your capital.

O(n log n). The greedy works because taking the largest affordable profit only ever increases what you can afford later.

int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
    Integer[] idx = new Integer[profits.length];
    for (int i = 0; i < idx.length; i++) idx[i] = i;
    Arrays.sort(idx, Comparator.comparingInt(i -> capital[i]));
    PriorityQueue<Integer> best = new PriorityQueue<>(Collections.reverseOrder());
    for (int j = 0, round = 0; round < k; round++) {
        while (j < idx.length && capital[idx[j]] <= w) best.add(profits[idx[j++]]);
        if (best.isEmpty()) break;
        w += best.poll();
    }
    return w;
}

Q8. Meeting rooms II. The minimum number of platforms.

Short answer: This is the maximum number of overlapping intervals:

  • sort the meetings by start time, and keep a min-heap of end times; free the rooms whose meetings have ended (end ≤ start). The heap's maximum size is the answer;
  • or sort the starts and ends separately, and sweep with two pointers: the maximum concurrency is the answer.
  • Minimum platforms (train arrivals and departures) is the same problem. Be careful whether a departure at the same time as an arrival frees the platform (≤ versus <).

O(n log n). (Meeting Rooms II)

int minMeetingRooms(int[][] iv) {
    int n = iv.length; int[] s = new int[n], e = new int[n];
    for (int i = 0; i < n; i++) { s[i] = iv[i][0]; e[i] = iv[i][1]; }
    Arrays.sort(s); Arrays.sort(e);
    int rooms = 0, best = 0;
    for (int i = 0, j = 0; i < n; i++) {
        while (j < n && e[j] <= s[i]) { j++; rooms--; }    // for platforms, use < if dep == arr needs 2 platforms
        best = Math.max(best, ++rooms);
    }
    return best;
}

Q9. Fractional knapsack.

Short answer: Greedy by value per unit of weight: sort by value/weight descending; take whole items while they fit, then a fraction of the next one. O(n log n). Greedy is optimal here (items are divisible); for 0/1 knapsack it isn't, so you need DP.

double fractionalKnapsack(int[] wt, int[] val, int cap) {
    Integer[] idx = new Integer[wt.length];
    for (int i = 0; i < idx.length; i++) idx[i] = i;
    Arrays.sort(idx, (a, b) -> Double.compare((double) val[b] / wt[b], (double) val[a] / wt[a]));
    double total = 0;
    for (int i : idx) {
        if (cap == 0) break;
        int take = Math.min(wt[i], cap);
        total += (double) val[i] * take / wt[i]; cap -= take;
    }
    return total;
}

Q10. Gas station (the greedy argument).

Short answer: If the total gas is at least the total cost, a solution exists. Scan once; whenever the running tank goes negative at i, no start in [start..i] can work (they all reach i with even less fuel), so restart at i+1. O(n). (The full code is in the array-problems lesson.) (Gas Station)

int canCompleteCircuit(int[] gas, int[] cost) {
    int total = 0, tank = 0, start = 0;
    for (int i = 0; i < gas.length; i++) {
        total += gas[i] - cost[i]; tank += gas[i] - cost[i];
        if (tank < 0) { start = i + 1; tank = 0; }
    }
    return total >= 0 ? start : -1;
}

Q11. Find the median from a data stream.

Short answer: Use two heaps: a max-heap for the lower half and a min-heap for the upper half, balanced so the lower half has the same size, or one more. The median is the top of the lower half, or the average of both tops. addNum is O(log n); findMedian is O(1). (Practice)

class MedianFinder {
    private final PriorityQueue<Integer> lo = new PriorityQueue<>(Collections.reverseOrder()), hi = new PriorityQueue<>();
    public void addNum(int x) {
        lo.add(x); hi.add(lo.poll());                         // move the largest of lo to hi
        if (hi.size() > lo.size()) lo.add(hi.poll());         // rebalance
    }
    public double findMedian() {
        return lo.size() > hi.size() ? lo.peek() : ((double) lo.peek() + hi.peek()) / 2.0;
    }
}

Q12. The smallest range covering elements from K lists.

Short answer: Put one element from each list in a min-heap, and track the current maximum. The range [heapMin, curMax] covers all the lists. Pop the minimum, and advance in its list (updating the maximum). Stop when any list is exhausted. O(N log K).

int[] smallestRange(List<List<Integer>> lists) {
    PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(e -> lists.get(e[0]).get(e[1])));
    int max = Integer.MIN_VALUE;
    for (int i = 0; i < lists.size(); i++) { pq.add(new int[]{i, 0}); max = Math.max(max, lists.get(i).get(0)); }
    int[] best = {0, Integer.MAX_VALUE};
    while (true) {
        int[] e = pq.poll(); int min = lists.get(e[0]).get(e[1]);
        if ((long) max - min < (long) best[1] - best[0]) best = new int[]{min, max};
        if (e[1] + 1 == lists.get(e[0]).size()) return best;
        int next = lists.get(e[0]).get(e[1] + 1);
        max = Math.max(max, next); pq.add(new int[]{e[0], e[1] + 1});
    }
}

Q13. The skyline problem.

Short answer: Sweep line plus a max-heap of the active heights:

  1. Turn each building into a start event (x, -h) and an end event (x, h). Sort by x, with starts before ends; taller starts first, and shorter ends first.
  2. At each event, add or remove the height (use a TreeMap<height, count>, for O(log n) removal).
  3. When the current maximum height changes, output a key point (x, newMax).

O(n log n).

List<List<Integer>> getSkyline(int[][] buildings) {
    List<int[]> events = new ArrayList<>();
    for (int[] b : buildings) { events.add(new int[]{b[0], -b[2]}); events.add(new int[]{b[1], b[2]}); }
    events.sort((a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]);
    TreeMap<Integer, Integer> heights = new TreeMap<>(Map.of(0, 1));
    List<List<Integer>> res = new ArrayList<>(); int prev = 0;
    for (int[] e : events) {
        if (e[1] < 0) heights.merge(-e[1], 1, Integer::sum);
        else if (heights.merge(e[1], -1, Integer::sum) == 0) heights.remove(e[1]);
        int cur = heights.lastKey();
        if (cur != prev) { res.add(List.of(e[0], cur)); prev = cur; }
    }
    return res;
}

Advertisement

Follow-up questions this topic invites — and their answers

Q: Why does PriorityQueue.remove(Object) hurt performance? A: It's a linear search, O(n), followed by an O(log n) sift. For frequent arbitrary removals, use a TreeMap of counts, an indexed heap, or lazy deletion.

Q: How do you create a max-heap in Java? A: new PriorityQueue<>(Collections.reverseOrder()), or with a comparator such as (a, b) -> Integer.compare(b, a). Avoid b - a, which can overflow for large or negative values.

Q: How do you prove a greedy algorithm is correct? A: Usually with an exchange argument: take any optimal solution that differs from the greedy one, and show that swapping in the greedy choice doesn't make it worse. Or show that greedy "stays ahead" at every step.

Q: What's the complexity of building a heap from n elements? A: O(n) with bottom-up heapify (new PriorityQueue<>(collection) does this), compared with O(n log n) for n individual inserts.

Advertisement

Previous

Dynamic Programming — Interview Questions

Next

Bit Manipulation & Math — Interview Questions

AI Tutor

Lesson: Heaps & Greedy Algorithms — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.