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· 10 min read

Stacks, Queues & Monotonic Stacks — Interview Questions

Java solutions for stack and queue problems — min stack, evaluating postfix expressions, next greater element, largest rectangle in a histogram, maximal rectangle in a binary matrix, queue using stacks and stack using queues, sliding window median, valid parentheses, a circular queue, monotonic stack applications, the stock span problem, simplify path, decode a nested string, and asteroid collision.

Published September 25, 2026


How to use this lesson

Use a stack when the most recent unresolved item matters: matching brackets, nested structures, "the previous or next greater" element. A monotonic stack keeps elements in increasing or decreasing order, and resolves each element exactly once, so it's O(n). In Java, use ArrayDeque (push, pop, peek) instead of the legacy Stack class.

Q1. Min stack (O(1) getMin).

Short answer: Store each value together with the minimum at the time it was pushed (pairs), or keep a second stack of minimums. Every operation is O(1). (Min Stack)

class MinStack {
    private final Deque<int[]> st = new ArrayDeque<>();          // {value, minSoFar}
    public void push(int x) { st.push(new int[]{x, st.isEmpty() ? x : Math.min(x, st.peek()[1])}); }
    public void pop() { st.pop(); }
    public int top() { return st.peek()[0]; }
    public int getMin() { return st.peek()[1]; }
}

Q2. Evaluate a postfix (Reverse Polish) expression.

Short answer: Push the numbers; on an operator, pop b, then a (the order matters for - and /), and push a op b. O(n). Java's integer division truncates toward zero, which matches the usual specification.

int evalRPN(String[] tokens) {
    Deque<Integer> st = new ArrayDeque<>();
    for (String t : tokens) {
        switch (t) {
            case "+" -> st.push(st.pop() + st.pop());
            case "*" -> st.push(st.pop() * st.pop());
            case "-" -> { int b = st.pop(), a = st.pop(); st.push(a - b); }
            case "/" -> { int b = st.pop(), a = st.pop(); st.push(a / b); }
            default  -> st.push(Integer.parseInt(t));
        }
    }
    return st.pop();
}

Q3. Next greater element. Monotonic stack applications.

Short answer: Use a decreasing stack of indices. For each new element, pop every index with a smaller value: the current element is their next greater element. The indices left in the stack have none. O(n). For a circular array, iterate 2n times using i % n. (Next Greater Element I, Daily Temperatures)

Monotonic stack applications:

  • next or previous greater and smaller elements;
  • daily temperatures;
  • stock span;
  • largest rectangle in a histogram;
  • trapping rain water;
  • removing k digits (the smallest number);
  • the sum of subarray minimums.
  • The rule: use a decreasing stack to find greater elements, and an increasing stack to find smaller ones.
int[] nextGreater(int[] a) {
    int n = a.length; int[] res = new int[n]; Arrays.fill(res, -1);
    Deque<Integer> st = new ArrayDeque<>();
    for (int i = 0; i < 2 * n; i++) {                     // 2n for the circular variant; n otherwise
        while (!st.isEmpty() && a[st.peek()] < a[i % n]) res[st.pop()] = a[i % n];
        if (i < n) st.push(i);
    }
    return res;
}

Q4. Largest rectangle in a histogram.

Short answer: Use an increasing stack of indices. When a bar is lower than the top of the stack, pop the top: its rectangle's height is h[top], extending from the new stack top + 1 up to i - 1. Add a sentinel height of 0 at the end, to flush the stack. O(n).

int largestRectangleArea(int[] h) {
    Deque<Integer> st = new ArrayDeque<>(); int best = 0;
    for (int i = 0; i <= h.length; i++) {
        int cur = i == h.length ? 0 : h[i];
        while (!st.isEmpty() && h[st.peek()] > cur) {
            int height = h[st.pop()];
            int left = st.isEmpty() ? -1 : st.peek();
            best = Math.max(best, height * (i - left - 1));
        }
        st.push(i);
    }
    return best;
}

Q5. Maximal rectangle in a binary matrix.

Short answer: Treat each row as the base of a histogram: heights[c] counts the consecutive 1s up to this row (reset to 0 on a 0). Run largest rectangle in a histogram for each row. O(rows × cols).

