Add stack-queue module: ten stack and queue interview problems, monotonic stack, min stack, queue from stacks and stack from a queue, brute-force cross-checks, dry-run traces, operation counts, pitfalls (11 tests)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b6nxynun5JFivebVb1
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
package com.ankurm.interviewlab.stackqueue;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/** Slow, obviously-correct references. The randomized tests compare every stack solution against these. */
|
||||
public final class BruteForce {
|
||||
private BruteForce() {}
|
||||
|
||||
public static int[] nextGreater(int[] a) {
|
||||
int[] result = new int[a.length];
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
result[i] = -1;
|
||||
for (int j = i + 1; j < a.length; j++) {
|
||||
if (a[j] > a[i]) {
|
||||
result[i] = a[j];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static int[] dailyTemperatures(int[] temps) {
|
||||
int[] wait = new int[temps.length];
|
||||
for (int i = 0; i < temps.length; i++) {
|
||||
for (int j = i + 1; j < temps.length; j++) {
|
||||
if (temps[j] > temps[i]) {
|
||||
wait[i] = j - i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return wait;
|
||||
}
|
||||
|
||||
public static int[] nextGreaterCircular(int[] a) {
|
||||
int n = a.length;
|
||||
int[] result = new int[n];
|
||||
Arrays.fill(result, -1);
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int step = 1; step < n; step++) {
|
||||
int candidate = a[(i + step) % n];
|
||||
if (candidate > a[i]) {
|
||||
result[i] = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** For every bar, widen left and right while the neighbours are at least as tall. */
|
||||
public static int largestRectangle(int[] h) {
|
||||
int best = 0;
|
||||
for (int i = 0; i < h.length; i++) {
|
||||
int left = i;
|
||||
while (left > 0 && h[left - 1] >= h[i]) {
|
||||
left--;
|
||||
}
|
||||
int right = i;
|
||||
while (right < h.length - 1 && h[right + 1] >= h[i]) {
|
||||
right++;
|
||||
}
|
||||
best = Math.max(best, h[i] * (right - left + 1));
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Keep only brackets, then delete adjacent matching pairs until nothing changes. Balanced iff nothing is left. */
|
||||
public static boolean isBalanced(String s) {
|
||||
String t = s.replaceAll("[^()\\[\\]{}]", "");
|
||||
String before;
|
||||
do {
|
||||
before = t;
|
||||
t = t.replace("()", "").replace("[]", "").replace("{}", "");
|
||||
} while (!t.equals(before));
|
||||
return t.isEmpty();
|
||||
}
|
||||
|
||||
/** Recursive-descent decode: the index travels in a one-element array. */
|
||||
public static String decode(String s) {
|
||||
return decodeFrom(s, new int[] {0});
|
||||
}
|
||||
|
||||
private static String decodeFrom(String s, int[] pos) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
while (pos[0] < s.length() && s.charAt(pos[0]) != ']') {
|
||||
char ch = s.charAt(pos[0]);
|
||||
if (Character.isDigit(ch)) {
|
||||
int count = 0;
|
||||
while (Character.isDigit(s.charAt(pos[0]))) {
|
||||
count = count * 10 + (s.charAt(pos[0]) - '0');
|
||||
pos[0]++;
|
||||
}
|
||||
pos[0]++; // skip the opening bracket
|
||||
String inner = decodeFrom(s, pos);
|
||||
pos[0]++; // skip the closing bracket
|
||||
out.append(inner.repeat(count));
|
||||
} else {
|
||||
out.append(ch);
|
||||
pos[0]++;
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.ankurm.interviewlab.stackqueue;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Arrays;
|
||||
import java.util.Deque;
|
||||
|
||||
/** Operation counters. These count work done, they do not time it. */
|
||||
public final class Complexity {
|
||||
private Complexity() {}
|
||||
|
||||
public record Counts(long comparisons, long pushes, long pops) {
|
||||
public long stackOps() {
|
||||
return pushes + pops;
|
||||
}
|
||||
}
|
||||
|
||||
/** nextGreater with every comparison, push and pop counted. Returns the answers too, so tests can check them. */
|
||||
public static Counts monotonicNextGreater(int[] a, int[] answerOut) {
|
||||
long comparisons = 0;
|
||||
long pushes = 0;
|
||||
long pops = 0;
|
||||
Arrays.fill(answerOut, -1);
|
||||
Deque<Integer> pending = new ArrayDeque<>();
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
while (!pending.isEmpty()) {
|
||||
comparisons++;
|
||||
if (a[pending.peek()] >= a[i]) {
|
||||
break;
|
||||
}
|
||||
answerOut[pending.pop()] = a[i];
|
||||
pops++;
|
||||
}
|
||||
pending.push(i);
|
||||
pushes++;
|
||||
}
|
||||
return new Counts(comparisons, pushes, pops);
|
||||
}
|
||||
|
||||
/** The brute-force version, counting each a[j] > a[i] comparison. */
|
||||
public static long bruteForceComparisons(int[] a) {
|
||||
long comparisons = 0;
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
for (int j = i + 1; j < a.length; j++) {
|
||||
comparisons++;
|
||||
if (a[j] > a[i]) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return comparisons;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.ankurm.interviewlab.stackqueue;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
|
||||
/** Problem 8: decode strings such as 3[a2[bc]]. Each open bracket parks the text built so far, and its count. */
|
||||
public final class DecodeString {
|
||||
private DecodeString() {}
|
||||
|
||||
public static String decode(String s) {
|
||||
Deque<StringBuilder> parked = new ArrayDeque<>();
|
||||
Deque<Integer> repeats = new ArrayDeque<>();
|
||||
StringBuilder current = new StringBuilder();
|
||||
int number = 0;
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char ch = s.charAt(i);
|
||||
if (Character.isDigit(ch)) {
|
||||
number = number * 10 + (ch - '0');
|
||||
} else if (ch == '[') {
|
||||
repeats.push(number);
|
||||
parked.push(current);
|
||||
current = new StringBuilder();
|
||||
number = 0;
|
||||
} else if (ch == ']') {
|
||||
StringBuilder outer = parked.pop();
|
||||
outer.append(current.toString().repeat(repeats.pop()));
|
||||
current = outer;
|
||||
} else {
|
||||
current.append(ch);
|
||||
}
|
||||
}
|
||||
return current.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package com.ankurm.interviewlab.stackqueue;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Instrumented copies of the solutions that record every step. The tests assert each copy returns the same answer
|
||||
* as the real method, so the traces describe what the real code does.
|
||||
*/
|
||||
public final class DryRuns {
|
||||
private DryRuns() {}
|
||||
|
||||
public record Trace<T>(List<String> lines, T result) {}
|
||||
|
||||
/** Closers waiting on the stack, top first, separated by spaces, so they do not clash with list brackets. */
|
||||
private static String closers(Deque<Character> stack) {
|
||||
if (stack.isEmpty()) {
|
||||
return "(empty)";
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (char ch : stack) {
|
||||
sb.append(sb.length() == 0 ? "" : " ").append(ch);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static Trace<Boolean> balanced(String s) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
Deque<Character> expected = new ArrayDeque<>();
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char ch = s.charAt(i);
|
||||
String prefix = "read '" + ch + "' at " + i + ": ";
|
||||
if (ch == '(' || ch == '{' || ch == '[') {
|
||||
char closer = ch == '(' ? ')' : ch == '{' ? '}' : ']';
|
||||
expected.push(closer);
|
||||
lines.add(prefix + String.format("%-18s", "push '" + closer + "'") + " waiting for (top first): " + closers(expected));
|
||||
} else {
|
||||
if (expected.isEmpty()) {
|
||||
lines.add(prefix + "stack is empty, nothing to close -> NOT balanced");
|
||||
return new Trace<>(lines, false);
|
||||
}
|
||||
char want = expected.pop();
|
||||
if (want != ch) {
|
||||
lines.add(prefix + "expected '" + want + "' -> NOT balanced");
|
||||
return new Trace<>(lines, false);
|
||||
}
|
||||
lines.add(prefix + String.format("%-18s", "pop '" + want + "', matches") + " waiting for (top first): " + closers(expected));
|
||||
}
|
||||
}
|
||||
boolean ok = expected.isEmpty();
|
||||
lines.add("end of input: waiting for " + closers(expected) + (ok ? " -> balanced" : " -> NOT balanced, openers left over"));
|
||||
return new Trace<>(lines, ok);
|
||||
}
|
||||
|
||||
public static Trace<Integer> rpn(String[] tokens) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
Deque<Integer> operands = new ArrayDeque<>();
|
||||
for (String token : tokens) {
|
||||
if (token.length() == 1 && "+-*/".contains(token)) {
|
||||
int right = operands.pop();
|
||||
int left = operands.pop();
|
||||
int value = Rpn.apply(token, left, right);
|
||||
operands.push(value);
|
||||
lines.add("token " + token + ": pop " + right + " then " + left + ", compute " + left + " " + token + " "
|
||||
+ right + " = " + value + " stack(top first) = " + operands);
|
||||
} else {
|
||||
operands.push(Integer.parseInt(token));
|
||||
lines.add("token " + token + ": push " + token + " stack(top first) = " + operands);
|
||||
}
|
||||
}
|
||||
return new Trace<>(lines, operands.peek());
|
||||
}
|
||||
|
||||
/** Runs a fixed sequence on the parallel-stack min stack, showing both internal stacks after every step. */
|
||||
public static Trace<List<Integer>> minStack(String... ops) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
List<Integer> minsSeen = new ArrayList<>();
|
||||
Deque<Integer> values = new ArrayDeque<>();
|
||||
Deque<Integer> minimums = new ArrayDeque<>();
|
||||
for (String op : ops) {
|
||||
if (op.startsWith("push ")) {
|
||||
int x = Integer.parseInt(op.substring(5));
|
||||
values.push(x);
|
||||
String note = "";
|
||||
if (minimums.isEmpty() || x <= minimums.peek()) {
|
||||
minimums.push(x);
|
||||
note = " (new or equal minimum, also pushed on mins)";
|
||||
}
|
||||
lines.add(String.format("%-9s values=%-14s mins=%-10s%s", op, values, minimums, note).stripTrailing());
|
||||
} else if (op.equals("pop")) {
|
||||
int x = values.pop();
|
||||
String note = "";
|
||||
if (x == minimums.peek()) {
|
||||
minimums.pop();
|
||||
note = " (it was the minimum, mins popped too)";
|
||||
}
|
||||
lines.add(String.format("%-9s values=%-14s mins=%-10s%s", op + " -> " + x, values, minimums, note).stripTrailing());
|
||||
} else {
|
||||
int min = minimums.peek();
|
||||
minsSeen.add(min);
|
||||
lines.add(String.format("%-9s values=%-14s mins=%-10s getMin() = %d", op, values, minimums, min));
|
||||
}
|
||||
}
|
||||
return new Trace<>(lines, minsSeen);
|
||||
}
|
||||
|
||||
public static Trace<int[]> nextGreater(int[] a) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
int[] result = new int[a.length];
|
||||
Arrays.fill(result, -1);
|
||||
Deque<Integer> pending = new ArrayDeque<>();
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
StringBuilder step = new StringBuilder("i=" + i + " value=" + a[i] + ":");
|
||||
while (!pending.isEmpty() && a[pending.peek()] < a[i]) {
|
||||
int j = pending.pop();
|
||||
result[j] = a[i];
|
||||
step.append(" pop index ").append(j).append(" (value ").append(a[j]).append(") -> its answer is ").append(a[i]).append(';');
|
||||
}
|
||||
pending.push(i);
|
||||
step.append(" push ").append(i).append(" pending(top first) = ").append(pending);
|
||||
lines.add(step.toString());
|
||||
}
|
||||
lines.add("indices still pending have no greater element to their right: " + pending + " -> stay -1");
|
||||
return new Trace<>(lines, result);
|
||||
}
|
||||
|
||||
public static Trace<Integer> histogram(int[] heights) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
int n = heights.length;
|
||||
int best = 0;
|
||||
Deque<Integer> rising = new ArrayDeque<>();
|
||||
for (int i = 0; i <= n; i++) {
|
||||
int current = (i == n) ? 0 : heights[i];
|
||||
lines.add("i=" + i + (i == n ? " (sentinel)" : "") + " height=" + current + ":");
|
||||
while (!rising.isEmpty() && heights[rising.peek()] >= current) {
|
||||
int height = heights[rising.pop()];
|
||||
int leftEdge = rising.isEmpty() ? -1 : rising.peek();
|
||||
int width = i - leftEdge - 1;
|
||||
best = Math.max(best, height * width);
|
||||
lines.add(" pop bar of height " + height + ": left edge index " + leftEdge + ", right edge index " + (i - 1)
|
||||
+ ", width " + width + ", area " + (height * width) + " best = " + best);
|
||||
}
|
||||
rising.push(i);
|
||||
lines.add(" push index " + i + " stack(top first) = " + rising);
|
||||
}
|
||||
return new Trace<>(lines, best);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.ankurm.interviewlab.stackqueue;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/**
|
||||
* Problem 3, version B: one stack, one extra variable. Each entry stores its distance from the minimum that was in
|
||||
* force when it was pushed. A negative entry marks a push that created a new minimum, and it carries the old
|
||||
* minimum inside it. The differences are longs because the difference of two ints can overflow an int.
|
||||
*/
|
||||
public final class EncodedMinStack implements IntMinStack {
|
||||
private final Deque<Long> diffs = new ArrayDeque<>();
|
||||
private long min;
|
||||
|
||||
@Override
|
||||
public void push(int x) {
|
||||
if (diffs.isEmpty()) {
|
||||
diffs.push(0L);
|
||||
min = x;
|
||||
return;
|
||||
}
|
||||
diffs.push((long) x - min);
|
||||
if (x < min) {
|
||||
min = x;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int pop() {
|
||||
requireNonEmpty();
|
||||
long diff = diffs.pop();
|
||||
if (diff < 0) {
|
||||
int removed = (int) min; // a negative entry means the popped value was the minimum
|
||||
min = min - diff; // restore the previous minimum
|
||||
return removed;
|
||||
}
|
||||
return (int) (min + diff);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int top() {
|
||||
requireNonEmpty();
|
||||
long diff = diffs.peek();
|
||||
return diff < 0 ? (int) min : (int) (min + diff);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMin() {
|
||||
requireNonEmpty();
|
||||
return (int) min;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return diffs.size();
|
||||
}
|
||||
|
||||
private void requireNonEmpty() {
|
||||
if (diffs.isEmpty()) {
|
||||
throw new NoSuchElementException("stack is empty");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.ankurm.interviewlab.stackqueue;
|
||||
|
||||
/** A stack of ints that also reports its minimum in O(1). */
|
||||
public interface IntMinStack {
|
||||
void push(int x);
|
||||
|
||||
/** Removes and returns the top. Throws NoSuchElementException when empty. */
|
||||
int pop();
|
||||
|
||||
/** Returns the top without removing it. Throws NoSuchElementException when empty. */
|
||||
int top();
|
||||
|
||||
/** Returns the smallest value currently in the stack. Throws NoSuchElementException when empty. */
|
||||
int getMin();
|
||||
|
||||
int size();
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.ankurm.interviewlab.stackqueue;
|
||||
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
import java.util.Queue;
|
||||
import java.util.Stack;
|
||||
|
||||
/** What the JDK gives you for a stack, and why the answer is ArrayDeque rather than java.util.Stack. */
|
||||
public final class JdkStackDemo {
|
||||
private JdkStackDemo() {}
|
||||
|
||||
/** Last in, first out: push 1, 2, 3, then pop until empty. */
|
||||
public static List<Integer> stackPopOrder() {
|
||||
Deque<Integer> stack = new ArrayDeque<>();
|
||||
stack.push(1);
|
||||
stack.push(2);
|
||||
stack.push(3);
|
||||
List<Integer> popped = new ArrayList<>();
|
||||
while (!stack.isEmpty()) {
|
||||
popped.add(stack.pop());
|
||||
}
|
||||
return popped;
|
||||
}
|
||||
|
||||
/** First in, first out: offer 1, 2, 3, then poll until empty. */
|
||||
public static List<Integer> queuePollOrder() {
|
||||
Queue<Integer> queue = new ArrayDeque<>();
|
||||
queue.offer(1);
|
||||
queue.offer(2);
|
||||
queue.offer(3);
|
||||
List<Integer> polled = new ArrayList<>();
|
||||
while (!queue.isEmpty()) {
|
||||
polled.add(queue.poll());
|
||||
}
|
||||
return polled;
|
||||
}
|
||||
|
||||
/** Items in iteration order after push(1), push(2), push(3) on the legacy class. Bottom to top. */
|
||||
public static List<Integer> legacyStackOrder() {
|
||||
Stack<Integer> stack = new Stack<>();
|
||||
stack.push(1);
|
||||
stack.push(2);
|
||||
stack.push(3);
|
||||
return new ArrayList<>(stack);
|
||||
}
|
||||
|
||||
/** Items in iteration order after push(1), push(2), push(3) on an ArrayDeque. Top to bottom. */
|
||||
public static List<Integer> dequeOrder() {
|
||||
Deque<Integer> stack = new ArrayDeque<>();
|
||||
stack.push(1);
|
||||
stack.push(2);
|
||||
stack.push(3);
|
||||
return new ArrayList<>(stack);
|
||||
}
|
||||
|
||||
public static String legacySuperclass() {
|
||||
return Stack.class.getSuperclass().getName();
|
||||
}
|
||||
|
||||
public static boolean legacyPopIsSynchronized() throws NoSuchMethodException {
|
||||
return Modifier.isSynchronized(Stack.class.getMethod("pop").getModifiers());
|
||||
}
|
||||
|
||||
public static boolean dequePopIsSynchronized() throws NoSuchMethodException {
|
||||
return Modifier.isSynchronized(ArrayDeque.class.getMethod("pop").getModifiers());
|
||||
}
|
||||
|
||||
/** The legacy class accepts null; ArrayDeque rejects it. Returns the exception class name, or "accepted". */
|
||||
public static String pushNullOnLegacy() {
|
||||
try {
|
||||
new Stack<Integer>().push(null);
|
||||
return "accepted";
|
||||
} catch (RuntimeException e) {
|
||||
return e.getClass().getName();
|
||||
}
|
||||
}
|
||||
|
||||
public static String pushNullOnDeque() {
|
||||
try {
|
||||
new ArrayDeque<Integer>().push(null);
|
||||
return "accepted";
|
||||
} catch (RuntimeException e) {
|
||||
return e.getClass().getName();
|
||||
}
|
||||
}
|
||||
|
||||
/** push is addFirst, offer is addLast. Mixing them on one deque reads from the wrong end. */
|
||||
public static int peekAfterPushes() {
|
||||
Deque<Integer> d = new ArrayDeque<>();
|
||||
d.push(1);
|
||||
d.push(2);
|
||||
return d.peek();
|
||||
}
|
||||
|
||||
public static int peekAfterOffers() {
|
||||
Deque<Integer> d = new ArrayDeque<>();
|
||||
d.offer(1);
|
||||
d.offer(2);
|
||||
return d.peek();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.ankurm.interviewlab.stackqueue;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/** Problem 3, version A: a second stack that remembers the minimum at every depth where it changed. */
|
||||
public final class MinStack implements IntMinStack {
|
||||
private final Deque<Integer> values = new ArrayDeque<>();
|
||||
private final Deque<Integer> minimums = new ArrayDeque<>();
|
||||
|
||||
@Override
|
||||
public void push(int x) {
|
||||
values.push(x);
|
||||
if (minimums.isEmpty() || x <= minimums.peek()) { // <=, not <: a duplicate minimum needs its own entry
|
||||
minimums.push(x);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int pop() {
|
||||
requireNonEmpty();
|
||||
int x = values.pop();
|
||||
if (x == minimums.peek()) { // int against Integer: unboxed, compared by value
|
||||
minimums.pop();
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int top() {
|
||||
requireNonEmpty();
|
||||
return values.peek();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMin() {
|
||||
requireNonEmpty();
|
||||
return minimums.peek();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return values.size();
|
||||
}
|
||||
|
||||
private void requireNonEmpty() {
|
||||
if (values.isEmpty()) {
|
||||
throw new NoSuchElementException("stack is empty");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.ankurm.interviewlab.stackqueue;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Arrays;
|
||||
import java.util.Deque;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Problems 4 to 7: the monotonic stack pattern. The stack holds indices whose answer is not known yet, and the
|
||||
* values at those indices never increase from bottom to top. A new value that breaks that order settles every
|
||||
* index it is larger than.
|
||||
*/
|
||||
public final class MonotonicStack {
|
||||
private MonotonicStack() {}
|
||||
|
||||
/** Problem 4: for each element, the first strictly greater element to its right, or -1. */
|
||||
public static int[] nextGreater(int[] a) {
|
||||
int[] result = new int[a.length];
|
||||
Arrays.fill(result, -1);
|
||||
Deque<Integer> pending = new ArrayDeque<>();
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
while (!pending.isEmpty() && a[pending.peek()] < a[i]) {
|
||||
result[pending.pop()] = a[i];
|
||||
}
|
||||
pending.push(i);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Problem 4, interview form: for each value of nums1 (a subset of nums2, all distinct), its next greater in nums2. */
|
||||
public static int[] nextGreaterSubset(int[] nums1, int[] nums2) {
|
||||
Map<Integer, Integer> nextOf = new HashMap<>();
|
||||
Deque<Integer> pending = new ArrayDeque<>();
|
||||
for (int x : nums2) {
|
||||
while (!pending.isEmpty() && pending.peek() < x) {
|
||||
nextOf.put(pending.pop(), x);
|
||||
}
|
||||
pending.push(x);
|
||||
}
|
||||
int[] answer = new int[nums1.length];
|
||||
for (int k = 0; k < nums1.length; k++) {
|
||||
answer[k] = nextOf.getOrDefault(nums1[k], -1);
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
|
||||
/** Problem 5: for each day, how many days until a warmer one; 0 if none. */
|
||||
public static int[] dailyTemperatures(int[] temps) {
|
||||
int[] wait = new int[temps.length];
|
||||
Deque<Integer> pending = new ArrayDeque<>();
|
||||
for (int i = 0; i < temps.length; i++) {
|
||||
while (!pending.isEmpty() && temps[pending.peek()] < temps[i]) {
|
||||
int day = pending.pop();
|
||||
wait[day] = i - day;
|
||||
}
|
||||
pending.push(i);
|
||||
}
|
||||
return wait;
|
||||
}
|
||||
|
||||
/** Problem 6: next greater element in a circular array, so the search may wrap around past the end. */
|
||||
public static int[] nextGreaterCircular(int[] a) {
|
||||
int n = a.length;
|
||||
int[] result = new int[n];
|
||||
Arrays.fill(result, -1);
|
||||
Deque<Integer> pending = new ArrayDeque<>();
|
||||
for (int i = 0; i < 2 * n; i++) {
|
||||
int value = a[i % n];
|
||||
while (!pending.isEmpty() && a[pending.peek()] < value) {
|
||||
result[pending.pop()] = value;
|
||||
}
|
||||
if (i < n) {
|
||||
pending.push(i); // second lap only settles answers, it never adds new work
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Problem 7: area of the largest rectangle inside a histogram. The stack holds indices of rising bar heights. */
|
||||
public static int largestRectangle(int[] heights) {
|
||||
int n = heights.length;
|
||||
int best = 0;
|
||||
Deque<Integer> rising = new ArrayDeque<>();
|
||||
for (int i = 0; i <= n; i++) {
|
||||
int current = (i == n) ? 0 : heights[i]; // a final bar of height 0 flushes the stack
|
||||
while (!rising.isEmpty() && heights[rising.peek()] >= current) {
|
||||
int height = heights[rising.pop()];
|
||||
int leftEdge = rising.isEmpty() ? -1 : rising.peek();
|
||||
best = Math.max(best, height * (i - leftEdge - 1));
|
||||
}
|
||||
rising.push(i);
|
||||
}
|
||||
return best;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.ankurm.interviewlab.stackqueue;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
|
||||
/** Problem 1: balanced brackets. */
|
||||
public final class Parentheses {
|
||||
private Parentheses() {}
|
||||
|
||||
/**
|
||||
* True when every bracket is closed by the matching kind, in the right order. Characters that are not
|
||||
* brackets are ignored. The stack holds the closer each open bracket is waiting for.
|
||||
*/
|
||||
public static boolean isBalanced(String s) {
|
||||
Deque<Character> expected = new ArrayDeque<>();
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char ch = s.charAt(i);
|
||||
switch (ch) {
|
||||
case '(' -> expected.push(')');
|
||||
case '{' -> expected.push('}');
|
||||
case '[' -> expected.push(']');
|
||||
case ')', '}', ']' -> {
|
||||
if (expected.isEmpty() || expected.pop() != ch) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
default -> { }
|
||||
}
|
||||
}
|
||||
return expected.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Index of the first offending character, or -1 when the string is balanced. That is either a closer
|
||||
* with no matching opener, or, when the scan ends with openers left over, the earliest opener never closed.
|
||||
*/
|
||||
public static int firstMismatch(String s) {
|
||||
Deque<Integer> openers = new ArrayDeque<>();
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char ch = s.charAt(i);
|
||||
if (ch == '(' || ch == '{' || ch == '[') {
|
||||
openers.push(i);
|
||||
} else if (ch == ')' || ch == '}' || ch == ']') {
|
||||
if (openers.isEmpty() || !matches(s.charAt(openers.pop()), ch)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return openers.isEmpty() ? -1 : openers.peekLast();
|
||||
}
|
||||
|
||||
private static boolean matches(char open, char close) {
|
||||
return (open == '(' && close == ')') || (open == '{' && close == '}') || (open == '[' && close == ']');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package com.ankurm.interviewlab.stackqueue;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Arrays;
|
||||
import java.util.Deque;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/** Plausible-looking wrong versions. Each one passes a casual test and fails the case the test chooses. */
|
||||
public final class Pitfalls {
|
||||
private Pitfalls() {}
|
||||
|
||||
/** Wrong: counts each bracket kind, never checks order. */
|
||||
public static boolean balancedCountsOnly(String s) {
|
||||
int round = 0;
|
||||
int curly = 0;
|
||||
int square = 0;
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
switch (s.charAt(i)) {
|
||||
case '(' -> round++;
|
||||
case ')' -> round--;
|
||||
case '{' -> curly++;
|
||||
case '}' -> curly--;
|
||||
case '[' -> square++;
|
||||
case ']' -> square--;
|
||||
default -> { }
|
||||
}
|
||||
if (round < 0 || curly < 0 || square < 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return round == 0 && curly == 0 && square == 0;
|
||||
}
|
||||
|
||||
/** Wrong: compares two boxed Integers with ==, which compares references. Works only while values are cached. */
|
||||
public static final class BoxedEqualsMinStack implements IntMinStack {
|
||||
private final Deque<Integer> values = new ArrayDeque<>();
|
||||
private final Deque<Integer> minimums = new ArrayDeque<>();
|
||||
|
||||
@Override
|
||||
public void push(int x) {
|
||||
values.push(x);
|
||||
if (minimums.isEmpty() || x <= minimums.peek()) {
|
||||
minimums.push(x);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int pop() {
|
||||
Integer x = values.pop();
|
||||
if (x == minimums.peek()) { // Integer == Integer: reference comparison
|
||||
minimums.pop();
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int top() {
|
||||
return values.peek();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMin() {
|
||||
return minimums.peek();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return values.size();
|
||||
}
|
||||
}
|
||||
|
||||
/** Wrong: pushes onto the min stack only on a strictly smaller value, so duplicates of the minimum are lost. */
|
||||
public static final class StrictMinStack implements IntMinStack {
|
||||
private final Deque<Integer> values = new ArrayDeque<>();
|
||||
private final Deque<Integer> minimums = new ArrayDeque<>();
|
||||
|
||||
@Override
|
||||
public void push(int x) {
|
||||
values.push(x);
|
||||
if (minimums.isEmpty() || x < minimums.peek()) { // should be <=
|
||||
minimums.push(x);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int pop() {
|
||||
int x = values.pop();
|
||||
if (x == minimums.peek()) {
|
||||
minimums.pop();
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int top() {
|
||||
return values.peek();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMin() {
|
||||
return minimums.peek();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return values.size();
|
||||
}
|
||||
}
|
||||
|
||||
/** Wrong: the encoded min stack with int differences, which overflow for values far apart. */
|
||||
public static final class IntDiffMinStack implements IntMinStack {
|
||||
private final Deque<Integer> diffs = new ArrayDeque<>();
|
||||
private int min;
|
||||
|
||||
@Override
|
||||
public void push(int x) {
|
||||
if (diffs.isEmpty()) {
|
||||
diffs.push(0);
|
||||
min = x;
|
||||
return;
|
||||
}
|
||||
diffs.push(x - min); // overflows when x and min are more than Integer.MAX_VALUE apart
|
||||
if (x < min) {
|
||||
min = x;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int pop() {
|
||||
int diff = diffs.pop();
|
||||
if (diff < 0) {
|
||||
int removed = min;
|
||||
min = min - diff;
|
||||
return removed;
|
||||
}
|
||||
return min + diff;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int top() {
|
||||
int diff = diffs.peek();
|
||||
return diff < 0 ? min : min + diff;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMin() {
|
||||
if (diffs.isEmpty()) {
|
||||
throw new NoSuchElementException("stack is empty");
|
||||
}
|
||||
return min;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return diffs.size();
|
||||
}
|
||||
}
|
||||
|
||||
/** Wrong: pops on {@code <=}, so an equal value is reported as "greater". */
|
||||
public static int[] nextGreaterPopsEqual(int[] a) {
|
||||
int[] result = new int[a.length];
|
||||
Arrays.fill(result, -1);
|
||||
Deque<Integer> pending = new ArrayDeque<>();
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
while (!pending.isEmpty() && a[pending.peek()] <= a[i]) { // should be <
|
||||
result[pending.pop()] = a[i];
|
||||
}
|
||||
pending.push(i);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Wrong: the histogram loop without the final height-0 bar, so bars still on the stack are never measured. */
|
||||
public static int largestRectangleNoSentinel(int[] heights) {
|
||||
int n = heights.length;
|
||||
int best = 0;
|
||||
Deque<Integer> rising = new ArrayDeque<>();
|
||||
for (int i = 0; i < n; i++) { // should run to i <= n
|
||||
while (!rising.isEmpty() && heights[rising.peek()] >= heights[i]) {
|
||||
int height = heights[rising.pop()];
|
||||
int leftEdge = rising.isEmpty() ? -1 : rising.peek();
|
||||
best = Math.max(best, height * (i - leftEdge - 1));
|
||||
}
|
||||
rising.push(i);
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Wrong: pours {@code in} onto {@code out} on every dequeue, even when {@code out} still holds older items. */
|
||||
public static final class PourAlwaysQueue {
|
||||
private final Deque<Integer> in = new ArrayDeque<>();
|
||||
private final Deque<Integer> out = new ArrayDeque<>();
|
||||
|
||||
public void enqueue(int x) {
|
||||
in.push(x);
|
||||
}
|
||||
|
||||
public int dequeue() {
|
||||
while (!in.isEmpty()) { // should be guarded by out.isEmpty()
|
||||
out.push(in.pop());
|
||||
}
|
||||
return out.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.ankurm.interviewlab.stackqueue;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/**
|
||||
* Problem 9: a FIFO queue built from two LIFO stacks. New items go onto {@code in}. Items leave from {@code out};
|
||||
* when {@code out} is empty, everything in {@code in} is poured over, which reverses it into queue order.
|
||||
*/
|
||||
public final class QueueViaStacks<T> {
|
||||
private final Deque<T> in = new ArrayDeque<>();
|
||||
private final Deque<T> out = new ArrayDeque<>();
|
||||
private long transfers;
|
||||
|
||||
public void enqueue(T item) {
|
||||
in.push(item);
|
||||
}
|
||||
|
||||
public T dequeue() {
|
||||
pourIfNeeded();
|
||||
if (out.isEmpty()) {
|
||||
throw new NoSuchElementException("queue is empty");
|
||||
}
|
||||
return out.pop();
|
||||
}
|
||||
|
||||
public T peek() {
|
||||
pourIfNeeded();
|
||||
if (out.isEmpty()) {
|
||||
throw new NoSuchElementException("queue is empty");
|
||||
}
|
||||
return out.peek();
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return in.size() + out.size();
|
||||
}
|
||||
|
||||
/** Total number of single-element moves from {@code in} to {@code out} so far. */
|
||||
public long transferCount() {
|
||||
return transfers;
|
||||
}
|
||||
|
||||
/** The two stacks, top first, for traces. */
|
||||
public String snapshot() {
|
||||
return "in=" + in + " out=" + out;
|
||||
}
|
||||
|
||||
private void pourIfNeeded() {
|
||||
if (out.isEmpty()) { // only when out is empty: pouring onto a non-empty out would put new items ahead of old ones
|
||||
while (!in.isEmpty()) {
|
||||
out.push(in.pop());
|
||||
transfers++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.ankurm.interviewlab.stackqueue;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
|
||||
/** Problem 2: evaluate a Reverse Polish Notation expression. Division truncates toward zero, as Java's does. */
|
||||
public final class Rpn {
|
||||
private Rpn() {}
|
||||
|
||||
public static int evaluate(String[] tokens) {
|
||||
Deque<Integer> operands = new ArrayDeque<>();
|
||||
for (String token : tokens) {
|
||||
switch (token) {
|
||||
case "+", "-", "*", "/" -> {
|
||||
int right = operands.pop(); // the second operand is on top
|
||||
int left = operands.pop();
|
||||
operands.push(apply(token, left, right));
|
||||
}
|
||||
default -> operands.push(Integer.parseInt(token));
|
||||
}
|
||||
}
|
||||
if (operands.size() != 1) {
|
||||
throw new IllegalArgumentException("malformed expression: " + operands.size() + " values left");
|
||||
}
|
||||
return operands.pop();
|
||||
}
|
||||
|
||||
static int apply(String operator, int left, int right) {
|
||||
return switch (operator) {
|
||||
case "+" -> left + right;
|
||||
case "-" -> left - right;
|
||||
case "*" -> left * right;
|
||||
case "/" -> left / right;
|
||||
default -> throw new IllegalArgumentException("unknown operator " + operator);
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.ankurm.interviewlab.stackqueue;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Queue;
|
||||
|
||||
/**
|
||||
* Problem 10: a LIFO stack built from one FIFO queue. After each push, every older item is rotated behind the new
|
||||
* one, so the newest item sits at the front of the queue, which is exactly where pop and top read from.
|
||||
*/
|
||||
public final class StackViaQueue<T> {
|
||||
private final Queue<T> queue = new ArrayDeque<>();
|
||||
private long rotations;
|
||||
|
||||
public void push(T item) {
|
||||
queue.offer(item);
|
||||
for (int i = queue.size() - 1; i > 0; i--) {
|
||||
queue.offer(queue.poll());
|
||||
rotations++;
|
||||
}
|
||||
}
|
||||
|
||||
public T pop() {
|
||||
if (queue.isEmpty()) {
|
||||
throw new NoSuchElementException("stack is empty");
|
||||
}
|
||||
return queue.poll();
|
||||
}
|
||||
|
||||
public T top() {
|
||||
if (queue.isEmpty()) {
|
||||
throw new NoSuchElementException("stack is empty");
|
||||
}
|
||||
return queue.peek();
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return queue.size();
|
||||
}
|
||||
|
||||
/** Total number of single-element rotations so far. */
|
||||
public long rotationCount() {
|
||||
return rotations;
|
||||
}
|
||||
|
||||
/** The queue, front first (the front is the top of the stack), for traces. */
|
||||
public String snapshot() {
|
||||
return "queue(front=top)=" + queue;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user