int maximalRectangle(char[][] m) {
    if (m.length == 0) return 0;
    int[] heights = new int[m[0].length]; int best = 0;
    for (char[] row : m) {
        for (int c = 0; c < row.length; c++) heights[c] = row[c] == '1' ? heights[c] + 1 : 0;
        best = Math.max(best, largestRectangleArea(heights));
    }
    return best;
}

Q6. Implement a queue using stacks, and a stack using queues.

Short answer:

  • A queue with two stacks: push onto in; for pop and peek, if out is empty, move everything from in to out (reversing the order). Each element moves at most once, so it's amortised O(1).
  • A stack with one queue: after each offer, rotate the queue size-1 times, so the newest element is at the front. push is O(n); pop and top are O(1).
class MyQueue {
    private final Deque<Integer> in = new ArrayDeque<>(), out = new ArrayDeque<>();
    public void push(int x) { in.push(x); }
    public int pop()  { peek(); return out.pop(); }
    public int peek() { if (out.isEmpty()) while (!in.isEmpty()) out.push(in.pop()); return out.peek(); }
    public boolean empty() { return in.isEmpty() && out.isEmpty(); }
}
class MyStack {
    private final Queue<Integer> q = new ArrayDeque<>();
    public void push(int x) { q.offer(x); for (int i = 1; i < q.size(); i++) q.offer(q.poll()); }
    public int pop() { return q.poll(); }
    public int top() { return q.peek(); }
    public boolean empty() { return q.isEmpty(); }
}

Q7. Sliding window median.

Short answer: Use two heaps (a max-heap for the lower half and a min-heap for the upper half), with removal of the element leaving the window. PriorityQueue.remove(Object) is O(k), which gives O(n·k). For O(n log k), use lazy deletion (a map of pending deletions, cleaned when those elements reach the top), or two TreeMap-based multisets.

double[] medianSlidingWindow(int[] a, int k) {
    PriorityQueue<Integer> lo = new PriorityQueue<>(Collections.reverseOrder()), hi = new PriorityQueue<>();
    double[] res = new double[a.length - k + 1];
    for (int i = 0; i < a.length; i++) {
        if (lo.isEmpty() || a[i] <= lo.peek()) lo.add(a[i]); else hi.add(a[i]);
        if (i >= k) { if (a[i - k] <= lo.peek()) lo.remove(a[i - k]); else hi.remove(a[i - k]); }
        while (lo.size() > hi.size() + 1) hi.add(lo.poll());
        while (hi.size() > lo.size()) lo.add(hi.poll());
        if (i >= k - 1) res[i - k + 1] = k % 2 == 1 ? lo.peek() : ((double) lo.peek() + hi.peek()) / 2.0;
    }
    return res;
}

Learn it in depth → Two Heaps

Q8. Valid parentheses.

Short answer: Push the expected closing bracket for each opening one; on a closing bracket, it must match the popped value. At the end, the stack must be empty. O(n). A string of odd length can be rejected immediately. (Practice)

boolean isValid(String s) {
    if (s.length() % 2 == 1) return false;
    Deque<Character> st = new ArrayDeque<>();
    for (char c : s.toCharArray()) {
        switch (c) {
            case '(' -> st.push(')'); case '[' -> st.push(']'); case '{' -> st.push('}');
            default -> { if (st.isEmpty() || st.pop() != c) return false; }
        }
    }
    return st.isEmpty();
}

Q9. Design a circular queue.

Short answer: A fixed array, with a head index and a count (or the head and tail, with one slot kept empty). The indices wrap with % capacity. O(1) for every operation. It's the basis of ring buffers (for example, the LMAX Disruptor, and bounded logging buffers).

class MyCircularQueue {
    private final int[] buf; private int head, count;
    MyCircularQueue(int k) { buf = new int[k]; }
    public boolean enQueue(int v) { if (isFull()) return false; buf[(head + count++) % buf.length] = v; return true; }
    public boolean deQueue() { if (isEmpty()) return false; head = (head + 1) % buf.length; count--; return true; }
    public int Front() { return isEmpty() ? -1 : buf[head]; }
    public int Rear()  { return isEmpty() ? -1 : buf[(head + count - 1) % buf.length]; }
    public boolean isEmpty() { return count == 0; }
    public boolean isFull()  { return count == buf.length; }
}

Q10. The stock span problem.

Short answer: A day's span is the number of consecutive days up to and including today with a price ≤ today's. Keep a decreasing stack of (price, span): pop while the top price is ≤ today's, adding their spans. Amortised O(1) per day.

class StockSpanner {
    private final Deque<int[]> st = new ArrayDeque<>();
    public int next(int price) {
        int span = 1;
        while (!st.isEmpty() && st.peek()[0] <= price) span += st.pop()[1];
        st.push(new int[]{price, span});
        return span;
    }
}

Q11. Simplify a Unix-style path.

Short answer: Split on /. Skip empty parts and .; for .., pop (if the stack isn't empty); push any other name. Join as / plus the names. O(n).

String simplifyPath(String path) {
    Deque<String> st = new ArrayDeque<>();
    for (String p : path.split("/")) {
        if (p.isEmpty() || p.equals(".")) continue;
        if (p.equals("..")) { if (!st.isEmpty()) st.pollLast(); }
        else st.offerLast(p);
    }
    return "/" + String.join("/", st);
}

Q12. Decode a nested encoded string (like 3[a2[c]]).

Short answer: Use two stacks: counts and partial strings. On [, push the current count and the current builder, then start fresh. On ], pop them, and append the current string repeated count times to the popped builder. Digits can have several characters (12[a]). O(output length).

String decodeString(String s) {
    Deque<Integer> counts = new ArrayDeque<>(); Deque<StringBuilder> parts = new ArrayDeque<>();
    StringBuilder cur = new StringBuilder(); int k = 0;
    for (char c : s.toCharArray()) {
        if (Character.isDigit(c)) k = k * 10 + (c - '0');
        else if (c == '[') { counts.push(k); parts.push(cur); cur = new StringBuilder(); k = 0; }
        else if (c == ']') { StringBuilder prev = parts.pop(); prev.append(cur.toString().repeat(counts.pop())); cur = prev; }
        else cur.append(c);
    }
    return cur.toString();
}

Q13. Asteroid collision.

Short answer: Positive values move right, negative values move left. Only a right-moving asteroid on the stack meeting a new left-moving one collides. While the top is positive and the new one negative: the smaller explodes; if they're equal, both do. Push the survivors. O(n).

int[] asteroidCollision(int[] a) {
    Deque<Integer> st = new ArrayDeque<>();
    for (int x : a) {
        boolean alive = true;
        while (alive && x < 0 && !st.isEmpty() && st.peekLast() > 0) {
            int top = st.peekLast();
            if (top < -x) st.pollLast();                 // top explodes, keep checking
            else { if (top == -x) st.pollLast(); alive = false; }
        }
        if (alive) st.offerLast(x);
    }
    return st.stream().mapToInt(Integer::intValue).toArray();
}

Advertisement

Follow-up questions this topic invites — and their answers

Q: Why is a monotonic stack O(n) despite the nested while loop? A: Each index is pushed once and popped at most once, so the total work of all the inner loops across the whole run is at most n.

Q: Why store indices rather than values in monotonic stacks? A: Indices give both the value (a[i]) and the position, which you need for distances (spans, widths, days until warmer).

Q: Why use ArrayDeque instead of LinkedList for queues? A: ArrayDeque is backed by a resizable circular array: better cache locality, and no per-node allocation. LinkedList allows nulls and implements List, but is slower for queue workloads.

Q: What's a real-world use of a ring buffer? A: Bounded producer-consumer pipelines (the LMAX Disruptor), audio and network buffers, "last N events" diagnostics, and in-memory log buffers that overwrite the oldest entries.

Advertisement

Previous

Linked Lists, LRU & LFU Caches — Interview Questions

Next

Binary Trees & BSTs — Interview Questions

AI Tutor

Lesson: Stacks, Queues & Monotonic Stacks — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.