{"steppers":{"java":[{"id":"t0-1","no":"0.1","title":"Your first Java program","imp":"extra","quiz":[["Which method signature does the JVM look for to start a program?",["public void main(String[] args)","public static void main(String[] args)","static int main(String args)","public static void start(String[] args)"],1,"It must be public, static, void, named main, with a String[] parameter (Java 25 also allows simpler forms in compact source files).","E"],["What does <code>javac Hello.java</code> produce?",["A native .exe for your OS","A .jar archive","Hello.class containing bytecode","Nothing until you run java"],2,"javac compiles source to platform-neutral bytecode; the JVM runs it.","E"],["A file <code>Main.java</code> contains <code>public class App</code>. What happens?",["It runs, and the JVM uses App as the entry point","Compile error: a public class must be in a file of the same name","It compiles, but running java Main then fails","javac renames the class to Main automatically"],1,"One public top-level class per file, and the file is named after it.","M"],["What does the JVM do with a <code>.class</code> file?",["Turns it back into Java source first","Loads its bytecode, verifies it and runs it","Sends it to the OS to execute directly","Compresses it into a JAR"],1,"The JVM loads, verifies and executes (interprets/JIT-compiles) bytecode.","E"],["What does <code>System.out.println(\"a\" + 1 + 2)</code> print?",["a3","a12","3a","Compile error"],1,"Left to right: \"a\" + 1 = \"a1\", then + 2 = \"a12\".","M"],["And <code>System.out.println(1 + 2 + \"a\")</code>?",["12a","a3","3a","Compile error"],2,"1 + 2 = 3 first (int math), then \"3\" + \"a\".","M"],["You run <code>java Hello</code> but get \"Could not find or load main class Hello\". Most likely cause?",["main is missing, so the JVM can't start the class","The class wasn't compiled, or you're in the wrong folder / classpath","The installed JVM is too old for the bytecode","The source file still contains a comment block"],1,"java looks for Hello.class on the classpath (current directory by default).","E"],["What does <code>javac</code> report when you forget a semicolon?",["A compile error with the file and line","A warning, then it runs anyway","A runtime exception","Nothing: semicolons are optional"],0,"Syntax errors stop compilation before anything runs.","E"]]},{"id":"t0-2","no":"0.2","title":"Variables, types and operators","imp":"good","quiz":[["<code>int x = 7 / 2;</code> What is x?",["3.5","4","3","Compile error"],2,"Integer division drops the fraction (it doesn't round).","E"],["<code>int i = 5; int a = i++; int b = ++i;</code> What are a and b?",["a = 6, b = 7","a = 5, b = 6","a = 6, b = 6","a = 5, b = 7"],3,"i++ yields 5 (i becomes 6); ++i makes i 7 and yields 7.","M"],["<code>long big = Integer.MAX_VALUE + 1;</code> What is big?",["-2147483648","2147483648","Compile error","ArithmeticException"],0,"The addition happens in int and overflows before the result is widened to long.","H"],["Which type would you use for a whole number that may exceed 2.1 billion?",["int","short","long","float"],2,"int tops out at 2,147,483,647.","E"],["<code>int r = 17 % 5;</code> What is r?",["3","2","3.4","12"],1,"17 = 3 × 5 + 2.","E"],["<code>boolean b = (5 > 3) || (1 / 0 > 0);</code> What happens?",["ArithmeticException: / by zero","b is false","b is true; the right side never runs","Compile error"],2,"|| short-circuits once the left side is true.","M"],["<code>int x = 3; x += 2.7;</code> What is x?",["5.7","5","6","Compile error"],1,"Compound assignment includes an implicit cast back to int (truncation).","H"],["<code>var count = 10;</code> What type is count?",["Object","dynamic, it can change later","int, inferred at compile time","Integer"],2,"var is local type inference; the type is fixed.","M"]]},{"id":"t0-3","no":"0.3","title":"Control flow: if, switch and loops","imp":"extra","quiz":[["In a for loop, what does <code>continue</code> do?",["Exits the loop","Skips to the next iteration","Restarts the loop from the beginning","Pauses the thread"],1,"break exits; continue skips the rest of the current pass.","E"],["Which loop always runs its body at least once?",["while","for","enhanced for","do-while"],3,"do-while checks the condition after the body.","E"],["Classic switch: <code>case 1: x = \"one\"; case 2: x = \"two\"; break;</code>. With value 1, x is?",["\"one\"","\"two\"","null","Compile error"],1,"No break after case 1, so it falls through into case 2.","M"],["How many times does <code>for (int i = 0; i &lt; 5; i++)</code> run its body?",["4","5","6","Forever"],1,"i = 0, 1, 2, 3, 4.","E"],["<code>while (x &gt; 0) { x--; }</code> with x = 0 at the start. How many iterations?",["0","1","Infinite","-1"],0,"while checks the condition before the first pass.","E"],["Which loop is best for visiting every element of a List when you don't need the index?",["A for loop with list.get(i)","do-while","The enhanced for: for (T x : list)","A switch"],2,"It uses the iterator and works for any Iterable.","E"],["Inside nested loops, a plain <code>break</code> exits?",["Both loops","Only the innermost loop","The method","The outer loop only"],1,"Use a labelled break (outer: … break outer;) to exit both.","M"],["A switch expression on a String has cases \"A\" and \"B\" but no default. What happens?",["Compile error: switch expressions must be exhaustive","It returns null for any value not listed","It compiles but throws only at run time","It falls through to the \"B\" case by default"],0,"Only enums/sealed types can be exhaustive without default.","H"]]},{"id":"t0-4","no":"0.4","title":"Arrays","imp":"good","quiz":[["<code>int[] a = new int[3];</code> What is <code>a[2]</code>?",["null","0","Undefined garbage","ArrayIndexOutOfBoundsException"],1,"Numeric arrays start filled with 0.","E"],["<code>int[] b = a; b[0] = 9;</code> What is <code>a[0]</code>?",["9: both names refer to one array","0: the assignment made b a copy","Compile error: b must be declared new","It depends on the JVM implementation"],0,"Arrays are objects; assignment copies the reference.","M"],["How do you print an array's contents?",["System.out.println(arr)","arr.toString()","Arrays.toString(arr)","String.valueOf(arr)"],2,"Arrays don't override toString, so printing shows type@hash.","M"],["What is the index of the last element of <code>int[] a = new int[10]</code>?",["10","9","11","0"],1,"Indexes run from 0 to length − 1.","E"],["<code>String[] names = new String[3];</code> What does <code>names[0]</code> hold?",["\"\"","\"null\"","null","It throws"],2,"Object arrays start filled with null.","E"],["Can an array's size change after it's created?",["Yes, by calling add() on the array","No: create a new array or use ArrayList","Yes, by assigning a new value to length","Only arrays of primitives like int[]"],1,"Arrays are fixed-size.","E"],["<code>int[] a = {5, 2, 9}; Arrays.sort(a);</code> What is a now?",["[9, 5, 2]","[5, 2, 9]","A new array is returned; a is unchanged","[2, 5, 9]"],3,"Arrays.sort sorts in place, ascending.","M"],["Which loop prints every element safely?",["for (int i = 0; i &lt;= a.length; i++)","for (int i = 1; i &lt;= a.length; i++)","for (int i = 0; i &lt; a.length; i++)","for (int i = a.length; i &gt; 0; i--) print(a[i])"],2,"The others go out of bounds.","M"]]},{"id":"t0-5","no":"0.5","title":"Methods, recursion and the call stack","imp":"good","quiz":[["What does a method with return type <code>void</code> return?",["null","0","Nothing","An empty Optional"],2,"void means it returns no value.","E"],["A recursive method has no base case. What happens?",["It returns 0","StackOverflowError","OutOfMemoryError: heap","The JIT turns it into a loop"],1,"Each call adds a frame until the thread's stack is full.","M"],["<code>factorial(3)</code> calls itself down to factorial(1). How many factorial frames exist at the deepest point?",["1","2","4","3"],3,"factorial(3), (2) and (1) are all on the stack at once.","M"],["Which keyword sends a value back from a method?",["yield","break","return","send"],2,"return value; ends the method and passes the value back.","E"],["Two methods: <code>sum(int, int)</code> and <code>sum(int, int, int)</code>. What is this called?",["Overriding","Overloading","Recursion","Hiding"],1,"Same name, different parameter lists.","E"],["A local variable declared inside a method is visible where?",["In the whole class","Only inside that method (its block)","In every method called from it","Everywhere"],1,"Locals live in the method's stack frame.","E"],["What does this return: <code>int sumTo(int n) { return n == 0 ? 0 : n + sumTo(n - 1); }</code> for n = 4?",["4","10","24","StackOverflowError"],1,"4 + 3 + 2 + 1 + 0.","M"],["A <code>void</code> method has <code>return;</code> in the middle. What happens?",["Compile error","It returns null","It ends the method early","It's ignored"],2,"return; exits a void method.","M"]]},{"id":"t0-6","no":"0.6","title":"Classes, objects and constructors","imp":"good","quiz":[["What does a constructor do?",["Destroys an old object before reuse","Initialises a newly created object","Copies an existing object field by field","Compares two objects for equality"],1,"It runs once per new object to set its starting state.","E"],["<code>Account a = new Account(\"Ana\"); Account c = a; c.deposit(100);</code> Does a's balance change?",["Yes: a and c are the same object","No: c is a copy","Only if deposit is static","Compile error"],0,"Object variables hold references; assignment shares the object.","M"],["Inside a constructor, what does <code>this.owner = owner</code> do?",["Compares the field to the parameter","Assigns the field to itself","Copies the parameter into the object's field","Creates a new object"],2,"this.owner is the field; owner alone is the parameter that shadows it.","M"],["How do you create an object of class Car?",["Car c = Car();","Car c = new Car();","Car c = create Car;","new c = Car();"],1,"new allocates the object and runs a constructor.","E"],["What is the default value of an object field of type String?",["\"\"","null","\"null\"","It must be set, or compile error"],1,"Fields get default values; locals don't.","E"],["A constructor has which return type?",["void, like any method returning nothing","The class type, since it builds an instance","None: constructors have no return type","Object, the parent of every class"],2,"Adding void turns it into an ordinary method.","M"],["Why make fields <code>private</code> and expose methods instead?",["Private fields are faster for the JVM to access","So the class controls changes and keeps its data valid","Java forbids public fields on normal classes","Private fields take up less memory per object"],1,"That's encapsulation.","E"],["<code>class A { int x; }</code> <code>A a1 = new A(); A a2 = new A(); a1.x = 5;</code> What is <code>a2.x</code>?",["5","0","null","Compile error"],1,"Each object has its own copy of instance fields.","M"]]},{"id":"t0-7","no":"0.7","title":"Packages, imports and access modifiers","imp":"good","quiz":[["Which modifier makes a member visible only inside its own class?",["private","protected","(no modifier)","final"],0,"private is the most restrictive.","E"],["A field has no access modifier. Who can see it?",["Everyone, like public","Only the class itself","Classes in the same package","Only its subclasses"],2,"No keyword = package-private.","M"],["What does an <code>import</code> statement do?",["Loads the class into memory at startup","Copies the class into your package","Makes private members accessible","Lets you use a class's short name"],3,"Imports are a compile-time naming shortcut only.","M"],["Which classes don't need an import?",["Classes in java.util, like List and Map","Classes in java.lang and in the same package","Every class that ships with the JDK","None: every class needs an import"],1,"String, Math, Integer… are in java.lang.","E"],["What does the package declaration have to match?",["The name of the public class in the file","The folder structure of the source file","The name of the JAR it will be packaged in","Nothing: it's only a label"],1,"com.shop.order ↔ com/shop/order/.","E"],["Which access level should most fields have?",["public","protected","private","package-private"],2,"Expose behaviour through methods instead.","E"],["A protected field in class Base (package a). A subclass Child in package b. Can Child's methods use the inherited field?",["Yes","No","Only if static","Only with an import"],0,"protected = package + subclasses.","M"],["What does <code>import java.util.*;</code> import?",["All classes in java.util and its sub-packages","All classes directly in java.util (not sub-packages)","Only interfaces","Nothing"],1,"java.util.concurrent still needs its own import.","M"]]},{"id":"t1-1","no":"1.1","title":"JDK, JRE, JVM and the JIT","imp":"good","quiz":[["A service is fast in steady state, but the first requests after each deploy are slow. Most likely cause?",["The young generation starts small and only grows after the first full GC","Hot code still runs interpreted or in C1 until the JIT has profiled and compiled it","Bytecode is re-verified on each request until the class is marked trusted","String literals are interned on first use, which locks the String pool"],1,"Execution starts in the interpreter. C1, then C2, compile hot code once invocation and back-edge counters cross their thresholds: that's JIT warm-up.","E"],["<code>main()</code> is called once but contains a loop that runs 10 million times. How does that loop get compiled?",["It doesn't: only methods with a high invocation count are ever compiled","C1 compiles main() as soon as the loop's first back-edge is seen","On-Stack Replacement compiles the loop and switches the running frame into it","javac unrolls loops with constant bounds, so no JIT step is needed"],2,"Back-edge counters trigger OSR, which swaps the interpreted frame for a compiled one while the loop is still running.","M"],["C2 inlined a virtual call because only <code>Car</code> was ever seen there. Later <code>Truck extends Car</code> is loaded and reaches that call. What happens?",["The compiled code is deoptimised back to the interpreter and may be recompiled","Truck keeps running Car's inlined body until the code cache is flushed","Loading Truck fails with IncompatibleClassChangeError at that call site","The JIT adds a type guard to the compiled code without ever leaving it"],0,"C2 optimisations are speculative. When an assumption (class hierarchy, branch never taken) breaks, the code is made not entrant and execution falls back to the interpreter.","H"],["Which part of the JVM checks that bytecode won't break memory safety before it runs?",["The garbage collector","The bytecode verifier","javac","The JIT"],1,"Verification checks types, stack use and jumps.","E"],["What is a \"stack machine\" in the context of bytecode?",["Bytecode pushes and pops values on an operand stack","A machine designed to run recursive code fast","The thread's call stack that holds the frames","A CPU that executes bytecode natively"],0,"e.g. iload, iadd, istore.","M"],["What's the main job of C1 vs C2 in HotSpot?",["C1 interprets bytecode while C2 compiles it","C1 compiles fast; C2 optimises the hottest code","C1 targets desktops, C2 targets large servers","C2 compiles first and C1 cleans up afterwards"],1,"Tiered compilation.","M"],["Which JIT optimisation copies a small method's body into its caller?",["Escape analysis","Inlining","Loop unrolling","Deoptimisation"],1,"Inlining enables further optimisations.","E"],["Why does a JMH benchmark run warm-up iterations first?",["To warm the disk cache with the class files","To let the JIT compile hot code before measuring","To load test data into memory first","To trigger a full GC before measuring"],1,"Measuring cold code measures the interpreter.","M"]]},{"id":"t1-2","no":"1.2","title":"Class loading","imp":"good","quiz":[["Your code asks for <code>java.lang.String</code>. Which class loader actually loads it?",["The application loader, because it received the request first","Whichever loader finds a matching class first on the classpath","The bootstrap loader, because loaders delegate to their parent first","The platform loader, which owns every java.* package"],2,"Parent-first delegation: app → platform → bootstrap. Core classes such as java.lang.String come from the bootstrap loader, so they can't be spoofed.","E"],["Code compiled fine, but at run time it throws <code>NoClassDefFoundError</code> (not ClassNotFoundException). Classic cause?",["Class.forName was called with a misspelled class name at run time","Two class loaders loaded the class and the JVM couldn't choose one","The class's constructor threw an exception while running new","The class existed at compile time but is missing now, or its static init failed"],3,"ClassNotFoundException comes from explicit loading (forName, loadClass). NoClassDefFoundError means linking to a class seen at compile time failed: a missing JAR, or an earlier ExceptionInInitializerError.","M"],["Library A has <code>static final int MAX = 10;</code> used by app B. You change it to 20 and redeploy only A's JAR. What does B see?",["20, because static fields are always read from the defining class","10, because compile-time constants are inlined into B's bytecode","20, but only after B's classes are reloaded by a new class loader","B fails at startup with IncompatibleClassChangeError"],1,"Compile-time constants are copied into the calling class at compile time. B must be recompiled to see 20.","H"],["When is a class typically loaded?",["At JVM startup, all at once","The first time it's actually needed","When javac compiles it","Only when Class.forName is called"],1,"Loading is lazy.","E"],["Which loader loads your application's classes from the classpath?",["The bootstrap class loader","The platform class loader","Application (system) class loader","The JIT compiler's loader"],2,"It delegates to platform and bootstrap first.","E"],["What happens if a static initialiser throws an exception?",["It's retried the next time the class is used","ExceptionInInitializerError; the class stays unusable","The error is ignored and fields keep defaults","The class loader restarts and tries again"],1,"Avoid risky work in static blocks.","M"],["During \"preparation\", what values do static fields get?",["Their declared initial values","Default values (0, null, false)","Random values","None until first use"],1,"Initialisers run later, at initialisation.","M"],["Two threads trigger initialisation of the same class at once. What does the JVM guarantee?",["Both threads run the static block once each","Static init runs exactly once; the other thread waits","The JVM deadlocks the two threads","The second thread gets an exception"],1,"That's why the holder idiom is thread-safe.","M"]]},{"id":"t1-3","no":"1.3","title":"JVM memory: stack vs heap","imp":"must","quiz":[["Inside a method, <code>Car c = new Car();</code>. Where do the object and the variable live?",["Object on the heap, the reference in the method's stack frame","Both on the stack, since the object never leaves the method","Object in the thread's stack, the reference in Metaspace","Both on the heap, because Java variables are all objects"],0,"Objects live on the shared heap; locals (including references) live in the thread's stack frame. Escape analysis can optimise this, but that's the model.","E"],["A recursive method with no base case runs. What is thrown?",["OutOfMemoryError: Java heap space, as each frame is allocated on the heap","OutOfMemoryError: unable to create native thread","StackOverflowError","Nothing: the JIT turns tail calls into a loop, so it runs forever"],2,"Each call pushes a frame on the thread's fixed-size stack. Java has no tail-call optimisation.","M"],["An app generates many classes at run time (dynamic proxies, script engines) and eventually dies. Which space is most likely exhausted?",["PermGen, which still holds class data in Java 17","The code cache, which stores generated classes","The old generation, where Class objects live forever","Metaspace, which holds class metadata in native memory"],3,"Class metadata lives in Metaspace since Java 8 (PermGen is gone). Unbounded class generation or class loader leaks give OutOfMemoryError: Metaspace.","H"],["Where do static fields' values live?",["On the stack of the thread that set them","On the heap, with the Class object","In CPU registers for faster access","In the JIT's code cache with the methods"],1,"Since Java 8, static fields live with the Class mirror on the heap.","H"],["Each thread has its own...",["heap","stack","Metaspace","String pool"],1,"The heap is shared by all threads.","E"],["When is a method's local variable memory freed?",["At the next garbage collection run","When the method returns and its frame pops","When the owning thread itself ends","Never, locals stay until JVM exit"],1,"Stack frames are freed instantly.","E"],["What does <code>-Xmx2g</code> set?",["Stack size","Maximum heap size","Metaspace size","Thread count"],1,"-Xms sets the initial heap.","E"],["Which error means the JVM couldn't create a new thread?",["StackOverflowError: thread stack exhausted","OutOfMemoryError: unable to create native thread","OutOfMemoryError: Java heap space","IllegalThreadStateException on start()"],1,"OS limits or native memory ran out, often from unbounded thread creation.","M"]]},{"id":"t1-4","no":"1.4","title":"Garbage collection","imp":"must","quiz":[["Two objects reference each other, but nothing else references either. Will they be collected?",["No: each still has a reference count of 1","Yes: tracing starts at GC roots and neither is reachable","Only if one of the two references is a WeakReference","Only after both are promoted and a full GC runs"],1,"Java's GC traces from roots; it doesn't count references. Unreachable cycles are garbage.","E"],["Why is a young-generation GC usually cheap even when Eden is large?",["It only marks objects and leaves sweeping to a background thread","It runs concurrently, so the application never pauses for it","Its cost tracks the live objects it copies, and most young objects are dead","It ignores references from the old generation, so it scans less"],2,"Copying collectors only touch survivors (weak generational hypothesis). Old→young references are tracked with card tables, not ignored.","M"],["Heap usage after each full GC creeps up over days until OutOfMemoryError. Best first step?",["Take a heap dump and check the dominator tree for what retains memory","Raise -Xmx; if usage levels off higher, it wasn't a leak","Switch to ZGC, which reclaims objects that G1 misses","Call System.gc() on a schedule to keep the floor down"],0,"A leak is \"reachable but useless\". The dominator tree and path to GC roots show what is holding memory and why. More heap only delays the crash.","H"],["What decides whether an object is garbage?",["How long ago it was created","Whether it's reachable from GC roots","How many bytes it occupies","Whether its finalize() has already run"],1,"Unreachable = collectable.","E"],["Which of these is a GC root?",["A local variable in an active stack frame","An object in a HashMap that nothing references","An unreachable cycle","Any object older than 1 minute"],0,"Also static fields and JNI references.","E"],["What is a stop-the-world pause?",["A JVM crash that halts all threads","App threads paused while the GC works","A thread dump that freezes the app","A deadlock among application threads"],1,"Modern collectors keep these short.","E"],["Why does <code>System.gc()</code> usually not help?",["It's only a hint, and a forced full GC usually hurts latency","It deletes every object, including live ones","It's illegal to call since Java 17","It turns off the JIT until the next restart"],0,"Let the collector decide.","M"],["Which collector is the default in modern HotSpot for most server JVMs?",["Serial","CMS","G1","Epsilon"],2,"CMS was removed in Java 14.","M"]]},{"id":"t1-5","no":"1.5","title":"Reference types: strong, soft, weak, phantom","imp":"extra","quiz":[["When does the GC clear a softly-reachable object?",["At the next GC cycle, exactly like a weak reference","When the SoftReference variable goes out of scope","Under memory pressure; always before OutOfMemoryError","After a fixed time, regardless of free memory"],2,"Soft references are cleared at the GC's discretion under memory pressure. Weak references are cleared at the next GC that finds them weakly reachable.","E"],["A <code>WeakHashMap&lt;Key, Value&gt;</code> never shrinks, even though nothing else uses the keys. Likely bug?",["Each value holds a strong reference back to its own key","WeakHashMap only clears entries when purge() is called","Weak references are only cleared during a full GC","Reading the map from several threads pins its entries"],0,"Values are held strongly by the map. If value → key, the key stays strongly reachable and is never cleared.","M"],["What's the modern replacement for <code>finalize()</code> to release a native resource once an object is unreachable?",["Overriding finalize(), which is still the supported hook in Java 21","A SoftReference, so cleanup waits until memory is needed","A WeakReference whose get() can revive the object for cleanup","java.lang.ref.Cleaner, which runs an action once the object is phantom reachable"],3,"Cleaner uses phantom reachability for post-mortem cleanup. finalize() is deprecated for removal. Still prefer explicit close() with try-with-resources.","H"],["Which reference type is cleared at the next GC once nothing stronger points to the object?",["Strong","Soft","Weak","Phantom"],2,"Soft waits for memory pressure.","E"],["What does <code>weakRef.get()</code> return after the object is collected?",["The old object","null","An exception","A new instance"],1,"Always check for null.","E"],["Why can a phantom reference's get() never return the object?",["It's a known JDK bug kept for compatibility","It's post-mortem only: no resurrection allowed","Phantom references always start out as null","get() is synchronized on the GC thread"],1,"Used with ReferenceQueue / Cleaner.","M"],["What does a ReferenceQueue tell you?",["Which objects are still strongly reachable","That a registered reference has been cleared by the GC","How long each GC pause took","How much heap is still free"],1,"Lets you clean up associated resources.","M"],["Which is a typical use of WeakHashMap?",["As the primary store for application data","Metadata for objects you don't own, without leaks","A thread-safe cache shared by all requests","Keeping keys sorted by insertion time"],1,"Entries vanish when keys become unreachable.","M"]]},{"id":"t1-6","no":"1.6","title":"Pass-by-value (always)","imp":"must","quiz":[["<pre>void reset(Car c) { c = new Car(\"Blank\"); }\nCar car = new Car(\"Tesla\"); reset(car);\nSystem.out.println(car.name);</pre>What prints?",["Blank, because objects are passed by reference","Tesla","null, because reset releases the old reference","Nothing: parameters are implicitly final, so it won't compile"],1,"The reference is copied. Reassigning the parameter changes only the copy; the caller's variable still points to Tesla.","E"],["<pre>void rename(Car c) { c.name = \"Blank\"; }\nCar car = new Car(\"Tesla\"); rename(car);</pre>What is <code>car.name</code> now?",["Blank","Tesla, because Java passes a copy of the object","Tesla, because String fields are immutable","null, because the parameter's changes are discarded"],0,"Both references point to the same object, so mutating it through the parameter is visible to the caller.","E"],["Which statement is correct?",["Primitives are passed by value; objects are passed by reference","Objects are passed by reference, except Strings, which are copied","Java is always pass-by-value; for objects, the value copied is the reference","Arrays are passed by reference; everything else is passed by value"],2,"There's no pass-by-reference in Java, which is why a swap(a, b) method can't change the caller's variables.","M"],["<pre>void inc(int n) { n++; }\nint x = 1; inc(x);</pre>What is x?",["2","1","0","Compile error"],1,"The int value is copied.","E"],["<pre>void clear(List&lt;String&gt; l) { l.clear(); }</pre>Called with a list of 3 items. Afterwards the caller's list has?",["3 items","0 items","null","It throws"],1,"Same object, mutated through the copied reference.","E"],["<pre>void reset(String s) { s = \"new\"; }\nString t = \"old\"; reset(t);</pre>What is t?",["\"new\"","\"old\"","null","\"\""],1,"Reassigning the parameter doesn't affect the caller, and Strings are immutable anyway.","M"],["How can a method give back two values to its caller?",["Use two return statements in a row","Return a small result object or record","Swap the values into the caller's variables","Pass the variables by reference"],1,"e.g. record MinMax(int min, int max).","M"],["<pre>void grow(StringBuilder sb) { sb.append(\"!\"); sb = new StringBuilder(\"x\"); }\nStringBuilder b = new StringBuilder(\"hi\"); grow(b);</pre>What is b?",["hi","hi!","x","x!"],1,"The append mutates the shared object; the reassignment is local.","H"]]},{"id":"t1-7","no":"1.7","title":"Wrappers, autoboxing, Integer cache","imp":"must","quiz":[["<pre>Integer a = 127, b = 127, c = 128, d = 128;\nSystem.out.println((a == b) + \" \" + (c == d));</pre>",["true true","false false","false true","true false"],3,"Integer.valueOf caches -128..127 by default, so a and b are the same object; 128 creates two objects. Always compare with equals.","M"],["<pre>Integer x = null;\nint y = flag ? x : 0;</pre>When <code>flag</code> is true, what happens?",["y is 0, because a null Integer converts to 0","NullPointerException from unboxing x","Compile error: Integer and int can't be mixed in a ternary","The result is boxed, so y becomes null"],1,"The ternary has a primitive branch, so its type is int and x is unboxed. Unboxing null throws NPE.","H"],["<code>List&lt;Integer&gt; list = new ArrayList&lt;&gt;(List.of(10, 20, 30)); list.remove(1);</code> What's the list now?",["[10, 30]","[20, 30]","[10, 20, 30], since the value 1 isn't in the list","Compile error: the call is ambiguous"],0,"remove(int index) is chosen over remove(Object), so index 1 (the value 20) goes. Use remove(Integer.valueOf(20)) to remove by value.","M"],["What is autoboxing?",["Converting an Integer into its String form","Automatic primitive → wrapper conversion","Packing several objects into one JAR entry","Sorting boxed values automatically"],1,"Unboxing is the reverse.","E"],["How should two Integer objects be compared for equal values?",["a == b, since both are Integers","a.equals(b) or Objects.equals(a, b)","a.compareTo(b) == 1","a.hashCode() == b.hashCode() only"],1,"== compares references.","E"],["<code>Map&lt;String,Integer&gt; m = new HashMap&lt;&gt;(); int n = m.get(\"x\");</code> Result?",["n = 0","NullPointerException","n = -1","Compile error"],1,"get returns null, unboxing null throws. Use getOrDefault.","M"],["Why is <code>Long sum = 0L; for (...) sum += i;</code> slow in a hot loop?",["Long arithmetic is slower than int on every CPU","Each += unboxes and creates a new Long object","The sum overflows after a few iterations","It isn't slower than using a primitive long"],1,"Use the primitive long.","M"],["<code>Integer a = 1000, b = 1000; a.equals(b)</code>?",["true","false","NullPointerException","Compile error"],0,"equals compares values regardless of caching.","E"]]},{"id":"t1-8","no":"1.8","title":"String pool, == vs equals, StringBuilder","imp":"must","quiz":[["Building a 100,000-line report with <code>s += line</code> in a loop is slow. Why?",["String concatenation is synchronized, so it contends","Each new String is interned, and the pool keeps resizing","Each += creates a new String and copies everything so far: O(n²)","Loops that concatenate strings can't be JIT-compiled"],2,"Strings are immutable, so every concatenation copies the whole result. Use one StringBuilder.","E"],["Which is NOT a reason String is immutable?",["Pooled literals can be shared safely","Its hash code can be cached for HashMap keys","A validated path or class name can't change after the check","So that == can safely compare content"],3,"== always compares references for objects. Immutability enables pooling, hash caching and security, not content comparison with ==.","M"],["<pre>final String a = \"ja\";\nString b = \"ja\";\nSystem.out.println((a + \"va\" == \"java\") + \" \" + (b + \"va\" == \"java\"));</pre>",["true false","false false","true true","false true"],0,"a is a compile-time constant, so a + \"va\" is folded into the pooled literal \"java\". b isn't final, so b + \"va\" is built at run time as a new String.","H"],["Which is the right way to check two Strings have the same text?",["s1 == s2","s1.equals(s2)","s1.hashCode() == s2.hashCode()","s1.compareTo(s2) == 1"],1,"equals compares characters.","E"],["What does <code>s.toUpperCase()</code> do to s?",["Changes s in place to upper case","Returns a new String; s is unchanged","Throws if s has no lower-case letters","Interns s and returns the pooled copy"],1,"Strings are immutable.","E"],["Safest way to compare a variable with a literal when the variable may be null?",["input.equals(\"yes\")","\"yes\".equals(input)","input == \"yes\"","input.compareTo(\"yes\")"],1,"The literal is never null. Objects.equals also works.","M"],["<code>\"a,b,,c\".split(\",\")</code> returns how many elements?",["3","4","5","2"],1,"[a, b, \"\", c]; trailing empty strings would be removed, middle ones aren't.","H"],["Why is StringBuilder preferred over String concatenation in a loop?",["StringBuilder is synchronized, so it's safer","It appends into one buffer instead of recopying","It uses less CPU per character in every case","It's immutable, so the JIT can optimise it"],1,"StringBuffer is the old synchronized version.","E"]]},{"id":"t1-9","no":"1.9","title":"static, final, inner classes","imp":"must","quiz":[["<code>final List&lt;String&gt; names = new ArrayList&lt;&gt;();</code> Which is true?",["names.add(\"x\") won't compile, because the list is final","names can't point to another list, but the list's contents can change","The list becomes immutable, so add throws UnsupportedOperationException","final makes the list safe to share between threads"],1,"final applies to the reference, not to the object it points to.","E"],["A <code>static</code> method <code>describe()</code> exists in both Parent and Child. <code>Parent p = new Child(); p.describe();</code> runs which?",["Child's, by dynamic dispatch on the object","Child's, but only if it's annotated @Override","Compile error: a static method can't be redeclared in a subclass","Parent's, because static methods are bound to the declared type"],3,"Static methods are hidden, not overridden. (@Override on a static method doesn't even compile.)","M"],["What does the Java Memory Model guarantee about <code>final</code> instance fields?",["After the constructor finishes (without leaking this), other threads see their values with no synchronization","They behave like volatile fields, so every read goes straight to main memory","They are stored once in Metaspace and shared by every instance of the class","Reflection can never change them, so the JIT may cache them in registers forever"],0,"Final-field semantics give safe publication of immutable objects, as long as this doesn't escape during construction.","H"],["Can a static method use instance fields directly?",["Yes, any static method can read them","No: there's no this in a static method","Only if the fields are declared public","Only inside records, not classes"],1,"It needs an object reference to reach them.","E"],["What does a <code>final</code> method mean?",["It can't be called","It can't be overridden","It runs once","It's static"],1,"final class = can't be extended.","E"],["How many copies of a static field exist with 100 objects?",["100","1","0","Depends on the GC"],1,"Static belongs to the class.","E"],["<code>final int[] a = {1}; a[0] = 2;</code> Allowed?",["No: the array is final, so it can't change","Yes: only the reference a is final","Only inside a static initialiser block","It compiles but fails at run time"],1,"final is about the reference.","M"],["When must a <code>final</code> instance field be assigned?",["Any time before the field is first read","Exactly once, by the end of every constructor","Before main starts, in a static block","Never: final fields keep their defaults"],1,"Otherwise compile error.","M"]]},{"id":"t1-10","no":"1.10","title":"Immutable class and money","imp":"must","quiz":[["<code>0.1 + 0.2 == 0.3</code> is false with doubles. What should you use for money?",["double, rounding with Math.round to two decimals after each step","new BigDecimal(0.1), which converts the double exactly","BigDecimal built from a String, or a long count of minor units (cents)","float, which has enough precision for currency"],2,"Binary floating point can't represent 0.1. new BigDecimal(0.1) faithfully captures the double's error; use BigDecimal(\"0.1\") or BigDecimal.valueOf.","E"],["<code>new BigDecimal(\"2.0\").equals(new BigDecimal(\"2.00\"))</code> returns?",["true, because the numeric values are equal","true, because trailing zeros are stripped on construction","It throws: values with different scales can't be compared","false, because equals compares scale as well as value"],3,"Use compareTo(...) == 0 for numeric equality. This also matters for HashSet&lt;BigDecimal&gt; (TreeSet uses compareTo).","M"],["An \"immutable\" class has <code>private final List&lt;Item&gt; items</code>, and its constructor does <code>this.items = Collections.unmodifiableList(items);</code>. Is it immutable?",["Yes: a final field holding an unmodifiable list is enough","No: the view still tracks the caller's list; copy it with List.copyOf","Yes, as long as the class itself is also declared final","No: unmodifiableList only blocks add(), so set() still works"],1,"unmodifiableList is a read-only view over the original list. Copy on the way in (and Item must be immutable too).","H"],["Which is NOT required for an immutable class?",["final fields","no setters","defensive copies of mutable inputs","a public no-arg constructor"],3,"Immutable classes usually validate everything in one constructor.","E"],["Why are immutable objects naturally thread-safe?",["Immutable classes use locks internally","Their state never changes, so nothing races","Immutable objects are stored on the stack","The JIT shields them from other threads"],1,"Share them freely.","E"],["<code>new BigDecimal(\"1.10\").setScale(1, RoundingMode.HALF_UP)</code>?",["1.1","1.10","1","ArithmeticException"],0,"Scale 1 → one decimal place.","M"],["How should you compare two BigDecimals for numeric equality?",["equals","compareTo(...) == 0","==","hashCode"],1,"equals also compares scale.","M"],["Storing prices as long cents means $12.34 is stored as?",["12.34","1234","12","123400"],1,"Integer minor units avoid floating point errors.","E"]]},{"id":"t1-11","no":"1.11","title":"Shallow vs deep copy","imp":"good","quiz":[["<code>Order copy = original.clone()</code> with the default shallow <code>clone()</code>. Then <code>copy.getItems().add(x)</code>. What happens to <code>original</code>?",["Nothing: clone() copies nested collections too","original.getItems() also contains x, because the list is shared","copy.getItems() is null, because clone skips reference fields","clone() throws CloneNotSupportedException for collections"],1,"A shallow copy duplicates the top-level object but shares nested mutable objects.","E"],["What's the usual recommendation instead of <code>Cloneable</code>?",["A copy constructor or static factory that copies each field explicitly","Serialize and deserialize, which is the fastest deep copy","Implement Cloneable; super.clone() deep-copies by default","BeanUtils.copyProperties, which deep-copies collections"],0,"clone() skips constructors, is shallow and has an awkward contract. A copy constructor is explicit and type-safe.","M"],["A copy constructor does <code>this.items = new ArrayList&lt;&gt;(other.items);</code>, and <code>Item</code> is mutable. Is the copy deep?",["Yes: new ArrayList copies every element it's given","Yes, because the items field is declared final","No: the list is new, but the Item objects are shared","Only if Item implements Cloneable"],2,"new ArrayList(other) copies references. For a deep copy, copy each Item too (or make Item immutable).","H"],["A shallow copy duplicates...",["Everything, recursively, down to the primitives","Only the top-level object; nested objects are shared","Nothing: it returns the same reference","Only the primitive fields; references become null"],1,"Deep copies duplicate nested mutable objects too.","E"],["Why can immutable fields be shared between a copy and the original?",["Immutable fields are static, so they're shared anyway","They can't change, so sharing has no side effects","The GC makes copies of them when needed","They're stored on the stack, not the heap"],1,"Strings, LocalDate, records of immutables.","E"],["What does <code>Object.clone()</code> do by default?",["A deep copy that calls each class's constructor","Shallow field-by-field copy without calling constructors","Serializes the object and reads it back","Nothing, unless you override it"],1,"And requires implementing Cloneable.","M"],["Calling clone() on a class that doesn't implement Cloneable throws?",["NullPointerException","CloneNotSupportedException","ClassCastException","Nothing"],1,"Cloneable is a marker interface.","M"],["<code>int[] b = a.clone();</code> for an int array. Is it independent of a?",["No: array clones always share their storage","Yes: primitive arrays copy their values","Only the first element is copied over","It throws CloneNotSupportedException"],1,"For object arrays it's still shallow (elements shared).","M"]]},{"id":"t2-1","no":"2.1","title":"Picking a collection","imp":"must","quiz":[["Bids stream in and you repeatedly need the current highest bid. Best structure?",["PriorityQueue ordered by amount, highest first","ArrayList, re-sorted with Collections.sort after each insert","LinkedHashMap, which keeps entries in insertion order","HashMap keyed by amount, then max() over keySet()"],0,"A heap gives O(log n) insert and O(1) peek at the best element.","E"],["You need all cars priced between 10k and 20k, in price order. Best choice?",["HashMap, filtering entries by price","PriorityQueue, polling until the price passes 20k","LinkedHashMap, if entries are inserted in price order","TreeMap, using subMap(10_000, true, 20_000, true)"],3,"TreeMap keeps keys sorted and supports range views in O(log n + k). Polling a PriorityQueue destroys it.","M"],["A legacy service uses <code>Hashtable</code> and <code>Vector</code> for thread safety. What should modern code use?",["Keep Hashtable: full synchronization makes check-then-put atomic","Collections.synchronizedMap, which locks per bucket like CHM","ConcurrentHashMap / CopyOnWriteArrayList / BlockingQueue by access pattern","A plain HashMap stored in a volatile field"],2,"Hashtable/Vector lock every call on one monitor, yet compound operations (check-then-put) still race. synchronizedMap is one lock too.","H"],["You need unique user ids with fast \"contains\" checks. Best choice?",["ArrayList","HashSet","LinkedList","ArrayDeque"],1,"O(1) average contains, no duplicates.","E"],["You need a map that iterates in insertion order. Which?",["HashMap","TreeMap","LinkedHashMap","EnumMap"],2,"HashMap has no order; TreeMap sorts by key.","E"],["Which should you use as a stack in new code?",["Stack","Vector","ArrayDeque (push/pop)","LinkedList only"],2,"Stack is a legacy synchronized class.","E"],["A list is read by many threads and changed rarely (listener registry). Which?",["ArrayList","CopyOnWriteArrayList","LinkedList","Vector"],1,"Reads need no locking; writes copy.","M"],["Why declare <code>List&lt;Order&gt; orders = new ArrayList&lt;&gt;()</code> instead of <code>ArrayList&lt;Order&gt;</code>?",["Interface-typed variables run faster","Code depends on the interface, not the class","ArrayList can't be used as a variable type","Generics require the interface type there"],1,"Program to interfaces.","M"]]},{"id":"t2-2","no":"2.2","title":"HashMap internals","imp":"must","quiz":[["You'll insert 1,000,000 entries. Why pre-size, e.g. <code>HashMap.newHashMap(1_000_000)</code>?",["It makes get() O(1) instead of O(log n) on big maps","It avoids repeated resizes, each of which rehashes all entries","It prevents hash collisions between similar keys","A HashMap can't grow past its initial capacity later"],1,"From 16 buckets the table doubles about 17 times, moving every node each time. Pre-sizing skips that.","E"],["A table of 16 buckets. Which bucket for a spread hash of 165 (0b1010_0101)?",["10, taken from the high bits of the hash","165 % 17, since tables use a prime size","15, the last bucket, because 165 ≥ 16","5, because index = hash & (n − 1)"],3,"n is a power of two, so n − 1 is a bit mask: 165 & 15 = 5.","M"],["When does a bucket's linked list become a red-black tree?",["At 8 nodes in a bucket, if the table has ≥ 64 buckets; otherwise it resizes","At 8 nodes in any bucket, whatever the current table size is","When the overall load factor passes 0.75 and the table is full","At 16 nodes in one bucket, matching the default table capacity"],0,"TREEIFY_THRESHOLD = 8 and MIN_TREEIFY_CAPACITY = 64. Trees turn back into lists at 6.","H"],["What is HashMap's default initial capacity?",["10","16","32","100"],1,"It doubles on resize.","E"],["What is the default load factor?",["0.5","0.75","1.0","2.0"],1,"Resize when size > capacity × 0.75.","E"],["How does HashMap find the right entry within a bucket?",["By comparing hashCode values only","By comparing keys with equals","By the order the entries were inserted","By reference equality (==) only"],1,"hashCode picks the bucket, equals picks the entry.","M"],["Can a HashMap have a null key?",["No: null keys throw NullPointerException","Yes, one, stored in bucket 0","Yes, any number of them, all stored together","Only in Java 8 and later versions"],1,"ConcurrentHashMap and Hashtable don't allow null keys.","M"],["What is a hash collision?",["Two equal keys inserted twice","Two different keys landing in the same bucket","The table becoming completely full","Inserting a null key into the map"],1,"Collisions are normal; equals resolves them.","E"]]},{"id":"t2-3","no":"2.3","title":"equals and hashCode contract","imp":"must","quiz":[["A class overrides <code>equals</code> but not <code>hashCode</code>. Two equal instances are added to a HashSet. Size?",["1, because HashSet uses equals to find duplicates","1, because Object.hashCode is derived from the fields","Usually 2, because they land in different buckets","Compile error: equals and hashCode must be overridden together"],2,"The default hashCode is identity-based, so equal objects usually hash to different buckets and equals is never called.","E"],["<pre>Key k = new Key(\"a\"); map.put(k, 1);\nk.setName(\"b\");     // name is used in hashCode\nmap.get(k);</pre>Returns?",["1, because the map holds the same object reference","null: the entry sits in the bucket for the old hash","1, because HashMap rehashes keys on each get","It throws ConcurrentModificationException"],1,"Lookups go to the bucket for the new hash. The entry becomes a ghost you can't reach or remove.","M"],["Which statement about the equals/hashCode contract is true?",["Equal hash codes imply equal objects","Unequal objects must have different hash codes","hashCode may use fields that equals ignores, if it's consistent","Equal objects must have equal hash codes"],3,"Collisions are allowed. Using a field that equals ignores would let two equal objects get different hashes, which breaks the contract.","H"],["Which methods must be overridden together?",["toString and equals","equals and hashCode","hashCode and compareTo","clone and finalize"],1,"From the same fields.","E"],["What does the default <code>Object.equals</code> compare?",["All fields","References (identity)","hashCode values","toString output"],1,"Override it for value semantics.","E"],["What do records generate for equals/hashCode?",["Nothing","Identity-based versions","Versions based on all components","Only hashCode"],2,"That's why records make good map keys.","E"],["Is <code>x.equals(null)</code> allowed to throw?",["Yes, NullPointerException","No: it must return false","Only for Strings","Only if x is null"],1,"Part of the equals contract.","M"],["Why should hashCode be cheap and stable?",["It's only called once, when the key is inserted","Maps call it on every put/get; a changing hash loses entries","Maps use it for sorting keys in order","It doesn't matter as long as equals is correct"],1,"Use immutable fields.","M"]]},{"id":"t2-4","no":"2.4","title":"LinkedHashMap LRU and TreeMap navigation","imp":"good","quiz":[["A <code>TreeMap&lt;Integer,String&gt;</code> has keys 10, 20, 30. What do <code>floorKey(25)</code> and <code>ceilingKey(25)</code> return?",["10 and 30","20 and 30","30 and 20","20 and 20"],1,"floor = greatest key ≤ 25; ceiling = smallest key ≥ 25.","E"],["How do you build an LRU cache with LinkedHashMap?",["new LinkedHashMap&lt;&gt;(cap) and override removeEldestEntry; insertion order is LRU order","new LinkedHashMap&lt;&gt;(cap, 0.75f, true) and removeEldestEntry returning size() &gt; cap","LinkedHashMap is LRU by default; just cap it in the constructor","A TreeMap keyed by last-access timestamp"],1,"accessOrder = true moves an entry to the end on every get; without it you get FIFO, not LRU.","M"],["<code>TreeSet&lt;String&gt;</code> created with <code>String.CASE_INSENSITIVE_ORDER</code>. Add \"Java\", then \"java\". What are <code>size()</code> and <code>contains(\"JAVA\")</code>?",["2 and false","2 and true","1 and true","1 and false"],2,"Sorted sets use the comparator, not equals: compare == 0 means duplicate, and lookups use the comparator too.","H"],["TreeMap keys must be...",["Strings, since TreeMap sorts alphabetically","Comparable, or a Comparator must be supplied","Objects with unique hashCode values","Integers or other numeric wrapper types"],1,"It orders keys with compareTo / compare.","E"],["<code>treeMap.firstKey()</code> returns?",["The first inserted key","The smallest key","A random key","The largest key"],1,"lastKey gives the largest.","E"],["<code>headMap(30)</code> on keys 10, 20, 30, 40?",["{10, 20}","{10, 20, 30}","{30, 40}","{40}"],0,"headMap(toKey) excludes toKey by default.","M"],["What is the cost of TreeMap get/put?",["O(1)","O(log n)","O(n)","O(n log n)"],1,"Red-black tree.","E"],["LinkedHashMap with accessOrder = false iterates in which order?",["Sorted","Insertion order","Most recently used last","Random"],1,"accessOrder = true gives access order.","M"]]},{"id":"t2-5","no":"2.5","title":"ArrayList vs LinkedList","imp":"must","quiz":[["You need fast <code>get(i)</code> on a large list. Which and why?",["LinkedList, because it caches the last index it visited","Either one: both implement the RandomAccess interface","ArrayList: get(i) is an array index; LinkedList walks nodes","LinkedList, because its nodes avoid array copying on get"],2,"Only ArrayList implements RandomAccess. LinkedList traverses from the nearer end.","E"],["What's the amortised cost of <code>ArrayList.add(x)</code> at the end?",["O(n), because every add copies the array","O(log n), because the array doubles each time","O(1) only if ensureCapacity was called first","O(1): capacity grows ~1.5×, so copies are rare"],3,"Occasional O(n) copies spread over many cheap appends average O(1).","M"],["Inserting at index <code>size()/2</code> into a 1M-element list. Which is usually faster in practice?",["ArrayList: one arraycopy shift beats walking 500k nodes","LinkedList: inserting a node is always O(1)","LinkedList, because it can start walking from the tail","Neither: both are O(n) with the same constant factor"],0,"LinkedList insertion is O(1) only once you're at the position; getting there is O(n) pointer chasing, which is far slower than a memmove.","H"],["What happens when an ArrayList's internal array is full and you add?",["It throws IllegalStateException","It allocates a bigger array (~1.5×) and copies","It links a new array chunk to the old one","It overwrites the oldest element"],1,"That's why add is amortised O(1).","E"],["<code>new ArrayList&lt;&gt;(1000)</code> sets what?",["Size 1000, all elements null","Initial capacity 1000; size is 0","A maximum size of 1000 elements","Nothing: the argument is ignored"],1,"Capacity ≠ size.","M"],["Which is O(1) on a LinkedList?",["get(i)","addFirst / removeFirst","contains","indexOf"],1,"Operations at the ends are cheap.","E"],["Iterating a 1M-element LinkedList vs ArrayList: which is typically faster?",["LinkedList, since it never has to resize","ArrayList: contiguous memory suits CPU caches","Same: both are O(n) so they're equally fast","It depends only on the GC settings"],1,"Pointer chasing is cache-unfriendly.","M"],["<code>for (int i = 0; i &lt; linkedList.size(); i++) linkedList.get(i)</code> costs?",["O(n)","O(n²)","O(log n)","O(1)"],1,"Each get(i) walks the list.","H"]]},{"id":"t2-6","no":"2.6","title":"Fail-fast iterators (modCount)","imp":"must","quiz":[["<pre>for (String s : list) if (s.isBlank()) list.remove(s);</pre>Usually throws?",["IllegalStateException from the iterator","IndexOutOfBoundsException","Nothing: the loop skips the removed element","ConcurrentModificationException"],3,"The for-each iterator compares modCount with its expected count on next(). Removing through the list changes modCount.","E"],["Correct way to remove blank strings from an ArrayList?",["list.removeIf(String::isBlank)","A forward index loop calling list.remove(i)","Catch ConcurrentModificationException and continue","Wrap the list in Collections.synchronizedList"],0,"removeIf (or Iterator.remove) keeps the iterator consistent. A forward index loop skips the element after each removal.","M"],["List [a, b, c]. Inside a for-each you remove \"b\" (second-to-last). What happens?",["ConcurrentModificationException on the next iteration","No exception, but c is never visited","c is visited twice","No exception, and c is visited normally"],1,"After the removal size is 2 and the cursor is 2, so hasNext() is false and the loop ends before next() can check modCount. Fail-fast is best-effort.","H"],["What is modCount?",["The list's current number of elements","A count of structural changes","The number of open iterators","The capacity of the backing array"],1,"Used for fail-fast behaviour.","E"],["Does <code>list.set(i, x)</code> during a for-each loop throw CME?",["Yes, any change during iteration throws","No: set isn't a structural modification","Only for LinkedList, not ArrayList","Only when setting the last element"],1,"Structural = size changes.","M"],["Are fail-fast iterators guaranteed to detect all concurrent modifications?",["Yes","No: it's best-effort","Only single-threaded","Only on ArrayList"],1,"Don't rely on CME for correctness.","M"],["How do you safely remove while iterating with an explicit iterator?",["list.remove(x)","it.remove()","list.clear()","it.next() twice"],1,"Iterator.remove keeps counts in sync.","E"],["Iterating a ConcurrentHashMap while another thread adds keys?",["It throws ConcurrentModificationException","No CME: weakly consistent iteration","Iteration blocks until the writer finishes","It always returns duplicate keys"],1,"Concurrent collections are fail-safe.","M"]]},{"id":"t2-7","no":"2.7","title":"Comparable vs Comparator","imp":"must","quiz":[["Comparable vs Comparator?",["Comparable gives one natural order inside the class; Comparators give others outside","Comparable is used for sorting lists; Comparator is only used by TreeMap and TreeSet","Comparator must be implemented by the class being sorted, Comparable by a helper","Comparable supports several orders by overloading compareTo with different types"],0,"e.g. String implements Comparable; you pass Comparator.comparing(Car::price) for other orders.","E"],["A comparator is <code>(a, b) -> a.price - b.price</code> with int prices. Risk?",["It sorts in descending order","Subtraction is slower than Integer.compare","Equal elements may be reordered, so the sort becomes unstable","Integer overflow can flip the sign and break the ordering"],3,"For large or negative values a − b overflows. Use Integer.compare or Comparator.comparingInt.","M"],["A <code>TreeSet&lt;Car&gt;</code> uses a comparator on price only. Two different cars with the same price are added. Size?",["2, because the cars aren't equal by equals()","2, but contains() finds only one of them","1, because compare == 0 counts as a duplicate","It throws, because the comparator is inconsistent with equals"],2,"Sorted sets use the comparator for equality. Add a unique tie-breaker: thenComparing(Car::id).","H"],["<code>a.compareTo(b)</code> returns a negative number means?",["a comes after b","a comes before b","a equals b","error"],1,"Negative: a < b in this ordering.","E"],["Sort names case-insensitively?",["list.sort(null), which ignores case","list.sort(String.CASE_INSENSITIVE_ORDER)","Collections.reverse(list) after sorting","list.sort(String::compareTo)"],1,"A ready-made Comparator.","E"],["Sort cars by price descending?",["Comparator.comparing(Car::price)","Comparator.comparing(Car::price).reversed()","Comparator.reverseOrder()","list.reverse()"],1,"reversed() flips the comparator.","M"],["Is Java's <code>List.sort</code> (TimSort) stable?",["No: equal elements may be reordered","Yes: equal elements keep their relative order","Only when sorting primitive values","Only for lists below a size threshold"],1,"Lets you sort by secondary then primary key.","M"],["How do you sort nulls last with a comparator?",["It's impossible with the standard API","Comparator.nullsLast(Comparator.naturalOrder())","list.removeNulls() before sorting","Comparator.reverseOrder() puts them last"],1,"Otherwise compareTo on null throws NPE.","M"]]},{"id":"t2-8","no":"2.8","title":"PriorityQueue (binary heap)","imp":"good","quiz":[["You print a <code>PriorityQueue</code> holding 5, 1, 3, 2. Is the output sorted?",["Yes, in ascending order, since it's a min-heap","Yes, in the order the elements were inserted","Not necessarily: only poll() returns elements in order","Yes, in descending order, since the head is the max"],2,"A heap only guarantees parent ≤ children. Iteration and toString follow the array layout.","E"],["Top 10 largest of 10 million numbers with little memory. Best approach?",["A max-heap of all numbers, then poll 10 times","A min-heap capped at 10, evicting the smallest when it exceeds 10","A max-heap capped at 10, evicting the largest when it exceeds 10","Sort the array and take the last 10"],1,"O(n log K) time and O(K) memory. The min-heap's root is the smallest of the current top 10, so it's the one to evict.","M"],["Cost of <code>pq.remove(someObject)</code> where the object isn't the head?",["O(log n), the same as poll()","O(1), because elements know their heap index","O(n log n), because the heap is rebuilt","O(n): a linear search, then an O(log n) sift"],3,"PriorityQueue has no index map. For frequent removals, use a TreeSet or an indexed heap.","H"],["What does <code>peek()</code> on a PriorityQueue return?",["The element that was added last","The head, without removing it","A random element from the heap","A sorted copy of all elements"],1,"poll() removes it.","E"],["How do you make a max-heap of Integers?",["new PriorityQueue&lt;&gt;() with no arguments","new PriorityQueue<>(Comparator.reverseOrder())","new MaxHeap&lt;&gt;() from java.util","new TreeSet&lt;&gt;() used as a heap"],1,"Default is a min-heap.","E"],["Where are a node's children in an array-based binary heap (index i, 0-based)?",["i+1 and i+2","2i+1 and 2i+2","i/2","i*i"],1,"Parent is (i−1)/2.","M"],["Is PriorityQueue thread-safe?",["Yes, all methods are synchronized","No; use PriorityBlockingQueue","Only poll() is thread-safe","Only when it holds Integers"],1,"Concurrent version exists.","M"],["Building a heap from n elements at once (heapify) costs?",["O(n log n)","O(n)","O(log n)","O(n²)"],1,"new PriorityQueue<>(collection) heapifies in O(n).","H"]]},{"id":"t2-9","no":"2.9","title":"Immutable vs fixed-size vs view lists","imp":"good","quiz":[["<code>List&lt;String&gt; l = Arrays.asList(\"a\", \"b\"); l.add(\"c\");</code> What happens?",["UnsupportedOperationException: the list is fixed-size","l becomes [a, b, c]","Compile error: asList returns an immutable type","ArrayIndexOutOfBoundsException from the backing array"],0,"Arrays.asList is a fixed-size view over the array. set() works and writes through; add/remove don't.","E"],["<code>List&lt;String&gt; view = Collections.unmodifiableList(src); src.add(\"x\");</code> Does <code>view</code> contain \"x\"?",["No: unmodifiableList takes a snapshot","src.add throws UnsupportedOperationException","Yes: it's a read-only view of src","Only after view is created again"],2,"unmodifiableList blocks writes through the view, but reflects changes to the source. Use List.copyOf for a snapshot.","M"],["<pre>String[] arr = {\"a\", \"b\"};\nList&lt;String&gt; l = Arrays.asList(arr);\nl.set(0, \"z\");\narr[1] = \"y\";</pre>What are <code>l</code> and <code>arr</code>?",["l = [z, b], arr = [a, y]","l = [z, y], arr = [z, y]","l = [z, b], arr = [z, y]","set throws UnsupportedOperationException"],1,"The list is a view over the same array, so writes go both ways.","H"],["Which creates a truly immutable list?",["Arrays.asList(...)","List.of(...)","new ArrayList<>(...)","Collections.synchronizedList(...)"],1,"No add, set or remove.","E"],["<code>Arrays.asList(1, 2, 3).set(0, 9)</code>?",["Throws UnsupportedOperationException","Works: fixed-size lists allow set","Compile error","Adds 9"],1,"Only size-changing operations are unsupported.","M"],["<code>List.of(1, 2, 3).set(0, 9)</code>?",["It works, setting the first element to 9","Throws UnsupportedOperationException","It returns a new list with 9 at index 0","Compile error: List.of returns a read-only type"],1,"Fully immutable.","E"],["<code>List.copyOf(list)</code> when list is already unmodifiable (from List.of)?",["It always makes a fresh copy","May return the same instance","It throws: the list is already immutable","It returns null for immutable input"],1,"No need to copy an immutable list.","H"],["Which allows null elements?",["List.of","List.copyOf","Arrays.asList","Set.of"],2,"The of/copyOf factories reject nulls.","M"]]},{"id":"t2-10","no":"2.10","title":"Generics, type erasure, PECS","imp":"must","quiz":[["Why can't you write <code>new T()</code> or <code>x instanceof List&lt;String&gt;</code>?",["T might be a primitive type","Generics only work with interfaces","The compiler can't check T without reflection","Type erasure: type arguments don't exist at run time"],3,"The compiler checks types and inserts casts; at run time List&lt;String&gt; is just List.","E"],["A method adds Integers into a list that may be List&lt;Integer&gt;, List&lt;Number&gt; or List&lt;Object&gt;. Parameter type?",["List&lt;? super Integer&gt;","List&lt;? extends Number&gt;","List&lt;Integer&gt;","List&lt;?&gt;"],0,"PECS: Producer Extends, Consumer Super. You write into it, so it's a consumer.","M"],["<pre>List&lt;Integer&gt; ints = new ArrayList&lt;&gt;();\nList raw = ints;\nraw.add(\"x\");\nInteger i = ints.get(0);</pre>Where does it fail?",["At raw.add: ArrayStoreException, like arrays","It doesn't compile at raw.add(\"x\")","At ints.get(0): ClassCastException from an inserted cast","Nowhere: i simply ends up referring to \"x\""],2,"Raw types only warn. The bad element sits in the list (heap pollution) until a cast fails far from the bug.","H"],["What does the diamond <code>new ArrayList&lt;&gt;()</code> do?",["Creates a raw ArrayList without types","Lets the compiler infer the type argument","Makes the new list immutable","Nothing: it's only a style choice"],1,"Inferred from the target type.","E"],["<code>List&lt;?&gt;</code> means?",["A list of Objects; you can add anything","Unknown element type: read only, no adds","A raw list with no type checks at all","A list that can only contain nulls"],1,"Unbounded wildcard.","M"],["Generic method syntax?",["public T &lt;T&gt; first(List&lt;T&gt; l)","public &lt;T&gt; T first(List&lt;T&gt; l)","public T first&lt;T&gt;(List l)","public first(List&lt;T&gt; l)"],1,"Type parameters come before the return type.","M"],["What does <code>&lt;T extends Comparable&lt;T&gt;&gt;</code> mean?",["T must be a subclass of the Comparable class","T must be comparable to itself, so compareTo can be called","T is any type at all; the bound is a hint","T must be a primitive such as int or long"],1,"A bounded type parameter.","M"],["Can you create a <code>List&lt;int&gt;</code>?",["Yes: autoboxing makes primitive type arguments legal","No: needs a reference type, e.g. List&lt;Integer&gt;","Only since Java 21, via value classes","Yes, if the variable is declared with var"],1,"Primitives aren't allowed (until Valhalla).","E"]]},{"id":"t2-11","no":"2.11","title":"Exceptions: try / catch / finally flow","imp":"must","quiz":[["<pre>int f() { int x = 1;\n  try { return x; } finally { x = 2; } }</pre>What does f() return?",["2, because finally runs last and overwrites it","1, because the value is captured before finally","Compile error: finally can't modify x","0, the default value of an int"],1,"The value is saved when the return executes. Changing the local in finally doesn't change it.","M"],["In try-with-resources, the body throws E1 and <code>close()</code> throws E2. What does the caller get?",["E2, since it was thrown last","E1; E2 is silently lost","A wrapper exception holding both","E1, with E2 attached via getSuppressed()"],3,"The primary exception wins; close() failures are suppressed. Resources close in reverse order.","M"],["What happens to an exception thrown in <code>try</code> when <code>finally</code> contains <code>return</code>?",["It's discarded and the method returns normally","It still propagates after finally completes","It's added as a suppressed exception","The JVM wraps it in an Error"],0,"return (or throw) in finally discards the in-flight exception, hiding bugs. Never return from finally.","H"],["Which is a checked exception?",["NullPointerException","IllegalArgumentException","IOException","ArithmeticException"],2,"Checked exceptions must be caught or declared.","E"],["When does a <code>finally</code> block NOT run?",["When an exception is thrown in try","When the try block executes return","When System.exit is called (or the JVM crashes)","When break or continue leaves the try"],2,"Otherwise it always runs.","M"],["Catch order: <code>catch (Exception e)</code> before <code>catch (IOException e)</code>?",["Fine: both catches compile and run","Compile error: the second catch is unreachable","Runtime error when an IOException is thrown","The IOException catch is used first anyway"],1,"Catch more specific types first.","M"],["What does a multi-catch <code>catch (IOException | SQLException e)</code> do?",["Catches both types in one block","It catches only the first listed type","Compile error: catch takes one type","It catches every exception type"],0,"e is effectively final there.","E"],["What must a resource in try-with-resources implement?",["Closeable only","AutoCloseable","Serializable","Runnable"],1,"Closeable extends AutoCloseable.","M"]]},{"id":"t2-12","no":"2.12","title":"Lambdas and method references","imp":"must","quiz":[["<pre>int count = 0;\nlist.forEach(x -> count++);</pre>Why doesn't this compile?",["forEach can't change any state outside the lambda","count would need to be declared volatile","Captured locals must be effectively final (copied in)","Lambdas can capture fields, but never local variables"],2,"Use a stream count(), or an AtomicInteger if you really need a side effect.","E"],["Inside a lambda in an instance method, <code>this</code> refers to?",["The lambda object itself","The enclosing instance","The generated functional-interface class","Nothing: lambdas are static, so this doesn't compile"],1,"Unlike anonymous classes, lambdas don't introduce a new scope for this.","M"],["<pre>String str = null;\nSupplier&lt;Integer&gt; s = str::length;</pre>When does it fail?",["Later, when s.get() is first called","Compile error: str might be null","Never: s.get() simply returns 0","At creation: bound receivers are null-checked"],3,"A bound reference evaluates and null-checks the receiver when the reference is created, unlike the lambda () -> str.length().","H"],["What is a functional interface?",["Any interface","An interface with exactly one abstract method","An interface with only default methods","A class with lambdas"],1,"@FunctionalInterface documents and checks it.","E"],["Which functional interface takes a T and returns a boolean?",["Function","Supplier","Predicate","Consumer"],2,"Predicate&lt;T&gt;.test(T).","E"],["Which takes nothing and returns a value?",["Supplier","Consumer","Runnable","Predicate"],0,"Supplier&lt;T&gt;.get().","E"],["<code>ArrayList::new</code> is which kind of method reference?",["Static","Bound","Unbound","Constructor"],3,"Used as Supplier&lt;List&lt;T&gt;&gt; for example.","M"],["Can a lambda throw a checked exception with <code>Function&lt;T,R&gt;</code>?",["Yes, any lambda can throw checked exceptions","No: apply() declares none, so wrap it","Only IOException is allowed","Only inside stream pipelines"],1,"A common annoyance with streams.","M"]]},{"id":"t2-13","no":"2.13","title":"Streams: a lazy pipeline","imp":"must","quiz":[["<pre>Stream.of(1, 2, 3).peek(System.out::println).map(x -> x * 2);</pre>What's printed?",["Nothing: there's no terminal operation","1 2 3","2 4 6","1 2 3, because peek runs eagerly"],0,"Streams are lazy. Intermediate operations just build the pipeline.","E"],["<code>list.stream().filter(p).map(f).findFirst()</code> on 1 million elements; the 3rd matches. How many elements reach map?",["1,000,000","3","1","All matching elements"],2,"Elements flow one at a time and findFirst short-circuits, so only the first match reaches map.","M"],["<pre>Stream.of(3, 1, 2)\n  .peek(x -> System.out.print(\"p\" + x + \" \"))\n  .sorted().findFirst();</pre>What's printed?",["p3","p3 p1","p1","p3 p1 p2"],3,"sorted() is a stateful barrier: it must consume every element before it can emit the smallest.","H"],["What does <code>map</code> do in a stream?",["It filters elements by a condition","It transforms each element","It sorts the elements","It collects them into a Map"],1,"One in, one out.","E"],["What does <code>flatMap</code> do?",["It maps each element to a boolean","Maps each to a stream, then flattens","It sorts nested lists flat","Nothing: it's an alias for map"],1,"e.g. orders → their line items.","M"],["<code>IntStream.range(0, 5).sum()</code>?",["15","10","5","0"],1,"0 + 1 + 2 + 3 + 4.","E"],["Which is a terminal operation?",["filter","map","collect","peek"],2,"Terminal operations trigger processing.","E"],["<code>Stream.of(1,2,3,4).filter(x -&gt; x % 2 == 0).count()</code>?",["2","4","3","1"],0,"2 and 4.","E"]]},{"id":"t2-14","no":"2.14","title":"Optional, records, sealed, pattern matching","imp":"good","quiz":[["Where do you validate fields of <code>record Money(long cents, String ccy)</code>?",["In a setter, since record components are mutable","In a compact constructor: Money { if (cents &lt; 0) throw … }","In equals(), which runs on every comparison","Nowhere: records can't validate, so use a class"],1,"The compact canonical constructor runs before the fields are assigned.","E"],["<code>opt.orElse(loadDefault())</code> vs <code>opt.orElseGet(this::loadDefault)</code> when opt is present?",["Both skip loadDefault when a value is present","orElseGet calls it too but discards the result","orElse still calls loadDefault; orElseGet doesn't","orElse caches the result, so it's the cheaper one"],2,"The argument to orElse is evaluated before the call. Use orElseGet for expensive defaults.","M"],["What do you get from <code>sealed interface Shape permits Circle, Square</code> plus a pattern-matching switch?",["Faster dispatch, because the JVM uses a jump table for sealed types","Permitted subclasses become implicitly final and immutable","Only classes declared in the same file are allowed to implement it","Exhaustiveness checks: a new permitted type breaks unhandled switches"],3,"Sealed hierarchies plus switch patterns turn \"forgot a case\" into a compile error. Permitted subclasses can live in other files of the same package or module.","H"],["Which Optional method throws if empty?",["orElse","orElseThrow","isPresent","ofNullable"],1,"Prefer orElseThrow with a clear exception.","E"],["<code>Optional.of(null)</code>?",["Returns empty","Throws NullPointerException","Returns Optional[null]","Compile error"],1,"Use ofNullable for maybe-null values.","M"],["What do records generate?",["Private fields, getters, setters, equals/hashCode","Final fields, constructor, accessors, equals/hashCode","Final fields, no-arg constructor, getX() getters","Static fields, a builder, accessors and toString"],1,"Accessors are named like the components: name().","E"],["Can a record extend another class?",["Yes: any non-final class, like a normal class","No: records extend Record; interfaces only","Only abstract classes with a no-arg constructor","Only other records, forming record hierarchies"],1,"Records are final too.","M"],["Pattern matching: <code>if (obj instanceof String s &amp;&amp; s.length() &gt; 3)</code> — is s usable in the second condition?",["No: s is only in scope inside the if body","Yes: s is in scope once the instanceof is true","Only after an explicit cast to String","Only in Java 25 and later"],1,"Flow scoping.","M"]]},{"id":"t3-1","no":"3.1","title":"The four pillars and dynamic dispatch","imp":"must","quiz":[["<code>Vehicle v = new Car(); v.describe();</code> Car overrides describe(). Which runs?",["Car's, chosen at run time from the object's class","Vehicle's, chosen at compile time from the declared type","Car's, chosen at compile time because new Car() is visible","Vehicle's, unless describe() is abstract"],0,"Overridden instance methods are dispatched on the runtime class, typically through a vtable.","E"],["Vehicle.describe() calls <code>this.wheels()</code>, which Car overrides. Calling describe() on a Car uses which wheels()?",["Vehicle's, because the call is written inside Vehicle","Vehicle's, unless wheels() is protected","Car's, because this is a Car","It depends on whether describe() is final"],2,"Self-calls are dispatched dynamically too. That's what makes template methods work, and what makes fragile base classes fragile.","M"],["<pre>class A { String n = \"A\"; String n() { return n; } }\nclass B extends A { String n = \"B\"; String n() { return n; } }\nA a = new B();\nSystem.out.println(a.n + a.n());</pre>",["BB","AB","AA","BA"],1,"Fields aren't polymorphic: a.n uses the declared type A. Methods are, so a.n() runs B's and returns B's field.","H"],["Which pillar lets one variable of type Shape hold a Circle or a Square and call <code>area()</code> on either?",["Encapsulation","Polymorphism","Abstraction only","Composition"],1,"One interface, many behaviours.","E"],["What is abstraction?",["Hiding fields behind private modifiers","Showing what it does, hiding how","Copying objects between layers","Using abstract classes only"],1,"Interfaces are the main tool.","E"],["Which call is resolved by dynamic dispatch?",["A static method called via an instance","A private method called through this","An overridden instance method call","A super.method() call in a subclass"],2,"Static, private and final methods are bound statically.","M"],["What is a vtable?",["A table of the JVM's threads","Per-class table of method entries","A table in the database schema","A GC bookkeeping structure"],1,"Overrides replace their parent's entries.","M"],["Why is \"a setter for every field\" weak encapsulation?",["Setters are slow compared with fields","Callers can set any state, bypassing the rules","Setters can't be overridden later","It isn't weak; it's the right approach"],1,"Prefer meaningful methods like withdraw(amount).","M"]]},{"id":"t3-2","no":"3.2","title":"Overloading vs overriding","imp":"must","quiz":[["<code>Object o = \"hi\"; print(o);</code> with overloads print(Object) and print(String). Which runs?",["print(String), because the object is a String","print(Object), because overloads use static types","Both, in the order they're declared","Ambiguous call, so it's a compile error"],1,"Overloading is resolved at compile time from declared types. Only overriding is dynamic.","E"],["Overloads <code>m(long)</code> and <code>m(Integer)</code>. Which does <code>m(5)</code> call?",["m(Integer), since boxing gives an exact type match","Ambiguous: compile error","Decided at run time from the value","m(long), because widening is tried before boxing"],3,"Overload resolution phases: widening first, then boxing, then varargs.","M"],["An overriding method in a subclass may...",["return a subtype of the parent's return type","reduce visibility from public to protected","declare a broader checked exception","change a parameter from int to long"],0,"Covariant returns are allowed. Narrower access and broader checked exceptions aren't, and different parameters make it an overload.","H"],["Overloading is decided...",["At run time, from the object's class","At compile time, from argument types","By the JIT after profiling","By the class loader"],1,"Overriding is decided at run time.","E"],["Which is NOT a valid overload of <code>void log(String s)</code>?",["void log(String s, int level)","void log(Object o)","int log(String s)","void log(int code)"],2,"Return type alone doesn't distinguish overloads.","M"],["What does <code>@Override</code> do?",["Tells the JVM to dispatch the call dynamically","Asks the compiler to verify it overrides","Forces subclasses to override the method too","Hides the parent method instead of overriding"],1,"Catches typos that would create a new overload.","E"],["Overloads <code>m(int...)</code> and <code>m(int, int)</code>. <code>m(1, 2)</code> calls?",["m(int...)","m(int, int)","Ambiguous","Neither"],1,"Varargs is the last resort.","M"],["Can an override throw a new checked exception the parent method didn't declare?",["Yes","No","Only RuntimeException subclasses (which aren't checked)","Only if final"],1,"It may throw fewer or narrower checked exceptions.","M"]]},{"id":"t3-3","no":"3.3","title":"Initialisation order","imp":"good","quiz":[["<code>new Child()</code> for the first time. Which runs first?",["Child's static block","Parent's constructor","Parent's static block","Child's field initialisers"],2,"Static init: parent then child (once). Then per object: parent fields, parent constructor, child fields, child constructor.","E"],["Parent's constructor calls overridable <code>init()</code>. Child overrides it to print its field <code>String name = \"x\"</code>. What prints?",["x","null: the child's field initialiser hasn't run yet","Compile error: constructors can't call overridable methods","Parent's init() runs instead, because the object isn't a Child yet"],1,"The object is already a Child, so the override runs, but before the child's fields are initialised. Don't call overridable methods from constructors.","M"],["<pre>class C {\n  static { System.out.print(\"S \"); }\n  static final int K = 5;\n}\nSystem.out.println(C.K);</pre>What prints?",["S 5","5 S","S","5"],3,"C.K is a compile-time constant inlined at the call site, so C isn't initialised and its static block never runs.","H"],["How many times does a static initialiser run?",["Once per object created","Once per class (per class loader)","Every time a method is called","Never, unless called explicitly"],1,"On class initialisation.","E"],["What is the first statement of every constructor (explicit or implicit)?",["return","super(...) or this(...)","static","new"],1,"The compiler inserts super() if missing.","E"],["Parent field initialisers run before or after Child's?",["After","Before","At the same time","Only if static"],1,"Parent part is built first.","E"],["The parent has only <code>Parent(String name)</code>. Child has no explicit super call. Result?",["It works: Java adds super() with null","Compile error: no default constructor in Parent","Runtime error when Child is created","It compiles; name is simply null"],1,"Child must call super(name).","M"],["Where do instance initialiser blocks <code>{ … }</code> run?",["Before super(), at the very start","After super(), with field initialisers","After the constructor body finishes","Only once per class"],1,"They're copied into each constructor.","M"]]},{"id":"t3-4","no":"3.4","title":"Inheritance vs composition","imp":"must","quiz":[["What's the composition-based fix for the counting HashSet?",["Mark add() final in CountingSet so it can't be called twice","Call super.addAll inside a synchronized block","Wrap a Set field and forward calls, counting in your own add/addAll","Keep the count in a static field shared by every instance"],2,"A forwarding wrapper doesn't depend on the inner class's self-calls.","E"],["<code>CountingSet extends HashSet</code> overrides add() and addAll() to count. addAll of 3 items reports 6. Why?",["HashSet.addAll calls add() internally, so each item counts twice","addAll also counts the duplicates that HashSet rejects","There's a race between add and addAll on the counter field","super.addAll returns how many were already in the set"],0,"The fragile base class problem: you depend on the parent's self-use, which isn't part of its contract.","M"],["Your subclass of a JDK class works today. Why is that still risky?",["JDK classes are made final in later versions, breaking subclasses","Inheritance stops the JIT from inlining the parent's methods","Subclasses of JDK collection classes can't be serialised","A new version may change which methods call which, breaking overrides"],3,"Self-use is an implementation detail. Composition depends only on the public contract.","H"],["\"has-a\" relationships are modelled with?",["Inheritance","Composition (a field)","Interfaces only","Static methods"],1,"Car has an Engine.","E"],["What is a forwarding (wrapper) class?",["A subclass that adds behaviour","Holds an object and delegates to it","An abstract base class","Only a JDK dynamic proxy"],1,"The basis of decorators.","E"],["Why does composition make testing easier?",["Composed code runs faster","Collaborators can be swapped for fakes","It removes the need for interfaces","Tests no longer need any setup"],1,"You can't swap a superclass in a test.","M"],["When is inheritance still appropriate?",["Whenever it lets you reuse code","For true is-a subtypes, or classes made for it","Always, it's the main OOP tool","Never, composition is always better"],1,"Effective Java: design for inheritance or prohibit it.","M"],["Why make classes <code>final</code> by default in some codebases?",["It makes method calls faster","Stops fragile subclassing","Spring requires final classes","It saves memory per object"],1,"Note: Spring proxies need non-final classes for CGLIB.","H"]]},{"id":"t3-5","no":"3.5","title":"Abstract class vs interface, default-method conflicts","imp":"must","quiz":[["When is an abstract class a better fit than an interface?",["When the type needs multiple parents","When subclasses share instance state and a skeleton with protected helpers","When you need static methods, since interfaces can't have them","When you want to implement it with a lambda"],1,"Interfaces can't hold instance state. (They can have static and private methods since Java 8/9.)","E"],["Class C implements interfaces A and B, and both declare <code>default void hello()</code>. What must C do?",["Nothing: the first interface listed wins","Nothing: A wins because it was compiled first","C must be declared abstract","Override hello(); it may call A.super.hello()"],3,"Two unrelated defaults conflict and must be resolved explicitly.","M"],["<code>interface I { default void m(){} }</code>, <code>interface J extends I { default void m(){} }</code>, <code>class C implements I, J</code>. Which m() does C get?",["J's: the more specific interface wins","I's: it's listed first","Compile error: C must override m()","AbstractMethodError at run time"],0,"Rules: classes win; then the most specific interface wins; otherwise you must override.","H"],["Can an interface have instance fields?",["Yes, like any class","No: only public static final constants","Only private instance fields","Only from Java 21"],1,"State belongs in classes.","E"],["How many abstract classes can a class extend?",["One","Two","Any number","None"],0,"But it can implement many interfaces.","E"],["Can interfaces have static methods?",["No","Yes, since Java 8","Only private","Only in records"],1,"e.g. List.of, Comparator.comparing.","E"],["Can an abstract class have a constructor?",["No, they can't be instantiated","Yes: subclasses call it via super(...)","Only private constructors","Only static constructors"],1,"It initialises shared state.","M"],["Private methods in interfaces (Java 9+) are for?",["Nothing: they can't be called","Sharing code between default methods","Making default methods final","Making the interface thread-safe"],1,"Not visible to implementers.","M"]]},{"id":"t3-6","no":"3.6","title":"SOLID, with failing and fixed examples","imp":"must","quiz":[["Each new fee type means editing a big <code>switch</code> in FeeCalculator. Which principle, and what fix?",["Single responsibility: split FeeCalculator into two classes","Liskov: add a FeeCalculator subclass per fee","Open/Closed: add a FeeRule implementation and inject all rules","Interface segregation: one interface per case"],2,"New behaviour should be a new class, not an edit to existing code.","E"],["<code>Square extends Rectangle</code>. A test does setWidth(5), setHeight(4) and expects area 20 but gets 16. Which principle is broken?",["Liskov substitution","Single responsibility","Dependency inversion","Open/Closed"],0,"A subtype must keep the base type's contract. Square silently changes both sides.","M"],["<code>Printer</code> has print, scan and fax. <code>SimplePrinter.fax()</code> throws UnsupportedOperationException. What's violated?",["Only single responsibility","Only open/closed","Nothing: throwing UnsupportedOperationException is the standard approach","Interface segregation, and Liskov (callers of Printer can't rely on fax)"],3,"Split into small role interfaces (Printer, Scanner, Fax) so no class implements methods it can't support.","H"],["What does \"S\" in SOLID stand for?",["Static","Single responsibility","Substitution","Segregation"],1,"One reason to change.","E"],["Which principle says depend on abstractions, not concretions?",["Open/closed","Liskov","Dependency inversion","Interface segregation"],2,"Inject interfaces.","E"],["A <code>UserService</code> validates input, saves to the DB, sends emails and builds PDFs. Which principle is strained?",["Liskov","Single responsibility","Interface segregation","None"],1,"Four different reasons to change.","E"],["Strategy and plugin designs mostly help which principle?",["Open/closed","Single responsibility","Liskov","None"],0,"Add behaviour by adding classes.","M"],["A subclass override returns null where the parent promised a non-empty list. Which principle breaks?",["Interface segregation","Liskov substitution","Dependency inversion","Open/closed"],1,"It weakens the postcondition.","M"]]},{"id":"t3-7a","no":"3.7a","title":"Singleton (and how to break it)","imp":"must","quiz":[["Which singleton implementation resists reflection and serialization by default?",["Double-checked locking","An eager static final field","An enum with a single INSTANCE","The holder idiom"],2,"Enums can't be instantiated reflectively and serialise by name.","E"],["Why is the holder idiom (<code>private static class Holder { static final X I = new X(); }</code>) lazy and thread-safe?",["The JVM initialises Holder once, under a lock, on first use","The INSTANCE field is implicitly volatile inside Holder","All static fields are created when the JVM starts up","It isn't, unless getInstance() is also synchronized"],0,"Class initialisation is lazy and guarded by the JVM.","M"],["Which breaks a holder-idiom singleton but not an enum singleton?",["Two threads calling getInstance() at the same moment","Calling getInstance() from another class's static block","Class unloading during a GC","Reflection calling the private constructor with setAccessible(true)"],3,"Reflection (and serialization without readResolve) can create a second instance. Enums are protected against both.","H"],["How do you stop other code from creating a second instance of a singleton class?",["Make the class abstract","Make the constructor private","Make fields static","Use final fields"],1,"And expose one instance.","E"],["Eager singleton <code>static final X INSTANCE = new X();</code> is created when?",["When the JVM starts","When the class is first initialised","Never, until getInstance() runs twice","On each call to INSTANCE"],1,"Class init is lazy in Java.","M"],["Why is double-checked locking easy to get wrong?",["The outer check is slow under contention","Without volatile, a half-built object leaks","The inner synchronized block can deadlock","Static fields can't be read outside the lock"],1,"See 4.6.","M"],["Why are singletons often criticised?",["They're slow because every call is synchronized","Hidden global state, hard to replace in tests","They can't implement interfaces or be mocked","They force all their methods to be static"],1,"DI singletons avoid most problems.","E"],["How many instances does a Spring singleton bean have?",["One per thread using it","One per application context","One per JVM, globally","One per injection point"],1,"Two contexts would create two.","M"]]},{"id":"t3-7b","no":"3.7b","title":"Factory (and a Spring map registry)","imp":"must","quiz":[["Main benefit of a factory to client code?",["Objects are created faster than with new","Clients depend only on the interface type","It removes the need for interfaces","It guarantees one instance per type"],1,"The client can't accidentally depend on the concrete class.","E"],["What does an Abstract Factory produce?",["One complex object, built up step by step","A cached instance for each key you ask for","Families of related objects that must match, e.g. one theme","Instances of abstract classes, via generated subclasses"],2,"Swapping the factory swaps the whole family consistently.","M"],["Spring injects <code>Map&lt;String, PaymentProcessor&gt;</code>. What are the keys?",["Bean names, e.g. \"stripeProcessor\"","Fully qualified class names","The order beans were created in","Whatever each bean's getKey() returns"],0,"Spring builds the map from bean names. Name your beans deliberately when using a map registry.","H"],["What does a factory method return?",["Always a new instance of one concrete class","An object typed as an interface or base class","A Class object for the caller to instantiate","A Supplier that builds the object lazily"],1,"Callers don't see the concrete type.","E"],["<code>List.of(...)</code> is an example of?",["Builder","Static factory method","Adapter","Observer"],1,"It can return different hidden implementations.","E"],["What smell suggests replacing a switch-factory with a registry?",["The switch has just two or three cases","Every new type means editing the switch","Its return type is an interface","The factory method is declared static"],1,"Open/closed.","M"],["Abstract Factory vs Factory Method?",["Same pattern; Abstract Factory is just declared abstract","Abstract Factory makes related families; Factory Method one product","Factory Method makes related families; Abstract Factory one product","Abstract Factory is a Builder that hides construction steps"],1,"e.g. a UI kit per platform.","M"],["In Spring, a FactoryBean is used to?",["Build complex objects; getObject() returns the actual bean","Replace @Bean methods in Java configuration classes","Inject all beans of one type as a List","Decide which profile's beans get registered"],0,"e.g. older SessionFactory setups.","H"]]},{"id":"t3-7c","no":"3.7c","title":"Builder","imp":"must","quiz":[["<code>new Car(String, String, int, int, boolean, boolean, String)</code> keeps causing swapped-argument bugs. Best fix?",["More overloaded constructors with fewer parameters each","A no-arg constructor plus a JavaBean setter for each field","A static factory method taking the same 7 parameters","A Builder with named fluent methods and checks in build()"],3,"Builder fixes telescoping constructors and avoids half-built objects that setters allow.","E"],["Where should a Builder check invariants such as \"end date after start date\"?",["In each fluent setter only","In build(), once, with all values known","In the built object's getters","In the target class's no-arg constructor"],1,"Cross-field rules need all values together, which only build() has.","M"],["Why can a Builder produce an immutable object when JavaBeans can't?",["The builder deep-copies every field it's given, so nothing can leak out","Builder methods are synchronized, so the object can't change mid-build","It's built once in build() with every field set, so fields can be final","Discarding the builder afterwards freezes the object's fields in place"],2,"JavaBeans need setters (and a moment where the object is half-built); a builder hands everything to one constructor.","H"],["What problem does Builder mainly solve?",["Sharing one instance safely across threads","Long constructors with many optional parameters","Choosing which subclass to create at run time","Slow startup caused by eager object creation"],1,"Telescoping constructors.","E"],["Where is the final object created in a builder?",["In each setter","In build()","In the builder's constructor","In toString"],1,"After validation.","E"],["Why are JavaBeans (setters) worse for required fields?",["Setter calls are slower than one constructor call","The object exists in a half-built state between setter calls","Objects with setters can't be serialised by Jackson","Setters make the object immutable once it's built"],1,"And can't be immutable.","M"],["Lombok's <code>@Builder(toBuilder = true)</code> gives?",["A builder from an existing instance, to make a modified copy","A builder that checks required fields at compile time","A shared static builder reused across all instances","A builder whose build() caches the created object"],0,"Handy for immutable objects.","M"],["A builder method should return?",["void","this","a new object of the target class","null"],1,"For chaining.","E"]]},{"id":"t3-7d","no":"3.7d","title":"Strategy","imp":"must","quiz":[["Pricing must switch between \"regular\", \"festival\" and \"surge\" at run time. Which pattern?",["Strategy: a PricingStrategy interface, passed in","Template method: subclasses override a pricing step","State: the price object swaps its own behaviour","Decorator: prices are wrapped in discount layers"],0,"The context delegates to whichever strategy it holds; the caller picks it.","E"],["Strategy vs State, in one line?",["Strategy: the object switches itself; State: the caller picks","State needs an enum, while Strategy needs an interface","They're the same pattern, just with different names","Strategy: the caller picks; State: the object switches itself"],3,"Same structure, different intent.","M"],["Strategies are singleton Spring beans looked up from a map, and one keeps a mutable field <code>lastPrice</code>. Risk?",["Map lookups from many threads aren't thread-safe","None: each request gets its own strategy instance","Strategies are shared singletons, so lastPrice races","Strategies are garbage-collected between requests"],2,"Singleton beans must be stateless. Keep per-request data in parameters or locals.","H"],["Strategy replaces which code smell?",["Long parameter lists in constructors","if/else or switch choosing between algorithms","Duplicated getters and setters across classes","Static mutable state shared across threads"],1,"Each branch becomes a class.","E"],["Is a Comparator passed to sort a strategy?",["Yes","No","Only if anonymous","Only for Strings"],0,"The sorting algorithm delegates comparison.","E"],["Who usually chooses the strategy?",["The strategy itself","The caller or configuration","The JVM","The garbage collector"],1,"In State, the object switches itself.","M"],["How can Spring pick a strategy per request?",["Use @Primary to switch the bean on each request","Inject Map&lt;String, Strategy&gt; and look up by key","Store the chosen strategy in a static field","Use @Qualifier, which is resolved per request"],1,"Bean names are the keys.","M"],["What's the risk of strategies with mutable fields as singletons?",["Each thread gets a copy, wasting memory","Shared by all threads → race conditions","Spring refuses to create mutable singletons","Fields reset to defaults after each call"],1,"Keep strategies stateless.","M"]]},{"id":"t3-7e","no":"3.7e","title":"State (auction lifecycle)","imp":"good","quiz":[["An auction in CLOSED receives <code>placeBid()</code>. With the State pattern, what happens?",["ClosedState.placeBid() rejects it","The context checks the status with if/else first","It's silently ignored","It's queued until the auction reopens"],0,"Each state class implements every event; illegal ones are rejected in that state.","E"],["Biggest benefit of State over a switch on a status field?",["There are fewer classes than with the switch","It runs faster than a switch statement","Each state's current value is saved to the database for you","Each state's rules live in one class you can test on its own"],3,"Behaviour is localised per state.","M"],["Two pods try to move one auction from LIVE to CLOSED. How do you make it safe in the DB?",["SELECT the status, then UPDATE if it's LIVE, inside @Transactional","UPDATE … SET status='CLOSED' WHERE id=? AND status='LIVE'; check rows","A synchronized block on the auction's id string","Retry the UPDATE in a loop until it succeeds"],1,"A conditional update is a compare-and-set in SQL; only one pod sees 1 row. SELECT-then-UPDATE races under READ COMMITTED, and synchronized only covers one JVM.","H"],["In the State pattern, what changes when an event occurs?",["The context's class, via a new subclass instance","The current state object the context delegates to","The methods exposed on the context's interface","The strategy bean injected by the Spring container"],1,"The context swaps its state.","E"],["An illegal event in a state should?",["Be ignored so the state stays unchanged","Be rejected clearly (exception / error result)","Reset the machine to its initial state","Be queued until a valid state is reached"],1,"Fail loudly.","E"],["Which Java feature fits a small state machine well?",["A HashMap of strings mapping to boolean flags","An enum with allowed transitions and an exhaustive switch","A class hierarchy using reflection to pick states","A dedicated thread per state with a shared queue"],1,"See 7.1.","M"],["How do you prevent two servers from both moving an order from PAID to SHIPPED twice?",["Mark the transition method synchronized","UPDATE … WHERE status = 'PAID' and check rows affected","Keep a static in-memory set of shipped orders","Read the status first, then UPDATE if PAID"],1,"Compare-and-set in SQL.","M"],["Strategy vs State?",["Same structure; caller picks a strategy, an object changes its own state","Unrelated patterns with different class structures","State is a Strategy using only enums, no classes","Strategies swap themselves; callers pick the state"],0,"Intent differs.","M"]]},{"id":"t3-7f","no":"3.7f","title":"Observer (events)","imp":"good","quiz":[["Send a confirmation email only if the order transaction commits. In Spring?",["@EventListener","@Async on its own","@TransactionalEventListener(AFTER_COMMIT)","@PostConstruct on the mail service"],2,"AFTER_COMMIT fires only once the change is durable, so a rollback won't send a misleading email.","E"],["A synchronous listener throws while handling OrderPlaced. What happens?",["Spring isolates listeners, so the others still run","The exception reaches the publisher; later listeners may not run","The event is put back on the queue and retried","The exception is logged and swallowed"],1,"Synchronous notification couples the publisher to every listener's failures and latency.","M"],["An event is published outside any transaction, and its listener is <code>@TransactionalEventListener(AFTER_COMMIT)</code>. What happens?",["The listener runs immediately instead","It throws IllegalStateException","It runs at the next commit on that thread","It's skipped unless fallbackExecution = true"],3,"With no transaction to bind to, the event is dropped for that listener by default.","H"],["Observer decouples...",["threads from the locks they acquire","the publisher from the code reacting to its events","interfaces from the classes implementing them","the database from the cache in front of it"],1,"Add reactions without editing the publisher.","E"],["Spring annotation to handle an application event?",["@Bean","@EventListener","@Async","@Service"],1,"publisher.publishEvent(event) triggers it.","E"],["By default, Spring event listeners run?",["Asynchronously, on a new thread each","Synchronously, in the publisher's thread","On Spring's task scheduler thread pool","After the publisher's transaction commits"],1,"Add @Async for asynchronous handling.","M"],["Why use AFTER_COMMIT for \"send email\" listeners?",["So the email is sent on a separate async thread","So the email only goes out once the data is really saved","So a failed email rolls back the saved data","So the listener joins the publisher's transaction"],1,"Rollbacks would otherwise send wrong emails.","M"],["What's the risk of many slow synchronous listeners?",["Listeners start running on parallel threads","The publisher's request gets slower with each one","Each listener keeps its event object in memory","Listeners always deadlock with the publisher"],1,"Make heavy ones async or move to a queue.","M"]]},{"id":"t3-7g","no":"3.7g","title":"Decorator (wrapping)","imp":"good","quiz":[["<code>new BufferedReader(reader)</code> adds buffering behind the same Reader type. Which pattern?",["Decorator","Proxy","Adapter","Composite"],0,"Same interface, wraps an inner object, adds one behaviour, delegates.","E"],["<code>Logged(Retrying(client))</code> vs <code>Retrying(Logged(client))</code>?",["No difference: decorators always commute","The first one ends up retrying the logging","The first logs once per call; the second logs each attempt","The second doesn't compile"],2,"Calls flow inward through the layers, so order changes behaviour.","M"],["Decorator vs Proxy?",["Proxy changes the interface; a decorator keeps it the same","Decorators can be stacked several deep; proxies can't","Proxies must always be generated at run time","Same shape; decorator adds behaviour, proxy controls access"],3,"The difference is intent (lazy, cache, security, remote vs extra behaviour).","H"],["A decorator implements...",["A different interface from the wrapped object","The same interface as the object it wraps","No interface","Only abstract classes"],1,"That's why decorators stack.","E"],["Which JDK API is built from decorators?",["java.time (LocalDate, ZonedDateTime, Instant…)","java.io streams (BufferedInputStream, GZIPInputStream…)","java.util.Random (SecureRandom, ThreadLocalRandom…)","java.lang.Math (StrictMath, Math.abs, Math.max…)"],1,"Each adds one capability.","E"],["Adding caching, logging and retry to a client with decorators instead of subclassing gives?",["One subclass for each feature combination","Independent layers you can combine and reorder","Faster calls, since no extra layers exist","A single class holding all three concerns"],1,"Avoids class explosion.","M"],["<code>Collections.synchronizedList(list)</code> is a decorator adding?",["Sorting on every insertion","A lock around each method call","Immutability, rejecting writes","A cached copy for fast reads"],1,"Same List interface.","M"],["Does the order of decorators matter?",["No: decorators are applied in any order","Yes: calls pass through outer layers first","Only for java.io streams, not other APIs","Only when decorators share mutable state"],1,"e.g. cache outside retry vs inside.","E"]]},{"id":"t3-7h","no":"3.7h","title":"Proxy (and JDK dynamic proxies)","imp":"must","quiz":[["A JDK dynamic proxy can proxy...",["Any class with a public constructor","Only interfaces; Spring uses CGLIB for classes","Only final classes","Only classes with a no-arg constructor"],1,"java.lang.reflect.Proxy implements interfaces at run time and routes every call to one InvocationHandler.","E"],["<code>@Transactional save()</code> is called as <code>this.save()</code> from another method of the same bean. What happens?",["Ignored: the call bypasses the proxy","A transaction starts as usual","A nested transaction starts","Spring fails at startup"],0,"Spring AOP wraps the bean in a proxy; internal calls go straight to the target.","M"],["Why can't Spring's CGLIB proxy intercept a <code>final</code> or <code>private</code> method?",["Spring deliberately skips final methods for performance","javac inlines final methods, so the proxy never sees the call","It can: @Transactional works fine on final methods","The proxy is a subclass, which can't override those methods"],3,"CGLIB proxies work by overriding. Final/private calls go straight to the target code.","H"],["A proxy has...",["A different interface from the real object","The same interface as the real object","No methods","Only static methods"],1,"Callers can't tell the difference.","E"],["A virtual (lazy) proxy is used to?",["Encrypt data before passing it to the real object","Delay creating an expensive object until it's needed","Log every call made to the real object","Cache results of the real object's method calls"],1,"Hibernate's lazy-loaded entities are proxies.","M"],["What does a JDK dynamic proxy route every call to?",["A generated subclass of the target class","An InvocationHandler.invoke method","A MethodInterceptor.intercept method","The target's method via a MethodHandle"],1,"One handler for all methods.","M"],["Why does Hibernate return proxies for lazy associations?",["To make entities safe to share across threads","To load the real data only when a method is first called","To make entities serializable for remote calls","To avoid generating SQL for the entity's class"],1,"Outside a session that load fails (LazyInitializationException).","M"],["Spring <code>@Transactional</code> is implemented by?",["Bytecode javac injects around the annotated method","A proxy that starts/commits a transaction around the call","A servlet filter that wraps every HTTP request","A database trigger on the method's tables"],1,"Hence the self-invocation trap.","E"]]},{"id":"t3-7i","no":"3.7i","title":"Adapter","imp":"good","quiz":[["Your domain uses <code>PaymentGateway.charge(Money)</code>; the vendor SDK offers <code>pay(int cents, String ccy)</code>. Which pattern?",["Facade","Decorator","Adapter","Bridge"],2,"An adapter implements your interface, wraps the SDK and translates calls, results and errors.","E"],["Why translate vendor exceptions inside the adapter?",["To keep vendor types out of the domain code","Because vendor exceptions are always checked","To avoid logging the same error twice","Because translating exceptions is faster"],0,"The domain should only see your own error types.","M"],["Adapter vs Facade?",["Facade converts one interface; Adapter simplifies a subsystem","They're the same pattern under two names","Adapter is only used when wrapping legacy code","Adapter converts one interface; Facade simplifies a subsystem"],3,"Different intent and scope.","H"],["What does an adapter change?",["The behaviour, adding features on top","The interface, so incompatible code fits","The access, controlling who may call it","The performance, by caching each call"],1,"Translate calls between two interfaces.","E"],["<code>InputStreamReader</code> adapts?",["a character Reader to a byte InputStream","a byte InputStream to a character Reader","a File path to a buffered InputStream","a String to a stream of characters"],1,"Using a charset.","M"],["Where should vendor SDK types appear in your code?",["Everywhere","Only inside the adapter","In controllers","In entities"],1,"Keep them at the boundary.","E"],["Switching payment provider with adapters means?",["Rewriting each service that calls the provider","Writing a new adapter for the same interface","Changing the domain model to match the provider","Subclassing the old provider's client library"],1,"Domain code stays unchanged.","M"],["Facade vs Adapter in one sentence?",["Same thing; both wrap one class to rename its methods","Facade simplifies a subsystem; Adapter converts one interface to another","Facade converts interfaces; Adapter simplifies a subsystem","Facade adds behaviour; Adapter controls access to an object"],1,"Different intents.","M"]]},{"id":"t3-7j","no":"3.7j","title":"Template method","imp":"good","quiz":[["In Template Method, what is a \"hook\"?",["An abstract step every subclass must implement","A step with a default body subclasses may override","A static callback registered once at startup","A JVM shutdown hook that runs the template"],1,"Required steps are abstract; optional ones are hooks.","E"],["Why is the template (skeleton) method usually <code>final</code>?",["So subclasses can't change the order of steps","Because final methods run faster","Because abstract methods require it","So it can be called from a constructor"],0,"Subclasses fill in steps; the base class controls the flow.","M"],["<code>JdbcTemplate.query(sql, rowMapper)</code> combines template method with?",["Builder","Observer","Singleton","Callback (Strategy)"],3,"The template owns connection, statement, errors and cleanup; you supply only the varying part.","H"],["Template method puts the fixed algorithm in?",["Each subclass, which overrides the whole method","A base-class method that calls overridable steps","An interface whose methods each subclass implements","A static utility method taking a lambda per step"],1,"Subclasses fill in steps.","E"],["What's a typical modifier for the template method itself?",["abstract","final","static","private"],1,"So subclasses can't reorder steps.","E"],["Which Spring class follows template + callback?",["RestTemplate / JdbcTemplate","ApplicationContext / BeanFactory","Environment / PropertySource","ApplicationEventPublisher / Environment"],0,"They handle boilerplate; you pass the varying part.","M"],["JUnit's @BeforeEach / @AfterEach around tests is like?",["Observer: JUnit notifies hooks when tests change","Template method: fixed lifecycle, your test is the varying step","Singleton: one shared fixture for the whole class","Builder: each hook adds a step that builds the test"],1,"The framework controls the flow.","M"],["A required step should be declared as?",["A hook with a default","An abstract method","A static method","A private method"],1,"Optional steps are hooks.","E"]]},{"id":"t4-1","no":"4.1","title":"Process vs thread","imp":"must","quiz":[["Two threads in one process. What do they share?",["Their stacks","Their program counters","The heap: objects and static fields","Nothing, unless they use shared memory"],2,"Each thread has its own stack and PC; heap objects and statics are shared, hence the need for coordination.","E"],["A local <code>int</code> in a method called by many threads. Thread-safe?",["Yes: each call has its own copy in its own stack frame","No: it needs volatile","Only if it's declared final","No: the JIT may keep it in a shared register"],0,"Locals are thread-confined. Objects they point to may still be shared.","M"],["A method creates <code>new ArrayList&lt;&gt;()</code> in a local, submits a task that adds to it, and keeps adding itself. Thread-safe?",["Yes: the variable is a local","Yes: submit() publishes all later writes too","No: locals can't be passed to other threads","No: the list object itself is now shared"],3,"Confinement is about the object, not the variable. submit() only publishes writes made before the call.","H"],["What does each thread have its own copy of?",["Its heap and loaded classes","Its stack and program counter","Its static fields and constants","Its String pool and metaspace"],1,"The heap is shared.","E"],["Why are threads cheaper to switch between than processes?",["They share an address space, so no memory map switch is needed","They skip saving registers because they share one stack","The JVM switches them itself without involving the OS kernel","Each thread is pinned to its own core, so caches never go cold"],0,"Processes are isolated.","M"],["Two threads read and write the same object field without coordination. Risk?",["A guaranteed deadlock at runtime","Races and visibility problems","Only slower performance, not bugs","A ConcurrentModificationException"],1,"Shared mutable state needs coordination.","E"],["What is a context switch?",["The JVM moving a thread's objects to another heap region","The OS pausing one thread and resuming another on a CPU","A method call switching from one stack frame to another","The compiler changing which variables are in scope"],1,"It has a cost (saving registers, cache effects).","E"],["A JVM process with 10 threads crashes from an uncaught Error in one thread. What happens to the others?",["The JVM terminates every thread immediately","Only that thread ends; the rest keep running","All other threads pause until it's handled","The JVM restarts the failed thread automatically"],1,"Uncaught exceptions end only the thread (unless it's fatal to the JVM).","M"]]},{"id":"t4-2","no":"4.2","title":"Creating threads","imp":"must","quiz":[["<code>Thread t = new Thread(task); t.run();</code> Where does the task run?",["On a new thread","On the calling thread","Always on the main thread","On a pool thread"],1,"start() creates a new thread that then calls run().","E"],["Calling <code>start()</code> twice on the same Thread?",["Runs the task twice","The second call is ignored","IllegalThreadStateException","Restarts it from the beginning"],2,"A Thread can be started only once.","M"],["main() starts a non-daemon thread <code>t</code> and returns immediately. Does the JVM exit?",["No: it waits until all non-daemon threads finish","Yes: main returning stops every other thread","Yes, unless main called t.join() first","Only once System.exit() is called"],0,"The JVM exits when only daemon threads remain (or on System.exit).","H"],["Which interface returns a result from a task?",["Runnable","Callable","Thread","Executor"],1,"call() returns V.","E"],["What does <code>future.get()</code> do?",["Returns null immediately if the task isn't done","Blocks until the result (or exception) is ready","Starts the task and returns its result directly","Cancels the task if it hasn't finished yet"],1,"Use get(timeout, unit) to bound the wait.","E"],["What does <code>thread.join()</code> do?",["Starts that thread right away","Waits for that thread to finish","Merges it into the current thread","Waits for that thread to start"],1,"join(ms) waits at most ms.","E"],["What is a daemon thread?",["A high-priority thread the scheduler runs first","A background thread that doesn't keep the JVM alive","A thread that keeps running after the JVM exits","A system thread reserved only for the GC"],1,"setDaemon(true) before start().","M"],["An exception thrown inside a Callable submitted to an executor appears where?",["Thrown directly to the thread that called submit()","Wrapped in ExecutionException when you call future.get()","Passed to the pool's handler, killing the worker","Swallowed entirely, so future.get() returns null"],1,"getCause() gives the original.","M"]]},{"id":"t4-3","no":"4.3","title":"Thread lifecycle","imp":"must","quiz":[["A thread is trying to enter a <code>synchronized</code> block another thread holds. Its state?",["WAITING","TIMED_WAITING","RUNNABLE","BLOCKED"],3,"BLOCKED means waiting for a monitor lock.","E"],["<code>wait()</code> vs <code>sleep(ms)</code> with respect to locks?",["Both release the lock while they wait","Neither releases the lock while waiting","wait() releases the monitor; sleep() keeps it","sleep() releases the lock; wait() keeps it"],2,"That's why sleeping inside synchronized blocks other threads.","M"],["After <code>notify()</code>, while the notifier still holds the lock, the woken thread's state is?",["RUNNABLE, ready to continue","BLOCKED: it must re-acquire the monitor","Still WAITING until the notifier exits","TIMED_WAITING"],1,"notify doesn't hand over the lock; the woken thread competes for it.","H"],["A thread calls <code>Thread.sleep(1000)</code>. Its state?",["BLOCKED","WAITING","TIMED_WAITING","TERMINATED"],2,"Waiting with a timeout.","E"],["A thread calls <code>otherThread.join()</code> (no timeout). Its state?",["RUNNABLE","WAITING","BLOCKED","NEW"],1,"Waits indefinitely for the other to end.","E"],["Can a TERMINATED thread be restarted?",["Yes, call start()","No: create a new Thread","Yes, with run()","Only daemons"],1,"start() on it throws IllegalThreadStateException.","M"],["What state is a thread in right after <code>new Thread(r)</code>?",["RUNNABLE","NEW","WAITING","READY"],1,"Until start() is called.","E"],["What does <code>Thread.interrupt()</code> do to a thread that is just computing (not waiting)?",["Throws InterruptedException in it right away","Sets its interrupt flag; the code must check it","Stops it at the next safepoint automatically","Does nothing unless it's a daemon thread"],1,"Interruption is cooperative.","M"]]},{"id":"t4-4","no":"4.4","title":"The race condition","imp":"must","quiz":[["Two threads each run <code>count++</code> 100,000 times on a shared int. Typical result?",["Often less than 200,000: increments are lost","Always 200,000, since int writes are atomic","Exactly 100,000","Always 200,000 on a multi-core CPU"],0,"count++ is read, add, write. Interleavings lose updates.","E"],["<pre>if (!map.containsKey(k)) map.put(k, v);</pre>on a ConcurrentHashMap from many threads. Safe?",["Yes: ConcurrentHashMap makes it thread-safe","Yes, as long as the key is immutable","Only if the map field is declared volatile","No: the pair isn't atomic; use putIfAbsent"],3,"Check-then-act needs the check and the action to be one atomic operation.","M"],["Which does NOT fix a lost-update race on a counter?",["AtomicInteger.incrementAndGet()","Making the field volatile","synchronized around the increment","LongAdder.increment()"],1,"volatile gives visibility, not atomicity of read-modify-write.","H"],["What is a race condition?",["Two threads waiting on each other's locks","A result that depends on the timing of threads","A loop that spins until another thread ends","Threads competing to start first in a pool"],1,"Correctness depends on interleaving.","E"],["Which pattern is a check-then-act race?",["count++ on a shared int field from many threads","if (!map.containsKey(k)) map.put(k, v) from many threads","map.computeIfAbsent(k, f) on a ConcurrentHashMap","Reading a final field set in the constructor from many threads"],1,"Two threads can both see \"absent\".","E"],["Simplest way to avoid races on shared data?",["Mark every shared field volatile to make it safe","Don't share mutable state: immutability or confinement","Add Thread.sleep() calls to space out accesses","Run more threads so each touches less data"],1,"No sharing, no race.","M"],["Lazy initialisation <code>if (instance == null) instance = new X();</code> from many threads. Problem?",["Threads deadlock on the null check forever","Several instances may be created (and published unsafely)","None: reference assignment is atomic, so it's safe","The JIT removes the null check, so X is never built"],1,"Use a holder class or proper locking.","M"],["Why do race bugs often pass tests?",["Tests are single-threaded or the bad interleaving is rare","Races only show up in optimized production builds","JUnit runs tests under a global lock that hides races","The JVM serializes threads when assertions are on"],0,"Stress tests and reasoning are needed.","M"]]},{"id":"t4-5","no":"4.5","title":"synchronized: the monitor lock","imp":"must","quiz":[["A synchronized method calls another synchronized method on the same object. What happens?",["It deadlocks on itself","IllegalMonitorStateException","The hold count goes up (re-entrant)","The second method runs unsynchronized"],2,"The owning thread can re-enter the monitor it already holds.","E"],["Besides mutual exclusion, what does synchronized guarantee?",["Visibility: earlier writes are seen by the next locker","Fairness: threads get the lock in arrival order","Timeouts: blocked threads eventually give up","Nothing beyond mutual exclusion"],0,"Unlock → lock on the same monitor is a happens-before edge.","M"],["<code>static synchronized void reset()</code> and <code>synchronized void inc()</code> both modify a static field. Mutually exclusive?",["Yes: both lock the class's monitor","Yes, if the field is volatile","Yes: static synchronized locks every instance too","No: one locks Counter.class, the other locks this"],3,"Different monitors mean no mutual exclusion.","H"],["A synchronized block <code>synchronized (lock) { … }</code> locks?",["The current method for all callers","The monitor of the lock object","The Class object of the lock's type","Every field of the enclosing object"],1,"Pick a private final lock object.","E"],["Thread A holds a monitor. Thread B tries to enter a block on the same monitor. B's state?",["WAITING","BLOCKED","RUNNABLE","TERMINATED"],1,"Waiting for the monitor.","E"],["Is synchronized fair (first come, first served)?",["Yes: waiters are queued and served in order","No: any waiting thread may get the lock next","Yes, but only for static synchronized methods","Only when the JVM is started in fair-lock mode"],1,"ReentrantLock(true) offers fairness.","M"],["An exception is thrown inside a synchronized block. Is the lock released?",["No, deadlock","Yes, automatically","Only with finally","Only for RuntimeException"],1,"Monitors are released on any exit.","M"],["Why keep synchronized blocks small?",["The JIT can't optimize code inside large synchronized blocks","Other threads wait while you hold the lock; long sections kill throughput","Locked objects can't be GC'd, so big blocks hold more memory","Long blocks trip the JVM's deadlock detector and get aborted"],1,"Never do I/O while holding a lock.","E"]]},{"id":"t4-6","no":"4.6","title":"volatile and the Java Memory Model","imp":"must","quiz":[["Is <code>volatile int count; count++;</code> safe with many writers?",["Yes, volatile makes ++ atomic","No: it gives visibility, not atomicity","Yes, on 64-bit JVMs","Only for long and double fields"],1,"Use AtomicInteger or a lock.","E"],["<pre>boolean running = true;   // not volatile\n// T1: while (running) { }\n// T2: running = false;</pre>What can happen?",["T1 stops within one time slice","T1 throws IllegalMonitorStateException","T1 may loop forever: nothing forces it to see T2's write","The compiler rejects the unsynchronized access"],2,"Without happens-before, the JIT can hoist the read out of the loop.","M"],["Why does double-checked locking need the field to be <code>volatile</code>?",["Others may see a non-null reference to a half-built object","It makes the lock fair, so threads don't starve","Without it, the JIT may cache the lock object itself","It forces the second null check to read main memory"],0,"volatile forbids publishing the reference before construction completes.","H"],["What does volatile guarantee?",["Atomicity for compound operations like count++ on it","Visibility and ordering for reads/writes of that variable","Mutual exclusion for any code that touches that variable","Fair, first-come access to that variable across threads"],1,"Not atomicity of count++.","E"],["Good use of volatile?",["A hit counter incremented by many request threads","A stop flag set by one thread and read by another","A shared list that several threads append to","An account balance debited by concurrent transfers"],1,"Single writes and reads.","E"],["What is \"happens-before\"?",["A rule that one thread is scheduled before another","A guarantee that one action's effects are visible to another","A lock that orders threads by their start time","A GC phase that runs before objects are collected"],1,"Created by locks, volatile, thread start/join, etc.","M"],["Does <code>Thread.start()</code> create a happens-before edge?",["No: the new thread may see stale values of all fields","Yes: everything before start() is visible to the new thread","Only for fields marked volatile before start()","Only on x86, which has a strong memory model"],1,"Same for join(): the thread's writes are visible afterwards.","M"],["Why can a plain field update be invisible to another thread?",["Private fields are only visible to the thread that last wrote them","Caches, store buffers and JIT optimisations may keep it local without a happens-before edge","The GC may move the object before the other thread reads it","Each thread works on its own heap copy until it calls join()"],1,"The JMM only promises visibility with synchronization.","M"]]},{"id":"t4-7","no":"4.7","title":"CAS and atomics","imp":"must","quiz":[["What does compareAndSet do?",["Locks the variable until you release it","Sets the value and returns the old one","Blocks until the value changes","Sets it only if it still equals the expected value"],3,"A single CPU instruction used in retry loops: lock-free and non-blocking.","E"],["A metrics counter is hammered by 64 threads. Which scales best?",["AtomicLong","LongAdder","A synchronized long","A volatile long"],1,"LongAdder spreads updates across cells to avoid CAS contention; sum() adds them up.","M"],["The ABA problem?",["Two threads write the same value A at once","The CPU reorders writes A and B across cores","A → B → A lets a CAS pass though state changed","A CAS loop that retries forever under contention"],2,"AtomicStampedReference pairs the value with a version.","H"],["Which class offers atomic increments?",["Integer","AtomicInteger","int","volatile int"],1,"incrementAndGet uses CAS.","E"],["What does <code>getAndIncrement()</code> return?",["The new value","The old value","void","true/false"],1,"incrementAndGet returns the new value.","E"],["What does \"lock-free\" mean?",["No thread ever retries, so every thread always progresses","Threads never block on a lock; at least one always makes progress","It's always faster than locking in every workload","The code runs on one thread, so no locks are needed"],1,"CAS loops retry instead of waiting.","M"],["Atomically set a value only if it's currently 5?",["if (get() == 5) set(newValue)","compareAndSet(5, newValue)","getAndSet(newValue)","compareAndSet(newValue, 5)"],1,"Returns false if it wasn't 5.","M"],["<code>AtomicInteger.updateAndGet(x -&gt; x * 2)</code> with contention: the lambda may run?",["Exactly once, since updates are serialized by a lock","More than once, so it must be side-effect free","At most once; contended updates are dropped","Once, but on a separate pool thread"],1,"CAS retries re-apply it.","H"]]},{"id":"t4-8","no":"4.8","title":"wait / notify","imp":"good","quiz":[["Calling <code>obj.wait()</code> without holding obj's lock?",["IllegalMonitorStateException","It works normally","The thread waits forever","It deadlocks"],0,"wait/notify must be called while holding that object's monitor.","E"],["Why check the condition in a <code>while</code> loop around wait()?",["An if is enough as long as you use notifyAll","Otherwise wait() would return immediately","To avoid ConcurrentModificationException","Spurious wakeups, or the condition changed again"],3,"Always: while (!ready) wait();","M"],["Producers and consumers share one monitor; a producer calls <code>notify()</code>. Risk?",["None: notify wakes the longest waiter, which is a consumer","It may wake another producer, and then everyone ends up waiting","notify releases the lock immediately","notify throws if nobody is waiting"],1,"One wait set holds both kinds of waiters. Use notifyAll, separate Conditions, or a BlockingQueue.","H"],["What does <code>notifyAll()</code> do?",["Wakes every thread waiting on that object's monitor","Releases the monitor immediately so waiters can run","Interrupts every thread blocked on that monitor","Wakes every waiting thread in the JVM, on any object"],0,"They then compete for the lock.","E"],["Does <code>wait()</code> release the monitor?",["No: it keeps holding the monitor while it waits","Yes, while waiting; it's re-acquired before returning","Only when called with a timeout argument","Yes, and it returns without re-acquiring it"],1,"Unlike sleep().","E"],["What is a spurious wakeup?",["A notify() sent when no thread is waiting yet","A thread returning from wait() without being notified","A thread woken by an interrupt during sleep()","A GC pause that briefly wakes all threads"],1,"Hence while loops.","M"],["Higher-level replacement for wait/notify producer-consumer?",["Thread.sleep","BlockingQueue","HashMap","volatile"],1,"put/take block as needed.","E"],["Which object should you call wait() on?",["Thread.currentThread(), since the current thread waits","The object whose lock you hold and that guards the condition","Any object, as long as some thread will notify it","The Thread object of the thread that will notify you"],1,"Lock, condition and wait must be on the same monitor.","M"]]},{"id":"t4-9","no":"4.9","title":"Deadlock, livelock, starvation","imp":"must","quiz":[["Thread 1 locks A then B; thread 2 locks B then A. Risk and standard fix?",["Race; make the account fields volatile","Starvation; switch to fair locks","Deadlock; always lock in one global order","Livelock; add a short random sleep"],2,"Breaking circular wait removes one of the four deadlock conditions.","E"],["How do you confirm a deadlock in a running JVM?",["A thread dump: it reports \"Found one Java-level deadlock\"","A heap dump: deadlocked threads' objects stay reachable","GC logs: a deadlock stops collections from finishing","Restart the service and see if it happens again"],0,"The dump shows which thread holds which lock and waits for which.","M"],["You order locks by <code>System.identityHashCode(obj)</code>. What edge case must you handle?",["identityHashCode changes when the GC moves objects","It isn't thread-safe to call concurrently","It's much slower than a single global lock","Two objects can share a hash; add a tie-break lock"],3,"Equal hashes give no order, so take a third \"tie\" lock first in that case.","H"],["Which is NOT one of the four deadlock conditions?",["Mutual exclusion","Hold and wait","Circular wait","High CPU usage"],3,"The others plus \"no preemption\".","E"],["What is starvation?",["All threads blocked waiting on each other forever","A thread repeatedly losing out and never getting the resource","A thread spinning in a busy loop that burns CPU","The JVM running out of heap for new threads"],1,"Fair locks can help.","M"],["How does tryLock with a timeout help with deadlocks?",["It sorts lock requests so all threads acquire them in order","A thread gives up instead of waiting forever, then retries or backs off","It makes the lock fair so waiters get it by arrival order","It detects the lock cycle and throws a DeadlockException"],1,"Breaks \"hold and wait\".","M"],["A thread dump shows thread A waiting for lock X held by B, and B waiting for lock Y held by A. That is?",["Livelock","Deadlock","Starvation","A race"],1,"A cycle of waits.","E"],["Does a deadlock use CPU?",["Yes: they spin at 100% CPU retrying","No: deadlocked threads are blocked, idle","Yes, but only one core is kept busy","Only while the GC scans their stacks"],1,"Hangs with low CPU often mean deadlock or waiting.","M"]]},{"id":"t4-10","no":"4.10","title":"ReentrantLock, ReadWriteLock, StampedLock","imp":"good","quiz":[["Why must <code>lock.unlock()</code> go in a <code>finally</code> block?",["Style convention only","Otherwise a throw skips it","For fairness","unlock() throws otherwise"],1,"Explicit locks aren't released automatically like synchronized.","E"],["Which ReentrantLock feature does synchronized lack?",["Re-entrancy","Visibility guarantees","Mutual exclusion","tryLock with a timeout"],3,"Also lockInterruptibly, fairness and multiple Conditions.","M"],["With StampedLock you read x and y after <code>tryOptimisticRead()</code>, and <code>validate(stamp)</code> returns false. Now?",["Discard the values and re-read under a real read lock","Use them: validate only matters for writes","Call unlockRead(stamp)","Keep calling validate until it returns true"],0,"False means a write happened; the values may be inconsistent.","H"],["What does <code>lock.lockInterruptibly()</code> allow?",["Acquiring the lock again without blocking","Giving up waiting if the thread is interrupted","Waiting for the lock with a fixed timeout","Granting the lock in fair arrival order"],1,"synchronized can't be interrupted while blocked.","M"],["Is ReentrantLock re-entrant?",["No: a second lock() from the same thread deadlocks","Yes: the same thread can lock it again; unlock as many times","Only when created in fair mode with new ReentrantLock(true)","Yes, and a single unlock() releases all nested holds"],1,"Hence the name.","E"],["ReadWriteLock allows?",["Many writers at once","Many readers at once, or one writer","Readers and writers at once","One reader only"],1,"Good for read-mostly data.","E"],["What does a fair ReentrantLock do?",["Prevents deadlock by ordering how threads acquire the lock","Grants the lock roughly in arrival order, reducing starvation but lowering throughput","Runs faster by letting the newest waiter barge in first","Gives each thread an equal time slice while holding it"],1,"Fairness has a cost.","M"],["Where must unlock() go?",["At the end of the method, after the last statement","In a finally block right after the try that follows lock()","In a catch block so it runs only when errors occur","Inside the try block, as its last statement"],1,"Otherwise an exception leaks the lock.","E"]]},{"id":"t4-11","no":"4.11","title":"Synchronizers: latch, barrier, semaphore","imp":"good","quiz":[["Main must wait until 3 services finish initialising, once. Which tool?",["CyclicBarrier(3)","Semaphore(3)","CountDownLatch(3)","Thread.yield in a loop"],2,"Each service calls countDown(); main calls await(). One-shot.","E"],["Limit concurrent calls to a fragile API to 10. Which tool?",["Semaphore(10)","CountDownLatch(10)","CyclicBarrier(10)","A ReentrantLock"],0,"A semaphore bounds \"at most N inside\".","M"],["A worker calls <code>semaphore.acquire()</code>, then throws before <code>release()</code>, with no finally. Effect?",["The permit is released when the thread dies","Semaphore releases automatically on exceptions","Another thread gets IllegalMonitorStateException","That permit is lost; capacity shrinks until callers block"],3,"Permits have no owner and aren't tied to threads. Always release in finally.","H"],["What does <code>latch.countDown()</code> do?",["Blocks the caller until the count reaches zero","Decrements the count; at zero, waiting threads are released","Resets the count back to its initial value","Releases one waiting thread per call to it"],1,"await() waits for zero.","E"],["Can a CountDownLatch be reset?",["Yes: call reset() once the count hits zero","No: it's one-shot; use CyclicBarrier or a new latch","Yes: await() resets it automatically after release","Only if it was created with a count of one"],1,"CyclicBarrier is reusable.","M"],["<code>Semaphore(3)</code> means?",["At most 3 threads in the whole JVM","At most 3 holders of a permit at once","A 3-second timeout on each acquire()","At most 3 acquires over its lifetime"],1,"acquire / release.","E"],["What happens to <code>semaphore.tryAcquire()</code> when no permits are left?",["Blocks forever","Returns false immediately","Throws","Creates a permit"],1,"tryAcquire(timeout) waits up to the timeout.","M"],["CyclicBarrier's barrier action runs?",["On every await() call, by each arriving thread","Once per generation, when the last thread arrives","Once only, the first time the barrier trips","On a new thread after all parties are released"],1,"Useful to merge partial results.","M"]]},{"id":"t4-12","no":"4.12","title":"ThreadLocal","imp":"good","quiz":[["Where is a ThreadLocal's value stored?",["In a static map inside ThreadLocal, keyed by thread id","In the current Thread's own map, keyed by the ThreadLocal","On the thread's stack, in a hidden frame","In Metaspace, next to the ThreadLocal class"],1,"That's why each thread sees its own value.","E"],["A web app sets a user id in a ThreadLocal per request on a thread pool and never calls remove(). Bug?",["None: Spring clears it when the request ends","ConcurrentModificationException on reuse","The next request on that thread sees the old id","OutOfMemoryError straight away"],2,"Pool threads live forever. Always remove() in finally.","M"],["You set a ThreadLocal, then call <code>CompletableFuture.supplyAsync(...)</code>. Does the async code see the value?",["No: it runs on another thread","Yes: async tasks inherit ThreadLocals","Only on virtual threads","Yes, if the ThreadLocal is static"],0,"The same applies to @Async and MDC logging context.","H"],["What does ThreadLocal give each thread?",["A shared value","Its own independent value","A lock","A stack"],1,"get/set act on the current thread's copy.","E"],["Common legitimate uses of ThreadLocal?",["Shared counters updated by all request threads","Per-request context: user, transaction, logging MDC","Caches meant to be shared across all threads","Locks that coordinate several worker threads"],1,"Clean up afterwards.","E"],["Why call remove() in a finally block?",["Values stay after the thread dies, leaking until the JVM exits","Pooled threads are reused; leftover values leak into later tasks and memory","Without it, other threads can read your stale per-thread value","The compiler requires ThreadLocals to be cleared before reuse"],1,"Classic production bug.","M"],["<code>ThreadLocal.withInitial(() -&gt; new SimpleDateFormat(...))</code> does what?",["Shares one formatter instance across all threads","Gives each thread its own formatter, created on first get()","Creates a new formatter on every call to get()","Eagerly creates formatters for all threads up front"],1,"A fix for non-thread-safe objects (prefer DateTimeFormatter).","M"],["Does <code>@Async</code> code see the caller's ThreadLocal values?",["Yes","No: it runs on another thread","Only static ThreadLocals","Only in tests"],1,"Propagate explicitly.","E"]]},{"id":"t4-13","no":"4.13","title":"Thread pools (ExecutorService)","imp":"must","quiz":[["Why avoid <code>Executors.newFixedThreadPool(n)</code> for a public API under load?",["Its threads are daemon, so they die with main","It can't be shut down cleanly","It has no core threads, only temporary ones","Its queue is unbounded, so overload just piles up"],3,"Use a bounded queue plus a rejection policy such as CallerRunsPolicy.","E"],["A task given to <code>submit()</code> throws, and nobody calls get(). What do you see?",["A stack trace in the logs","Nothing: the exception is stored in the Future","The pool shuts down","The worker thread dies and isn't replaced"],1,"execute() reports uncaught exceptions; submit() captures them. Handle the Future or log inside the task.","M"],["ThreadPoolExecutor core=2, max=4, queue capacity=2. 7 slow tasks arrive at once. The 7th?",["It waits in the queue","A 5th thread is created for it","It's rejected: 4 running, 2 queued","It replaces the oldest queued task"],2,"Order: fill core → queue → extra threads up to max → reject. Extra threads only start once the queue is full.","H"],["Why use a thread pool instead of <code>new Thread</code> per task?",["Pools are required by Java","Reuse threads and bound concurrency","Threads can't be created manually","Pools are single-threaded"],1,"Creating threads is expensive and unbounded creation is dangerous.","E"],["<code>Executors.newFixedThreadPool(4)</code> runs at most how many tasks at once?",["1","4","Unlimited","Depends on CPU"],1,"Extra tasks wait in an (unbounded) queue.","E"],["What happens after <code>executor.shutdown()</code>?",["Running tasks are interrupted and queued ones dropped","No new tasks accepted; already submitted ones finish","It blocks until all submitted tasks have finished","New tasks still queue, but no queued task runs"],1,"shutdownNow() interrupts running tasks.","M"],["What does <code>AbortPolicy</code> (the default) do on rejection?",["Runs the task on the calling thread","Throws RejectedExecutionException","Silently drops the rejected task","Discards the oldest queued task"],1,"Choose a policy deliberately.","M"],["For blocking I/O tasks, pool size should be?",["Exactly the core count, since extra threads just thrash the CPU","Larger than core count, sized for how long tasks wait (or use virtual threads)","Core count minus one, the same as for CPU-bound work","Unbounded, so that no submitted task ever has to wait"],1,"Threads mostly wait, not compute.","M"]]},{"id":"t4-14","no":"4.14","title":"Future vs CompletableFuture","imp":"must","quiz":[["Price (300 ms), reviews (500 ms) and stock (200 ms) are independent. Fan-out + allOf takes about?",["~500 ms","~1000 ms","~300 ms","~200 ms"],0,"Parallel calls finish when the slowest does.","E"],["Why pass your own executor to <code>supplyAsync</code> for blocking HTTP calls?",["The default executor is single-threaded","It's required for exceptions to reach the caller","supplyAsync won't compile without an executor","The shared commonPool is small; blocking starves it"],3,"Size an I/O pool for the downstream.","M"],["With no executor given, where does the function in <code>thenApply</code> run?",["Always on the ForkJoin commonPool","Always on the thread that called thenApply","On whichever thread completed the previous stage","On a brand-new thread each time"],2,"Non-async stages run inline. Use thenApplyAsync(fn, executor) to control it.","H"],["What does <code>supplyAsync</code> return?",["The value, after blocking until it's computed","A CompletableFuture that completes with the value later","A new Thread that has already started running","A Supplier wrapping the computation for later"],1,"Non-blocking start.","E"],["Chain another async call that returns a CompletableFuture?",["thenApply","thenCompose","thenAccept","join"],1,"thenApply would nest futures.","M"],["Combine two independent futures' results?",["thenCompose","thenCombine","exceptionally","orTimeout"],1,"Runs the combiner when both are done.","E"],["Wait for many futures to finish?",["anyOf","allOf","join each in parallel streams","thenRun"],1,"anyOf completes with the first.","E"],["What does <code>join()</code> do differently from <code>get()</code>?",["Returns null immediately if the future isn't complete yet","Throws unchecked CompletionException instead of checked exceptions","Cancels the future if it hasn't completed by the call","Waits with a default timeout, whereas get() waits forever"],1,"Convenient in lambdas.","M"]]},{"id":"t4-15","no":"4.15","title":"ForkJoinPool and work stealing","imp":"extra","quiz":[["Why is blocking I/O inside a parallel stream a bad idea?",["Parallel streams aren't allowed to do I/O","It blocks the shared commonPool for everyone","It disables the JIT for the whole pipeline","It makes the results come back unordered"],1,"Keep the common pool CPU-bound.","E"],["In a RecursiveTask, why compute one half yourself instead of forking both?",["Forking both halves is illegal","To avoid a stack overflow","To make execution deterministic","So the thread works instead of waiting"],3,"fork() one half, compute() the other, then join().","M"],["How does work stealing pick tasks?",["Owners pop newest; thieves take the oldest, biggest tasks","Each idle thread picks a random task from anyone","All threads share one global FIFO queue","Tasks are dealt round-robin to the threads"],0,"Stealing big tasks means fewer steals overall.","H"],["What kind of tasks suit ForkJoinPool?",["Blocking I/O like file and socket reads","Recursive divide-and-conquer CPU work","Long single tasks that can't be split","Database calls issued in parallel batches"],1,"Split, compute, combine.","E"],["RecursiveTask vs RecursiveAction?",["RecursiveAction returns a result; RecursiveTask doesn't","RecursiveTask returns a result; RecursiveAction doesn't","RecursiveTask can fork subtasks; RecursiveAction can't","RecursiveAction is for I/O; RecursiveTask for CPU work"],1,"compute() returns V or void.","M"],["What is the common pool's default parallelism?",["Number of available processors × 2","Number of available processors − 1","Exactly the number of available processors","A fixed 256, regardless of CPU count"],1,"Shared by the whole JVM.","M"],["What uses the common ForkJoinPool by default?",["Tomcat request threads and Spring @Async methods","Parallel streams and CompletableFuture async methods without an executor","Spring @Scheduled tasks and JDBC connection pools","Every pool created by Executors.newFixedThreadPool"],1,"Don't block it.","M"],["Why steal from the opposite end of another worker's deque?",["To keep tasks in strict FIFO order across all the workers","Older tasks are bigger, so fewer steals are needed and contention with the owner is low","So stolen tasks are always the smallest and finish fastest","Either end works; the opposite end is just a convention"],1,"Owner works LIFO at its end.","H"]]},{"id":"t4-16","no":"4.16","title":"Concurrent collections","imp":"must","quiz":[["Count word frequencies safely in a ConcurrentHashMap. Which call?",["map.put(w, map.get(w) + 1)","map.putIfAbsent(w, 1)","map.merge(w, 1, Integer::sum)","map.replace(w, map.get(w) + 1)"],2,"merge is atomic per key. get-then-put races.","E"],["ConcurrentHashMap (Java 8+) puts into an empty bucket how?",["It locks the segment that owns the bucket","It CASes the new node in with no lock","It locks the whole table","It copies the table"],1,"Segments were Java 7. Now: CAS for an empty bin, synchronized on the head node otherwise, lock-free reads.","M"],["Thread A iterates a ConcurrentHashMap while thread B inserts keys. A will...",["throw ConcurrentModificationException","see a consistent snapshot from when iteration started","block until B finishes","not throw, and may or may not see B's new keys"],3,"CHM iterators are weakly consistent.","H"],["Does ConcurrentHashMap allow null keys or values?",["Both allowed","Neither","Null keys only","Null values only"],1,"null would be ambiguous with \"absent\".","E"],["Atomic \"insert if absent\" in ConcurrentHashMap?",["containsKey followed by put","putIfAbsent or computeIfAbsent","get, then put if it was null","putAll with a single-entry map"],1,"Single atomic operation.","E"],["Which queue blocks producers when it's full?",["ConcurrentLinkedQueue","ArrayBlockingQueue","PriorityQueue","ArrayDeque"],1,"Bounded blocking queue.","E"],["What is ConcurrentSkipListMap?",["A concurrent hash map with linked buckets","A concurrent sorted map (like a thread-safe TreeMap)","A lock-free FIFO queue of key-value pairs","A size-bounded cache with LRU eviction"],1,"O(log n), lock-free.","M"],["<code>size()</code> on a ConcurrentHashMap under updates is?",["Exact, since it locks every bin","An estimate that may be stale","Blocking until updates finish","The count at the last resize"],1,"Don't base logic on it.","M"]]},{"id":"t4-17","no":"4.17","title":"Virtual threads (Java 21)","imp":"good","quiz":[["A virtual thread blocks on socket I/O. What happens to its carrier thread?",["It unmounts; the carrier runs other virtual threads","The carrier thread blocks along with it","The carrier is destroyed and later recreated","The carrier spins until the I/O completes"],0,"That's how millions of blocking virtual threads fit on a few carriers.","E"],["A CPU-bound image resizer moves to virtual threads. Expected speedup?",["About 10×","Proportional to the number of virtual threads","It becomes 10× slower","About none: the cores are the bottleneck"],3,"Virtual threads help with waiting, not computing.","M"],["10,000 virtual threads each call a database that allows 50 connections. What should you add?",["A fixed pool of 50 virtual threads to run the calls","Nothing: virtual threads queue up automatically","A Semaphore(50), or a bounded connection pool","A synchronized block around the database call"],2,"Don't pool virtual threads; limit the scarce resource. synchronized would also pin carriers before JDK 24.","H"],["What's the main benefit of virtual threads?",["Faster CPU-bound work, since they run on more cores at once","Very cheap threads, so blocking I/O code can scale to many concurrent tasks","No need for locks, because each virtual thread is isolated","Less GC work, since their stacks never live on the heap"],1,"Thread-per-request without the cost.","E"],["Which Java version made virtual threads final?",["17","19","21","25"],2,"JEP 444.","E"],["How do you enable virtual threads for Spring Boot request handling?",["Switch to WebFlux, which runs on virtual threads by default","spring.threads.virtual.enabled=true (Boot 3.2+, Java 21+)","server.tomcat.threads.virtual=true (Boot 3.0+, Java 17+)","Add a Loom starter dependency; no configuration is needed"],1,"Tomcat then uses virtual threads.","M"],["What is pinning?",["A virtual thread that can't unmount, blocking its carrier","A thread bound to one CPU core by affinity","A platform thread given the highest priority","A virtual thread stuck forever in a deadlock"],0,"Mostly synchronized blocks before JDK 24, and native calls.","M"],["Should virtual threads be pooled?",["Yes, like platform threads","No: create one per task","Only for CPU work","Only in tests"],1,"Pooling defeats the purpose.","E"]]},{"id":"t4-18","no":"4.18","title":"Classic problems: odd/even and the singleton","imp":"good","quiz":[["An app hangs. Best first diagnostic?",["Several thread dumps a few seconds apart","Increase the number of threads","Restart it with more heap","Add log statements and redeploy"],0,"Repeated dumps show which threads are stuck and which progress, and who owns which lock.","E"],["Odd/even threads alternate with wait/notify. One thread hangs at the very end. Typical cause?",["There are too many threads for the CPU count","The last thread exits without waking the other","The shared counter isn't declared volatile","The Integer cache hands both threads one object"],1,"Always handle the termination case and wake the other side.","M"],["In double-checked locking, why is the second null check (inside synchronized) needed?",["It's only there to make it faster","It avoids a NullPointerException on return","It isn't needed if the field is volatile","Two threads can pass the first check together"],3,"The outer check avoids locking; the inner one ensures one creation.","H"],["Two threads must print alternately. What shared state do they need?",["Two separate locks, one held by each thread","A lock plus a variable saying whose turn it is","A static final flag fixed at startup","Nothing, if both threads call Thread.yield()"],1,"Each waits until it's their turn.","E"],["Simplest thread-safe lazy singleton in Java?",["DCL without volatile","The holder idiom or an enum","synchronized on every line","A static block with sleep"],1,"The JVM handles the safety.","E"],["Producer-consumer interview question: best modern answer?",["wait/notify guarded by an if check","A BlockingQueue with put/take","Polling a list with Thread.sleep","A volatile ArrayList shared by both"],1,"Mention wait/notify as the low-level alternative.","M"],["How would you print numbers 1–10 with 3 threads in round-robin order?",["Three independent loops, each printing its own numbers","A shared counter plus lock/condition; each waits for its turn","One volatile int that all three threads increment freely","Start the threads in order; the OS keeps them in sequence"],1,"Generalises odd/even.","M"],["What makes a classic \"bank transfer\" concurrency answer correct?",["Marking both balances volatile so updates are visible","Locking both accounts in a consistent order (by id) to avoid deadlock","Synchronizing on the source account for the whole transfer","Locking the source, then the target, in the order of the call"],1,"Plus checks inside the locked section.","M"]]},{"id":"t5-1","no":"5.1","title":"IoC and dependency injection","imp":"must","quiz":[["Two beans implement <code>PaymentGateway</code>, and a service injects one by type. What happens?",["Spring picks the first bean it found","NoUniqueBeanDefinitionException","Spring injects both behind a proxy","The alphabetically first bean wins"],1,"Or inject List&lt;PaymentGateway&gt; / Map&lt;String, PaymentGateway&gt; to get all of them.","E"],["Why is constructor injection preferred over field injection?",["Final fields, easy tests, and cycles fail fast","It's faster at run time than field injection","Field injection can't inject interfaces","Only constructor-injected beans can be proxied"],0,"Required dependencies become explicit.","M"],["ServiceA needs ServiceB and ServiceB needs ServiceA, both through constructors. Best fix?",["Switch both to field injection","Set allow-circular-references=true","Add @Lazy to both constructors","Extract the shared part into a third bean"],3,"The workarounds hide a design problem.","H"],["What is Inversion of Control?",["Lower layers depend on higher layers instead of the other way round","The framework creates and wires objects instead of your code doing it","Objects look up their own dependencies through a static service locator","Interfaces are used everywhere so implementations swap at compile time"],1,"Dependency injection is how Spring does it.","E"],["What is a Spring bean?",["A serializable class with getters, setters and a no-arg constructor","An object created and managed by the Spring container","A configuration entry declared in application.properties","A class file loaded by Spring's custom class loader"],1,"Declared via @Component or @Bean.","E"],["With a single constructor, is <code>@Autowired</code> required on it?",["Yes: without it Spring can't inject anything","No: Spring uses it automatically","Only when the constructor is public","Only when parameters are interfaces"],1,"Since Spring 4.3.","M"],["Use @Bean instead of @Component when?",["For beans that must be singletons, since @Component is prototype","For third-party classes you can't annotate, or custom construction","For classes that need constructor injection rather than fields","For beans that should be created lazily instead of at startup"],1,"@Bean methods live in @Configuration classes.","M"],["What does @Primary do?",["Makes the bean initialise before all other beans","Marks the default bean when several match by type","Forces the bean to be a singleton in every context","Exposes the bean to child application contexts only"],1,"@Qualifier overrides it at an injection point.","E"]]},{"id":"t5-2","no":"5.2","title":"Bean lifecycle and scopes","imp":"must","quiz":[["A singleton service stores <code>private User currentUser</code> per request. What's wrong?",["Nothing: Spring isolates beans per request","It needs @Lazy so it's created per request","Every request thread shares it, so users clash","The field must be final to be safe"],2,"Keep singletons stateless; pass request data as parameters.","E"],["A singleton needs a fresh prototype bean on every call. How?",["Inject ObjectProvider&lt;Proto&gt; and call getObject() each time","@Autowired Proto proto, since prototypes are recreated per use","Make the singleton a prototype too","Call new Proto() inside the method"],0,"A directly injected prototype is created once, when the singleton is built. new skips DI.","M"],["Why can a <code>@Transactional</code> method called from <code>@PostConstruct</code> run without a transaction?",["Transactions stay disabled until startup completes","@PostConstruct methods are always treated as static","It does run in a transaction, as usual","It runs on the raw bean, before the proxy exists"],3,"Use ApplicationReadyEvent, or call through another bean.","H"],["Default bean scope?",["prototype","singleton","request","session"],1,"One instance per context.","E"],["What does prototype scope mean?",["One shared instance per HTTP request being handled","A new instance each time the bean is requested","One instance per thread, reused across requests","A template copy cloned from the singleton at startup"],1,"Spring doesn't manage its destruction.","E"],["Where do proxies for @Transactional get created in the lifecycle?",["In the constructor via a generated subclass call","In a BeanPostProcessor after initialisation","At compile time by an annotation processor","At the first method call through lazy weaving"],1,"postProcessAfterInitialization.","M"],["Order: constructor, dependency injection, @PostConstruct?",["Injection → constructor → @PostConstruct","Constructor → injection → @PostConstruct","Constructor → @PostConstruct → injection","@PostConstruct → constructor → injection"],1,"With constructor injection, the first two happen together.","M"],["Where should per-request data live instead of a singleton field?",["A static field guarded by the singleton's monitor","Method parameters/locals or request-scoped beans","A volatile field on the singleton bean itself","An instance field marked transient on the singleton"],1,"Keep singletons stateless.","E"]]},{"id":"t5-3","no":"5.3","title":"AOP proxies and self-invocation","imp":"must","quiz":[["<code>@Cacheable</code> on a <code>private</code> method. Effect?",["It works like on a public method","Compile error","Silently ignored","Spring fails at startup"],2,"Same for final and static methods.","E"],["In AOP terms, what is a pointcut?",["An expression choosing where advice applies","The code that runs around the method call","The generated proxy class for the bean","The exception type that triggers advice"],0,"Aspect = advice (what) + pointcut (where).","M"],["<code>placeOrder()</code> calls <code>this.audit()</code>, which is <code>@Async</code>. What happens?",["audit runs asynchronously","audit runs synchronously","It deadlocks","Startup fails"],1,"Self-invocation skips the proxy. Move audit() to another bean.","H"],["What is \"advice\" in AOP?",["The expression that selects which methods to intercept","The code an aspect runs (before/after/around a method)","The proxy object Spring generates around a bean","The point in execution where an aspect may apply"],1,"Pointcut says where; advice says what.","E"],["Which advice can skip or replace the target call?",["@Before","@After","@Around","@AfterReturning"],2,"It controls proceed().","M"],["What's a join point in Spring AOP?",["Any field access on a Spring bean","A method execution on a Spring bean","A constructor call on any Java object","A pointcut expression combined with advice"],1,"Spring AOP only intercepts method calls.","M"],["Why does AOP only apply to Spring beans?",["Aspects are compiled into beans by the Spring Boot plugin","Interception is done by proxies Spring creates around beans","Only beans are loaded by Spring's instrumenting class loader","Non-bean classes lack the metadata the pointcut parser needs"],1,"new MyService() isn't proxied.","E"],["Which annotation enables custom @Aspect classes in Spring Boot?",["Nothing extra: auto-configured with spring-boot-starter-aop","@AspectScan on the main application class","@EnableAop plus an aop.xml file in META-INF","@EnableWeaving on a @Configuration class"],0,"Boot enables @EnableAspectJAutoProxy for you.","M"]]},{"id":"t5-4","no":"5.4","title":"@Transactional: propagation and rollback","imp":"must","quiz":[["A @Transactional method throws a checked <code>IOException</code>. By default?",["It rolls back","It rolls back only if the method declares throws IOException","It's retried","It commits: only unchecked exceptions and Errors roll back by default"],3,"Use rollbackFor = Exception.class if needed.","E"],["An audit row must be saved even if the business transaction rolls back. Propagation?",["REQUIRES_NEW","NESTED","REQUIRED","SUPPORTS"],0,"REQUIRES_NEW suspends the outer tx and commits on its own connection. NESTED is a savepoint, which rolls back with the outer.","M"],["Outer @Transactional (REQUIRED) calls inner @Transactional (REQUIRED), which throws a RuntimeException. Outer catches it and returns normally. Result?",["Outer commits everything, including inner's writes","Inner's work rolls back, but outer still commits","UnexpectedRollbackException: tx is rollback-only","Nothing is saved, and no exception surfaces"],2,"Both share one physical transaction; the inner failure poisons it.","H"],["What does @Transactional do on success?",["Rolls back","Commits","Nothing","Retries"],1,"And rolls back on unchecked exceptions.","E"],["Default propagation?",["REQUIRES_NEW","REQUIRED","NESTED","NEVER"],1,"Join an existing transaction or start one.","E"],["MANDATORY propagation means?",["Always starts a new transaction, suspending any existing one","Must run inside an existing transaction, otherwise an exception","Runs without a transaction, throwing if one already exists","Joins a transaction if present, otherwise runs non-transactionally"],1,"Guards methods that must not run alone.","M"],["@Transactional on a private method?",["Works, but only when called from another bean","Ignored: proxies can't intercept private methods","Fails at startup with a BeanCreationException","Works, but the transaction is always read-only"],1,"Same for self-invocation.","E"],["Why keep transactions short?",["Hibernate flushes only at commit, so long ones lose writes","They hold connections and locks, blocking others and draining pools","The JDBC driver aborts any transaction older than a few seconds","Long ones bypass the first-level cache and reload every entity"],1,"See 6.4.","M"]]},{"id":"t5-5","no":"5.5","title":"JPA and Hibernate: states, dirty checking, N+1, locking","imp":"must","quiz":[["Load 100 orders, then access <code>order.getItems()</code> (LAZY) in a loop. How many queries?",["101 (N+1)","1","2","100"],0,"Fix with JOIN FETCH, @EntityGraph or batch fetching.","E"],["In a transaction you load a managed entity and call a setter, without save(). At commit?",["Nothing: changes need save()","An exception about unsaved changes","An INSERT","An UPDATE, from dirty checking at flush"],3,"Managed entities are compared with their snapshot at flush.","M"],["Two users edit the same entity, which has <code>@Version</code>. The second save?",["It waits for the first user's row lock, then commits","OptimisticLockException: the versioned UPDATE hits 0 rows","It silently overwrites the first user's change","Hibernate merges both users' changes field by field"],1,"Optimistic locking detects lost updates without holding locks.","H"],["What's the persistence context?",["The shared cache of entities across all sessions (second-level cache)","The set of entities managed in the current transaction (first-level cache)","The mapping metadata Hibernate builds from your @Entity classes","The JDBC connection plus its open statements for the request"],1,"find() twice returns the same instance.","E"],["Which fetch type is the default for @ManyToOne?",["LAZY","EAGER","NONE","BATCH"],1,"Make it LAZY explicitly.","M"],["Fix N+1 when listing orders with their items?",["FetchType.EAGER on the items collection","JOIN FETCH / @EntityGraph / batch fetching","An index on the order_id foreign key","A larger connection pool and @Transactional"],1,"Load associations in one or few queries.","E"],["What does <code>merge(detached)</code> return?",["The same instance, now attached to the context","A managed copy; the passed object stays detached","A detached copy; the passed object becomes managed","Nothing; it reattaches the passed object in place"],1,"Use the returned instance.","M"],["What does <code>@Version</code> add?",["Pessimistic row locking on every read","Optimistic locking via a version column","Audit history of each change in a table","Schema versioning for Flyway migrations"],1,"Detects lost updates.","E"]]},{"id":"t5-6","no":"5.6","title":"Spring Boot startup and auto-configuration","imp":"good","quiz":[["Your @Service is in <code>com.acme.other</code>, the main class in <code>com.acme.app</code>. It isn't found. Why?",["It's missing a @Bean method in a config class","Spring only scans @Configuration classes","Scanning starts at the main class's package","Service classes must be declared public"],2,"Put the main class in the root package.","E"],["You declare your own <code>DataSource</code> bean. What does Boot's auto-configured one do?",["It backs off: @ConditionalOnMissingBean","It overrides yours","Both are created and startup fails","They're merged"],0,"Auto-configuration is conditional; your beans win.","M"],["spring-boot-starter-data-jpa is on the classpath, but no datasource URL and no embedded DB driver. Startup?",["It starts with an in-memory database it creates","It starts with JPA silently disabled","It starts, then fails on the first query","It fails: a DataSource URL is required"],3,"DataSource auto-configuration can't determine a URL.","H"],["What is a Spring Boot starter?",["A main class template that bootstraps the application context","A dependency that brings a curated set of libraries and auto-configuration","A Maven plugin that generates project skeletons from templates","A profile that activates default properties for a module"],1,"e.g. spring-boot-starter-web.","E"],["What starts Tomcat in a Boot web app?",["The Maven plugin deploys the app to a local server","Auto-configuration creates an embedded server","The JVM launches Tomcat from a system install","SpringApplication downloads Tomcat on first run"],1,"The app is a runnable JAR.","E"],["Where are auto-configuration classes listed (Boot 3)?",["META-INF/spring.factories under the EnableAutoConfiguration key","META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports","META-INF/spring/autoconfigure.properties in each starter","application.yml under spring.autoconfigure.include"],1,"Older Boot used spring.factories.","H"],["@ConditionalOnClass means?",["Apply if a class is on the classpath","Apply if a bean of that class exists","Apply if the class matches an active @Profile","Apply if the class is in a scanned package"],0,"e.g. only configure Jackson if Jackson is present.","M"],["How do you disable a specific auto-configuration?",["@ComponentScan(excludeFilters = …) on the main class","@SpringBootApplication(exclude = …) or spring.autoconfigure.exclude","@EnableAutoConfiguration(disabled = …) or spring.autoconfigure.skip","spring.main.lazy-initialization=true or @Lazy on the class"],1,"Or define your own bean so it backs off.","M"]]},{"id":"t5-7","no":"5.7","title":"Configuration precedence and profiles","imp":"good","quiz":[["Env var <code>PAYMENT_TIMEOUT_MS</code> binds to which property?",["Nothing: env vars must match exactly","payment.timeout-ms, through relaxed binding","payment_timeout_ms only","PAYMENT_TIMEOUT_MS only"],1,"Relaxed binding maps env-var style to property names.","E"],["<code>server.port</code>: 8080 in application.yml, 9090 in application-prod.yml, env SERVER_PORT=7070, <code>--server.port=6060</code>. Profile prod is active. Port?",["9090","7070","6060","8080"],2,"Command-line arguments beat env vars, which beat profile files, which beat application.yml.","M"],["<code>@Value(\"${payment.timeout}\")</code> is set only in application-prod.yml, and the app runs without prod. Result?",["Startup fails: unresolvable placeholder","The field stays null until prod is active","The field defaults to 0, as for any int","A warning is logged and an empty string is used"],0,"Give a default (${payment.timeout:5000}) or define it in application.yml.","H"],["What activates a profile?",["spring.profiles.active=prod (property, env var or arg)","A @Profile annotation on the main application class","Naming the JAR after the profile, e.g. app-prod.jar","spring.config.name=prod passed on the command line"],0,"SPRING_PROFILES_ACTIVE as env var.","E"],["Which file holds properties for profile dev?",["application.dev.yml (or .properties)","application-dev.yml (or .properties)","profile-dev.yml (or .properties)","dev.application.yml (or .properties)"],1,"Loaded on top of application.yml.","E"],["<code>@Value(\"${timeout:5000}\")</code> means?",["Use 5000 unless timeout is set to a larger value","Use property timeout, or 5000 if it's missing","Set timeout to 5000, overriding any configured value","Use timeout, capped at a maximum of 5000"],1,"Default after the colon.","M"],["Where should database passwords come from in production?",["application-prod.yml committed to Git, encoded with Base64","Environment variables or a secret store (Vault, Kubernetes secrets)","A constants class compiled into the JAR and obfuscated","JVM system properties baked into the Docker image"],1,"Never commit secrets.","E"],["Does a command-line argument beat an environment variable?",["No","Yes","Only for ports","They merge"],1,"Command line has higher precedence.","M"]]},{"id":"t5-8","no":"5.8","title":"Web layer: request flow","imp":"good","quiz":[["A body fails <code>@Valid</code>. Where do you map that to a 400 JSON error for every controller?",["A try/catch in every controller method","A servlet filter in front of the dispatcher","A custom ErrorController per endpoint","A @RestControllerAdvice @ExceptionHandler"],3,"Central, consistent error mapping.","E"],["Add a request-id header to every response, including static resources and error pages. Filter or HandlerInterceptor?",["HandlerInterceptor","A Filter","An @Aspect on controllers","@ControllerAdvice"],1,"Filters run for everything in the servlet container; interceptors only see requests mapped to handlers.","M"],["<code>@Valid OrderDto</code> has <code>List&lt;ItemDto&gt; items</code> without @Valid; ItemDto has @NotNull fields. Are items validated?",["Yes: Bean Validation always cascades into collections","Only the first item in the list is validated","No: the items field needs @Valid to cascade","Yes, as long as ItemDto is declared as a record"],2,"Bean Validation only cascades into fields marked @Valid.","H"],["Which annotation marks a class returning JSON from handler methods?",["@Controller","@RestController","@Service","@Component"],1,"@Controller + @ResponseBody.","E"],["Read <code>/cars/7</code>'s 7 into a parameter?",["@RequestParam","@PathVariable","@RequestBody","@Header"],1,"@RequestParam reads ?query=params.","E"],["Which status should a successful POST that creates a resource return?",["200","201 Created","204","302"],1,"Often with a Location header.","M"],["What converts Java objects to JSON in Spring MVC?",["The ViewResolver (Thymeleaf)","HttpMessageConverters (Jackson)","Tomcat's response encoder (Coyote)","HandlerInterceptors (Gson)"],1,"Content negotiation picks one.","M"],["What does <code>@Valid @RequestBody CarDto dto</code> trigger on failure?",["ConstraintViolationException → 500 by default","MethodArgumentNotValidException → 400 by default","BindException → 422 by default","HttpMessageNotReadableException → 400 by default"],1,"Customise the body in @ControllerAdvice.","M"]]},{"id":"t5-9","no":"5.9","title":"Spring Security with JWT","imp":"good","quiz":[["Valid JWT, but the user lacks ADMIN for <code>/admin</code>. Status?",["403","401","404","500"],0,"401 = not authenticated; 403 = authenticated but not allowed.","E"],["Is a JWT's payload secret?",["Yes: it's encrypted with the signing key","Only the roles claim is encrypted","It depends on the token's expiry","No: it's only encoded and signed"],3,"Signing prevents tampering, not reading. Don't put secrets in a JWT.","M"],["A user is banned, but their 24-hour JWT still works. Standard mitigation?",["Delete the user's HttpSession on the server","Short-lived access tokens plus refresh tokens","Call SecurityContextHolder.clearContext() on logout","Set the token's exp to now on the server"],1,"Stateless tokens can't be changed server-side; keep them short and revoke refresh tokens.","H"],["Authentication vs authorisation?",["Authentication = what you may do; authorisation = who you are","Authentication = who you are; authorisation = what you may do","Authentication = the login form; authorisation = the session cookie","Authentication = for end users; authorisation = for services"],1,"401 vs 403.","E"],["Where does a JWT usually travel?",["In the URL","In the Authorization: Bearer header","In the body of every request","In a server session"],1,"Sometimes in a cookie.","E"],["What part of a JWT proves it wasn't tampered with?",["Header","Payload","Signature","Base64"],2,"Signed with a secret or private key.","E"],["Where are passwords stored securely?",["Hashed once with fast SHA-256 so logins stay quick","Hashed with a slow, salted algorithm like bcrypt/argon2","Encrypted with AES using a key stored in the code","Base64-encoded with a salt so they can't be read"],1,"Spring Security's PasswordEncoder.","M"],["@PreAuthorize(\"hasRole('ADMIN')\") does what?",["Checks the role after the method runs, filtering its result","Checks the current user's role before the method runs","Grants the ADMIN role to the caller for that method","Restricts the URL mapped to the method in the filter chain"],1,"Method security (enable with @EnableMethodSecurity).","M"]]},{"id":"t5-10","no":"5.10","title":"Caching, scheduling, async, retries","imp":"good","quiz":[["@Cacheable with local Caffeine caches on 3 pods. Pod A updates a price. Pods B and C serve?",["The new price immediately","An error until they reload","Nothing: the entry is evicted everywhere","Possibly the stale price until TTL or eviction"],3,"Local caches are per pod. Use a short TTL, a shared cache or invalidation messages.","E"],["A <code>@Scheduled</code> nightly billing job, 4 pods. What happens, and the fix?",["Runs once: Spring coordinates pods","Runs 4 times: use ShedLock or similar","Runs only on the leader pod","Doesn't run in Kubernetes"],1,"Scheduling is per JVM.","M"],["<code>@Retryable</code> on a \"charge card\" call with no idempotency key. Risk?",["None: retries only happen after a failure","Slower startup while retry proxies are built","Double charge if the first attempt actually succeeded","Cache misses on the payment client"],2,"A timeout is an unknown outcome. Only retry idempotent operations, with backoff and jitter.","H"],["What does <code>@Cacheable(\"cars\")</code> do on a cache hit?",["Runs the method and refreshes the cached value","Returns the cached value without running the method","Runs the method, then compares it to the cache","Returns the cached value, then refreshes it async"],1,"On a miss it runs and stores.","E"],["Which annotation removes a cache entry?",["@CachePut","@CacheEvict","@Cacheable","@Caching"],1,"@CachePut always runs and updates.","M"],["What enables @Scheduled?",["Nothing","@EnableScheduling","@Async","@EnableCaching"],1,"Then use fixedRate, fixedDelay or cron.","E"],["fixedRate vs fixedDelay?",["fixedDelay: start every N ms; fixedRate: N ms after the last run ends","fixedRate: start every N ms; fixedDelay: N ms after the last run ends","fixedRate: N ms after the last run ends; fixedDelay: once after N ms","fixedDelay waits N ms before the first run; fixedRate starts at once"],1,"Default scheduler is single-threaded.","M"],["What does @Async return for a value?",["The value, computed on another thread","A CompletableFuture (or void)","An Optional filled in later","A Thread you can join()"],1,"Configure a bounded executor.","M"]]},{"id":"t5-11","no":"5.11","title":"Spring Data JPA","imp":"good","quiz":[["When does Spring Data parse <code>findByMakeAndYearGreaterThan(String make, int year)</code>?",["At startup; a typo fails startup","On every call, then it's cached","At compile time by an annotation processor","Never: you must write @Query"],0,"Derived queries are created from the method name.","E"],["Paging to page 50,000 with OFFSET is slow. Better?",["Bigger page sizes, so fewer pages","An index on every column used","Slice instead of Page","Keyset: WHERE id &gt; :lastId"],3,"OFFSET still scans and discards the skipped rows. Slice only skips the COUNT.","M"],["<code>@Modifying @Query(\"update Car ...\")</code> runs, then you read a Car already loaded in the same persistence context. You see?",["The new value","Maybe the old value","An exception","null"],1,"Use clearAutomatically = true, or clear/refresh.","H"],["What does <code>JpaRepository&lt;Car, Long&gt;</code> give you?",["A generated SQL schema plus migration scripts for the Car table","CRUD, paging and sorting methods without writing implementations","Only findAll and save; paging needs a separate repository","A JDBC template preconfigured with the Car table's columns"],1,"Spring generates the implementation.","E"],["<code>findByEmail(String email)</code> becomes?",["A runtime reflection call","SELECT … WHERE email = ?","A full table scan in Java","Nothing"],1,"Derived query.","E"],["Page vs Slice?",["Slice runs an extra COUNT for totals; Page only knows if there's a next page","Page runs an extra COUNT for totals; Slice only knows if there's a next page","Page loads all rows and splits them in memory; Slice uses LIMIT","Page supports sorting; Slice returns rows in insertion order only"],1,"Slice is cheaper for infinite scroll.","M"],["Write a custom JPQL query?",["@Sql(\"select c from Car c where …\")","@Query(\"select c from Car c where …\")","@Select(\"select c from Car c where …\")","@Jpql(\"select c from Car c where …\")"],1,"nativeQuery = true for SQL.","E"],["Fetch only id and name for a list page?",["Use FetchType.LAZY on the other columns","Use a projection (interface or record DTO)","Use a Page with a small page size","Use @Transient on the unused fields"],1,"Less data, no dirty checking.","M"]]},{"id":"t5-12","no":"5.12","title":"Testing Spring apps","imp":"good","quiz":[["Test only a controller's mapping, validation and JSON. Which?",["@SpringBootTest with a real server","@DataJpaTest","@WebMvcTest with MockMvc, mocking the service","A plain JUnit test calling the method"],2,"Loads only the MVC layer.","E"],["Why prefer Testcontainers (real PostgreSQL) over H2 for repository tests?",["Dialect, constraints and locking differ from production","H2 is slower than PostgreSQL for large test datasets","H2 can't run inside CI pipelines without a license","Testcontainers needs no Docker, so tests start faster"],0,"Test against the engine you run.","M"],["The suite is slow because Spring contexts keep reloading. Common cause?",["Too many assertions per test","Using JUnit 5","Using MockMvc","Differing @MockBean setups"],3,"Keep test configurations consistent so the cached context is reused.","H"],["@SpringBootTest loads?",["Only the web layer and controllers","The full application context","Only beans in the test's own package","A mock context with no real beans"],1,"Slowest, most realistic.","E"],["@DataJpaTest loads?",["The full application context, but with transactions disabled","JPA components (entities, repositories) with an embedded or configured DB","Repositories only, with every query mocked by Mockito","Controllers and services, with an in-memory repository stub"],1,"Transactions roll back after each test.","E"],["MockMvc lets you?",["Start a real embedded server on a random port for HTTP tests","Call controllers through the MVC stack without a network server","Mock the repository layer so controllers never touch the DB","Run load tests against controllers with many virtual users"],1,"Check status, headers and JSON.","M"],["Why test against a real database with Testcontainers?",["Faster test runs than any in-memory database can offer","Same SQL dialect, constraints and behaviour as production","No Docker dependency, so it runs on any CI agent","Spring Boot requires it for @DataJpaTest to start"],1,"H2 can hide dialect issues.","M"],["What's the test pyramid?",["Many end-to-end tests, fewer integration tests, very few unit tests","Many fast unit tests, fewer integration tests, very few end-to-end tests","Equal numbers of unit, integration and end-to-end tests per feature","Mostly integration tests, with unit tests only for utility classes"],1,"Fast feedback with confidence.","E"]]},{"id":"t5-13a","no":"5.13a","title":"Circuit breaker, timeouts, retries","imp":"must","quiz":[["Pricing is down and the caller has no timeouts or breaker. Typical result?",["Threads pile up waiting, and the caller fails too","Nothing: the HTTP client gives up after a second","It falls back to a cached value automatically","It fails fast with a clear error message"],0,"Default HTTP timeouts are often infinite or very long: cascading failure.","E"],["What is HALF_OPEN for?",["Letting all traffic through again","Blocking traffic until a restart","Resetting the failure metrics","Testing recovery with a few calls"],3,"Success closes the breaker; failure re-opens it.","M"],["Why add jitter to retry backoff?",["To make retry tests deterministic","To lower average latency","So clients don't all retry at once","Because the HTTP spec requires it"],2,"Synchronised retries cause retry storms.","H"],["Circuit breaker states?",["ON / OFF","CLOSED, OPEN, HALF_OPEN","READY / BUSY","NEW / DONE"],1,"CLOSED = normal.","E"],["What happens to calls when the breaker is OPEN?",["They wait in a queue until the breaker moves back to CLOSED","They fail fast (or use a fallback) without calling the service","They're retried with backoff until the service responds again","They pass through, but failures are no longer counted"],1,"Gives the dependency time to recover.","E"],["Which calls are safe to retry?",["Any call that failed with a 4xx client error","Idempotent ones (or protected by an idempotency key)","Only POST calls, since they create new resources","Any call, as long as backoff is configured"],1,"Retrying a charge can double-charge.","M"],["What's a fallback?",["A second attempt of the same call after a short backoff delay","An alternative response when the call fails (cache, default, degraded)","A timeout that cancels the call when the service is too slow","A breaker state where a few trial calls are let through"],1,"Graceful degradation.","E"],["Why must every remote call have a timeout?",["HTTP clients reject requests that don't declare a timeout","Without one, threads can wait forever and the caller collapses","Timeouts make retries idempotent, so duplicates are avoided","Load balancers drop connections that have no client timeout set"],1,"Timeouts come first.","M"]]},{"id":"t5-13b","no":"5.13b","title":"Saga and the Outbox pattern","imp":"good","quiz":[["Order created, payment charged, inventory reservation fails. In a saga, next?",["A distributed two-phase-commit rollback","Compensations in reverse: refund, then cancel","Nothing: the order stays half done","Retry the inventory call until it works"],1,"Each step has a compensation.","E"],["What does the Outbox pattern solve?",["Slow queries under load","Thread pool exhaustion","Schema migrations across services","DB save and Kafka publish in one step"],3,"Avoids \"saved but not published\" and \"published but rolled back\".","M"],["The outbox relay publishes at-least-once. What must consumers be?",["Idempotent","Stateless","Single-threaded","Timestamp-ordered"],0,"Duplicates will happen.","H"],["Why can't a normal database transaction span two microservices?",["HTTP calls are stateless, so they can't carry a transaction ID","Each service has its own database; there's no shared transaction","Spring only supports @Transactional within a single bean","Message brokers like Kafka reject any transactional producer"],1,"Sagas coordinate local transactions instead.","E"],["What is a compensating action?",["A database rollback of the earlier step's transaction","A business \"undo\" of an earlier step, e.g. refund","A retry of the failed step with a new idempotency key","A timeout that cancels the step if it runs too long"],1,"Must be idempotent.","E"],["Orchestration means?",["Services react to each other's events with no central owner","A central coordinator tells each service what to do next","A coordinator runs two-phase commit across all databases","Each service polls a shared table to find its next task"],1,"Choreography is the event-driven alternative.","M"],["In the outbox pattern, who publishes to Kafka?",["The request thread, inside the transaction","A separate relay reading the outbox table (polling or CDC)","The database","The consumer"],1,"After the transaction commits.","M"],["What delivery guarantee does the outbox give?",["Exactly-once","At-least-once","At-most-once","None"],1,"Consumers must deduplicate.","M"]]},{"id":"t5-13c","no":"5.13c","title":"Idempotency keys (no double charge)","imp":"good","quiz":[["The client times out on POST /payments and retries. How does the server avoid charging twice?",["It ignores every retry","It locks the account for a minute","Idempotency key → stored response","The client switches to GET"],2,"Same key, same result, no duplicate side effect.","E"],["Two copies of a request with the same key arrive in the same millisecond. What stops both from running?",["A UNIQUE constraint on the key: only one insert wins","An in-memory HashMap of seen keys","Checking whether the key exists, then inserting","A short Thread.sleep"],0,"Check-then-insert races (4.4); the DB constraint is atomic and works across pods.","M"],["The same key arrives with a different request body. Best response?",["Process it as a new request","Return the stored response","Ignore the new body","Reject it: the request hash differs"],3,"Signals a client bug.","H"],["What is an idempotent operation?",["One that returns the same response time on every call","One that has the same effect whether it runs once or many times","One that never fails, so it never needs to be retried","One that only reads data and never changes any state"],1,"e.g. setting a value, not incrementing it.","E"],["Who generates the idempotency key?",["The server, once per incoming HTTP request","The client, once per logical operation","The database, as the order's primary key","The client, freshly for every retry attempt"],1,"Retries reuse the same key.","E"],["What does the server store with each key?",["The client's credentials so retries can re-authenticate","The status and the response (plus a request hash)","Only the client IP address and the request time","A lock that expires once the first request finishes"],1,"To replay the same response.","M"],["Is <code>PUT /cars/7 {price: 100}</code> naturally idempotent?",["No: each PUT creates a new version of the car","Yes: repeating it leaves the same state","No: only GET and DELETE are idempotent by spec","Only if an idempotency key header is sent too"],1,"Unlike POST /charges.","M"],["How long should idempotency keys be kept?",["Forever, so any replay at any time returns the original result","A bounded retention window (e.g. 24 h–7 days), long enough for retries","Only until the response is sent, then delete it right away","Until the next deploy, since keys live in application memory"],1,"Then expire them.","M"]]},{"id":"t6-1","no":"6.1","title":"Flash sale: overselling the last unit","imp":"must","quiz":[["<code>UPDATE product SET stock = stock - 1 WHERE id = 42 AND stock &gt;= 1</code> returns 0 rows affected. What does that mean?",["A deadlock happened and it was rolled back","The item is sold out (or missing); report that to the user","The UPDATE failed and should be retried until it returns 1","Another transaction holds the row, so try again later"],1,"Rows affected is the result of the atomic check. Concurrent updates wait for the row lock, then re-check.","E"],["Each pod's <code>buy()</code> is <code>synchronized</code>. Two pods, stock 1. Can it oversell?",["No: synchronized prevents races","Only if buy() is static","Yes: monitors are per JVM","Only at READ UNCOMMITTED"],2,"Monitors live in one heap. Shared state in a DB needs a DB-level guarantee.","M"],["Stock 5. Two concurrent JPA read-modify-write purchases of 1 unit each, no @Version. Final stock?",["3","5","It throws OptimisticLockException","4: one decrement is lost"],3,"Both read 5 and write 4. Without @Version nothing detects the lost update.","H"],["Why can't <code>synchronized</code> prevent overselling across two pods?",["synchronized is released whenever a DB call blocks","Each pod is a separate JVM with its own locks","Pods share memory, but locks aren't visible across them","The JIT removes synchronized on Spring singleton beans"],1,"Shared state lives in the database.","E"],["Which SQL makes \"check stock and decrement\" atomic?",["SELECT stock FROM … WHERE id = ?, then UPDATE … SET stock = ?","UPDATE … SET stock = stock - 1 WHERE id = ? AND stock &gt;= 1","UPDATE … SET stock = ? WHERE id = ? AND version IS NOT NULL","INSERT INTO reservations VALUES (?, 1), then SELECT COUNT(*)"],1,"Then check rows affected.","E"],["What should the app do when the conditional UPDATE affects 0 rows?",["Retry the UPDATE until a row is affected","Report sold out (or conflict) to the user","Ignore it, since the order is already saved","Insert a new stock row and try the update again"],1,"0 rows = condition failed.","M"],["What safety net catches bugs that would make stock negative?",["A unique index on (product_id, stock)","A CHECK (stock &gt;= 0) constraint","A nightly job that resets negatives to 0","An ERROR log line when stock drops below 0"],1,"The DB rejects invalid states.","M"],["Optimistic locking approach for the same problem?",["SELECT … FOR UPDATE on Product, then decrement","@Version on Product, retry on OptimisticLockException","synchronized on Product, retry on InterruptedException","READ UNCOMMITTED isolation, retry on deadlock errors"],1,"Good when conflicts are rare.","M"]]},{"id":"t6-2","no":"6.2","title":"Memory leak in production: from alert to fix","imp":"good","quiz":[["A cache key is <code>userId + \":\" + System.nanoTime()</code>. Effect?",["Better spread across buckets","It never hits and grows forever","Fewer collisions, faster gets","Entries expire after a while"],1,"Keys must contain exactly the inputs that determine the value.","E"],["Which GC pattern most strongly suggests a leak?",["Heap reaching 90% between collections","Many young GCs every minute","Memory after each full GC rising for days","One long pause right after a deploy"],2,"A healthy heap returns to a stable floor. A rising floor means reachable data is piling up.","M"],["In a heap dump, what does the dominator tree tell you?",["Memory freed if an object became unreachable","Which thread allocated the most memory","The oldest objects still in the heap","Which classes were loaded most often"],0,"Combined with the path to GC roots, it shows what holds memory and why.","H"],["What is a memory leak in Java?",["Objects the GC forgets to track after a full collection cycle","Objects still referenced but no longer needed, so the GC can't free them","Unreferenced objects the GC hasn't collected yet at that moment","Memory used by large arrays that the JVM can't compact"],1,"Reachable but useless.","E"],["Which file format is a Java heap dump?",[".jfr",".hprof",".log",".class"],1,"Open it in Eclipse MAT or IntelliJ.","E"],["Which tool gives a cheap overview of what's filling the heap?",["Thread dump","jcmd GC.class_histogram","top","EXPLAIN"],1,"Counts and bytes per class.","M"],["What's wrong with a static <code>HashMap</code> cache with no eviction?",["Its entries are weakly held, so the GC may drop them","It grows forever and is shared across threads unsafely","Static maps are copied per thread, wasting memory","Lookups slow down as it rehashes on every put"],1,"Use a bounded concurrent cache.","E"],["Restarting a leaking service every night is?",["A proper fix, since the heap starts clean each day","A workaround that hides the bug and loses evidence","Best practice recommended by the JVM documentation","A fix, as long as the restart is during low traffic"],1,"Capture a dump, find the root cause.","M"]]},{"id":"t6-3","no":"6.3","title":"Thread-pool starvation: the batch that never finishes","imp":"good","quiz":[["Which change removes the blocking wait?",["Replace join() with get()","Double the pool size","Add Thread.sleep before join()","Compose with thenCombine"],3,"A bigger pool only moves the threshold. Composition doesn't hold a thread while waiting.","E"],["Fixed pool of 4. Each task submits a subtask to the same pool and calls <code>join()</code>. 4 tasks start at once. What happens?",["Subtasks run on temporary extra threads","The JVM detects the deadlock and throws","All 4 threads wait on queued subtasks","It finishes, just slowly"],2,"Thread-pool starvation deadlock. With no lock cycle, nothing detects it.","M"],["Why did it never hang in tests with 3 orders?",["3 tasks leave a thread free for subtasks","Tests run on virtual threads","The JIT optimised the join away","Tests mock CompletableFuture"],0,"It hangs only once concurrent outer tasks ≥ pool size.","H"],["What is thread-pool starvation?",["Two pool threads each hold a lock the other needs, forever","Pool threads all block waiting on queued work that can never run","The pool's queue fills up, so new tasks get rejected by policy","Idle pool threads time out and are never recreated again"],1,"Nothing makes progress.","E"],["What does a thread dump typically show in this case?",["Found one Java-level deadlock between two pool threads","All pool threads WAITING in join/get at the same place","A few RUNNABLE threads burning CPU in a tight loop","All pool threads BLOCKED on one synchronized monitor"],1,"No lock cycle is reported.","M"],["Why doesn't simply enlarging the pool fix it?",["Bigger pools trigger more GC, which slows the waiting threads","It only raises the threshold; enough concurrent outer tasks still fill it","The common pool's size is fixed and can't be changed at all","New threads only pick up new tasks, never the queued ones"],1,"Remove the blocking dependency.","M"],["Best way to wait for two async results without blocking a pool thread?",["join() both futures inside thenApply","thenCombine and return the combined future","allOf(…).get() on the calling pool thread","supplyAsync a task that calls get() on each"],1,"Composition.","E"],["What should blocking HTTP calls run on?",["The common ForkJoinPool, via parallel streams","A dedicated bounded I/O executor (or virtual threads)","A single-thread executor so calls stay ordered","An unbounded cached pool so calls never queue"],1,"Separate from CPU work.","M"]]},{"id":"t6-4","no":"6.4","title":"Checkout outage: a long @Transactional drains the connection pool","imp":"must","quiz":[["Why is sending a confirmation email inside <code>@Transactional</code> a correctness problem?",["SMTP clients aren't thread-safe inside a tx","Spring blocks network calls inside transactions","Rendering the email holds a row lock too long","A failed commit can't unsend the email"],3,"Use @TransactionalEventListener(AFTER_COMMIT) or an outbox.","E"],["20 requests/s, each holding a connection for 0.5 s. Connections in use on average?",["20","10","40","0.5"],1,"Little's law: L = λ × W = 20 × 0.5 = 10.","M"],["Hikari shows active = max and many pending threads, but DB CPU is 8%. Most likely cause?",["The database instance is too small","Missing indexes on the hot tables","Connections held while waiting on HTTP","Long GC pauses in the application"],2,"Low DB load with an exhausted pool means connections are held, not used.","H"],["When does @Transactional borrow a DB connection?",["At application start, one per bean, held for the bean's life","At the first database access in the transaction, held until commit","Per SQL statement, returned to the pool after each one","At commit time only, when the changes are flushed to the DB"],1,"Then it's held through everything inside.","E"],["Why is an HTTP call inside a transaction dangerous?",["HTTP clients roll back the transaction when a response is slow","The connection is held idle while waiting; slow calls drain the pool","The HTTP call joins the transaction and can't be retried later","JSON parsing inside a transaction disables Hibernate's flush"],1,"Move remote calls outside.","E"],["Hikari error \"Connection is not available, request timed out\" usually means?",["The SQL is invalid and the driver rejected the statement","The pool is empty: connections are held too long or leaked","The query hit a deadlock and the database aborted it","The JDBC driver version doesn't match the database server"],1,"Check usage time metrics.","M"],["Why does a slow checkout affect health checks?",["Health checks share the checkout's Tomcat thread and wait on it","Health checks need connections from the same exhausted pool","Kubernetes slows probes down whenever CPU usage is high","Actuator pauses health checks while a transaction is open"],1,"Blast radius of one slow dependency.","M"],["Where should the confirmation email be sent?",["Inside the transaction","After commit (AFTER_COMMIT listener or outbox)","Before saving","In the controller before the service"],1,"Only for committed orders.","E"]]},{"id":"t6-5","no":"6.5","title":"Cache stampede on a hot key","imp":"good","quiz":[["A key gets 2,000 requests/s and takes 250 ms to reload. Without coalescing, roughly how many requests miss during the reload?",["500","1","2,000","8"],0,"2,000/s × 0.25 s = 500 concurrent misses.","E"],["Why add random jitter to cache TTLs?",["Redis needs it to spread memory evenly","It hides key lifetimes from attackers","It reduces memory use over time","Keys loaded together won't expire together"],3,"Synchronised expiry causes stampedes after deploys and warm-ups.","M"],["Why does the single-flight code store a <code>CompletableFuture</code> instead of <code>computeIfAbsent(id, k -> db.load(k))</code>?",["computeIfAbsent isn't atomic per key","computeIfAbsent loads under the bin lock","A future is faster than the database","Futures use less memory than values"],1,"ConcurrentHashMap's compute functions must be short.","H"],["What triggers a cache stampede?",["The cache reaching its maximum size and evicting","A popular key expiring while many requests arrive","Too many distinct keys being written at once","A slow network between the app and the cache"],1,"All of them miss together.","E"],["What does \"single-flight\" mean?",["Each pod runs only one request per second for each key","For each key, only one request loads it; others wait for that result","Only one thread per pod may read the cache at a time","Each key is stored in exactly one cache across all services"],1,"Coalescing.","E"],["Caffeine's <code>cache.get(key, loader)</code> under concurrent misses?",["Calls the loader once per caller, then keeps the last","Calls the loader once per key; other callers wait","Throws, since concurrent misses must be handled by you","Returns null to the others until the first load ends"],1,"Built-in coalescing within a JVM.","M"],["What is negative caching?",["Caching error responses permanently so failures stay consistent","Briefly caching \"not found\" so missing keys don't hit the DB every time","Evicting entries early when the DB reports a newer version","Storing deltas instead of whole values to save cache memory"],1,"Defends against cache penetration.","M"],["Why does a stampede get worse over time once it starts?",["The cache grows with each miss until it evicts the hot key again","The DB slows down, so the reload takes longer and more requests miss meanwhile","GC pauses from failed lookups block the cache's eviction thread","Each miss resets the TTL, so the key keeps expiring sooner"],1,"A feedback loop.","M"]]},{"id":"t6-6","no":"6.6","title":"Shared SimpleDateFormat: wrong data, no errors","imp":"good","quiz":[["Which is safe to keep in a <code>static final</code> field and use from many threads?",["new SimpleDateFormat(\"yyyy-MM-dd\")","new StringBuilder()","DateTimeFormatter.ofPattern(\"yyyy-MM-dd\")","new DecimalFormat(\"#.00\")"],2,"java.time formatters are immutable. SimpleDateFormat and DecimalFormat keep parse/format state in fields.","E"],["Why is sharing one SimpleDateFormat across threads unsafe?",["Its methods keep state in shared fields (a Calendar)","Only format() is unsafe; parse() is fine","It holds a lock that serialises all callers","It caches and returns the last parsed date"],0,"Both parse and format use the shared Calendar and number format.","M"],["Every unit test of the parser passes. Why didn't they catch it?",["The bug is in the JDK, so tests can't see it","Tests run with a different default locale","Tests mock every date they use","They're single-threaded; it needs interleaving"],3,"Concurrency bugs are timing-dependent; they need concurrent tests or code review.","H"],["Why are Spring singleton beans' fields risky?",["They're recreated per request, so field values get lost","All request threads share them, so mutable fields can race","Their fields live on each thread's stack and aren't shared","Spring makes their fields final, so they can't be updated"],1,"Keep beans stateless.","E"],["Is <code>java.time.DateTimeFormatter</code> thread-safe?",["No","Yes: it's immutable","Only with ThreadLocal","Only in Java 21"],1,"Share one instance.","E"],["Is <code>StringBuilder</code> thread-safe?",["Yes (its append is synchronized)","No (StringBuffer is synchronized)","No (but StringBuffer isn't either)","Yes, since Java 9's compact strings"],1,"Keep StringBuilders local.","M"],["Why do concurrency bugs like this pass unit tests?",["JUnit runs each test in a lock, which hides races","Tests are single-threaded; the bug only appears under interleaving","The JIT removes races in short-running test methods","Mockito proxies synchronize every call on a mocked bean"],1,"Use stress tests and code review.","E"],["Fix for a shared SimpleDateFormat if you can't switch to java.time?",["Make it a static final field so all threads share it safely","Create one per call, use a ThreadLocal, or synchronize access","Declare it volatile so every thread sees its latest state","Call clone() on it once at startup and share the copy"],1,"DateTimeFormatter is still the best fix.","M"]]},{"id":"t7-1","no":"7.1","title":"Enums with fields and behaviour","imp":"must","quiz":[["How should you compare an enum value to a constant?",["s.equals(\"PAID\")","s.name() == \"PAID\"","s == OrderStatus.PAID","s.ordinal() == \"PAID\".hashCode()"],2,"Each constant is a singleton; == is correct and null-safe.","E"],["JPA entity uses <code>@Enumerated</code> with the default type. You insert a new constant in the middle of the enum. Effect?",["Nothing changes, since enum names are stored","Existing rows now map to different constants","Hibernate fails schema validation at startup","Only newly inserted rows get the shifted values"],1,"The default is ORDINAL; positions shift. Use EnumType.STRING.","M"],["A switch expression over an enum has no default. You add a new constant. What happens?",["The new constant is silently ignored","It throws at run time only","Nothing: switch expressions don't need cases","The switch fails to compile until the case is handled"],3,"Switch expressions must be exhaustive; that's the safety net.","H"],["What does <code>OrderStatus.values()</code> return?",["A Set of all constants in hash order","An array of all constants in declaration order","An immutable List of constants sorted by name","A Map from each constant's name to its ordinal"],1,"A new array each call.","E"],["Can enum constants have their own fields?",["No, enums can only hold their name and ordinal","Yes, set through the enum's constructor","Yes, but only static fields shared by all constants","Only if each field is a compile-time constant"],1,"e.g. PAID(false).","E"],["An enum's constructor is...",["public","implicitly private","protected","static"],1,"You can't call it yourself.","M"],["Why is an enum good for statuses instead of String constants?",["String comparisons are slower and the JIT can't inline them, so enums are always faster","The compiler only allows valid values and switches can be checked for exhaustiveness","Enums are stored more compactly in the database and use less disk than text columns","String constants can't be used as switch labels, so validation logic must use if-chains"],1,"Typos become compile errors.","E"],["<code>OrderStatus.PAID.compareTo(OrderStatus.SHIPPED)</code> compares?",["Names alphabetically","Ordinal positions","Hash codes","It throws"],1,"Declaration order.","M"]]},{"id":"t7-2","no":"7.2","title":"Reflection and annotations","imp":"good","quiz":[["What does an annotation do by itself?",["Nothing: some tool or framework must read it","It changes the method's bytecode","It always runs code before the method","It makes the method public"],0,"Annotations are metadata; behaviour comes from whoever processes them.","E"],["Your custom annotation is never found via <code>getAnnotation</code>. Most likely cause?",["The method isn't public","Its retention isn't RUNTIME","Annotations need an interface","Reflection is disabled by default"],1,"Default retention is CLASS, which isn't visible to reflection.","M"],["A reflectively invoked method throws IllegalStateException. What does <code>Method.invoke</code> throw?",["IllegalStateException directly","ReflectiveOperationException with no cause","InvocationTargetException wrapping it","Nothing: it's swallowed"],2,"Unwrap with getCause().","H"],["What does <code>Foo.class</code> give you?",["A new instance of Foo built with its no-arg constructor","The Class object describing Foo","A dynamic proxy that intercepts calls on Foo","The loaded bytecode of Foo as a byte array"],1,"Entry point for reflection.","E"],["Which retention keeps an annotation available at run time?",["SOURCE","CLASS","RUNTIME","DEFAULT"],2,"Needed for reflection-based frameworks.","E"],["<code>@Override</code> has which retention?",["RUNTIME","SOURCE","CLASS","None"],1,"It's only for the compiler.","M"],["What does <code>getDeclaredFields()</code> return?",["All public fields, including the ones inherited from superclasses","All fields declared in this class, including private (not inherited)","All fields from this class and its superclasses, including private ones","Only the static fields declared in this class, including private ones"],1,"getFields() returns public ones, including inherited.","M"],["Why is reflection slower than direct calls?",["Every reflective call is executed on a separate internal thread","Extra checks, boxing of arguments and harder JIT optimisation","The class file is re-parsed from disk on each invocation","Reflection always bypasses the JIT and runs in interpreted mode"],1,"Fine at startup, avoid in hot paths.","M"]]},{"id":"t7-3","no":"7.3","title":"Collectors in depth: grouping, partitioning, toMap","imp":"must","quiz":[["<code>toMap(Order::customer, Order::amount)</code> and two orders share a customer. Result?",["The later value silently replaces the earlier one","The amounts are summed under that customer's key","IllegalStateException: Duplicate key","A Map whose value is a List of both amounts"],2,"Pass a merge function as the third argument.","E"],["What does <code>partitioningBy(Order::paid)</code> return when every order is paid?",["A map with only the true key, since no order was unpaid","A map with true → all orders and false → empty list","A Map of true and false to the number of matching orders","A List of two lists: paid orders first, then unpaid ones"],1,"partitioningBy always contains both keys.","M"],["You need total amount per city, with cities in alphabetical order. Which?",["groupingBy(Order::city, TreeMap::new, summingLong(Order::amount))","groupingBy(Order::city, summingLong(Order::amount))","toMap(Order::city, Order::amount)","partitioningBy(Order::city)"],0,"The map factory chooses TreeMap; the downstream sums.","H"],["<code>Collectors.groupingBy(Order::city)</code> produces?",["List&lt;Order&gt;","Map&lt;String, List&lt;Order&gt;&gt;","Set&lt;String&gt;","Map&lt;String, Order&gt;"],1,"Values are lists by default.","E"],["Count orders per city?",["groupingBy(Order::city)","groupingBy(Order::city, counting())","toMap(Order::city, 1)","partitioningBy(Order::city)"],1,"Downstream counting.","E"],["<code>joining(\", \")</code> on [a, b, c]?",["abc","a, b, c","[a, b, c]","a,b,c,"],1,"Separator between elements.","E"],["Names of customers per city?",["groupingBy(Order::city, mapping(Order::customer, toList()))","groupingBy(Order::customer, mapping(Order::city, toList()))","toMap(Order::city, Order::customer)","groupingBy(Order::city, counting())"],0,"mapping transforms before collecting.","M"],["Which collector keeps the first value on duplicate keys?",["toMap(k, v)","toMap(k, v, (a, b) -&gt; a)","toMap(k, v, (a, b) -&gt; b)","groupingBy(k)"],1,"The merge function decides.","M"]]},{"id":"t7-4","no":"7.4","title":"Date and time with java.time","imp":"good","quiz":[["Which type should a server use to record when an order was created?",["LocalDateTime","LocalDate","String","Instant"],3,"Instant is an exact moment, independent of time zones.","E"],["<code>LocalDate.of(2026, 1, 31).plusMonths(1)</code>?",["2026-03-03","2026-02-28","2026-02-31","DateTimeException"],1,"java.time clamps to the last valid day of the month.","M"],["In Berlin, clocks jump from 02:00 to 03:00 on 29 March 2026. <code>LocalDateTime 02:30</code>.atZone(Berlin) gives?",["03:30, shifted forward by the gap","02:30 exactly, with a +02:00 offset","01:30, shifted back before the gap","DateTimeException, since 02:30 doesn't exist"],0,"Times in a DST gap are moved forward by the gap's length.","H"],["Which type represents a birthday?",["Instant","LocalDate","ZonedDateTime","Duration"],1,"A calendar date without time or zone.","E"],["Are java.time objects mutable?",["Yes, setters like setDayOfMonth change them in place","No: methods return new instances","Only LocalDate is immutable; the other types are mutable","Only Instant is immutable, because it has no time zone"],1,"Thread-safe as a result.","E"],["Exact elapsed time between two Instants?",["Period.between","Duration.between","ChronoUnit.YEARS","LocalDate.until"],1,"Period is for calendar amounts.","E"],["Parse \"2026-03-31\" into a date?",["new Date(\"2026-03-31\")","LocalDate.parse(\"2026-03-31\")","Instant.parse(\"2026-03-31\")","Integer.parseInt"],1,"ISO format by default.","M"],["Why store timestamps in UTC?",["UTC values take less space in the database than zoned values","A single unambiguous timeline; convert to local zones only for display","The JVM requires UTC to sort timestamps correctly across hosts","UTC removes the need to convert anything when showing times to users"],1,"Avoids DST and region confusion.","M"]]},{"id":"t7-5","no":"7.5","title":"I/O, NIO files and serialization","imp":"good","quiz":[["Best way to count lines matching a pattern in a 5 GB log file?",["Files.readAllLines, then stream and filter the list","Files.readString, then split on newlines and filter","Files.lines inside try-with-resources, then filter and count","Read it into a StringBuilder, then use a Matcher on it"],2,"Lazy streaming keeps memory flat; the stream must be closed.","E"],["A field is marked <code>transient</code> in a Serializable class. After deserialization it is?",["Its default value (null / 0)","Its original value","An exception is thrown","Encrypted"],0,"Transient fields aren't written.","M"],["Why is <code>ObjectInputStream.readObject</code> on untrusted input dangerous?",["It loads the whole stream into memory before checking types","It ignores serialVersionUID, so mismatched classes load silently","It skips constructors, so final fields are always left null","Crafted byte streams can trigger code in classes on the classpath (gadget chains)"],3,"Deserialization vulnerabilities have led to remote code execution; prefer JSON with explicit types.","H"],["Read a small text file in one line?",["new File(path).readText()","Files.readString(Path.of(path))","Paths.get(path).readString()","Files.readAllBytes(path).toString()"],1,"Java 11+.","E"],["What's the difference between InputStream and Reader?",["InputStream is buffered while Reader reads one byte at a time","InputStream reads bytes; Reader reads characters (decoded with a charset)","Reader reads lines only; InputStream reads raw characters (UTF-16)","InputStream is for files only; Reader is for network sockets"],1,"Wrap with InputStreamReader to convert.","E"],["Why use try-with-resources for files?",["It buffers the file so reads become faster","Files get closed even if an exception happens","The compiler rejects file APIs used outside it","It retries automatically if opening the file fails"],1,"Avoids leaking file handles.","E"],["Convert an object to JSON in Spring apps?",["toString()","Jackson's ObjectMapper","Serializable","String.format"],1,"Spring MVC uses it automatically.","E"],["What does <code>serialVersionUID</code> protect against?",["Deserializing objects whose classes aren't on the classpath","Deserializing data written by an incompatible class version","Classes being serialized concurrently from several threads","Malicious byte streams triggering gadget chains on deserialize"],1,"Mismatches throw InvalidClassException.","M"]]},{"id":"t7-6","no":"7.6","title":"What changed from Java 8 to Java 25","imp":"must","quiz":[["Which version introduced lambdas and the Stream API?",["Java 7","Java 8","Java 11","Java 17"],1,"Java 8 (2014).","E"],["Records, sealed classes and switch expressions are all standard by which LTS?",["Java 11","Java 17","Java 21","Java 25"],1,"Switch expressions (14), records (16), sealed classes (17).","M"],["Spring Boot 3 requires at least?",["Java 8","Java 11","Java 21","Java 17"],3,"Boot 3 is built on Spring 6, which needs Java 17 and the jakarta.* namespace.","M"],["Which version added <code>var</code> for local variables?",["8","10","14","17"],1,"Local variable type inference.","E"],["Which LTS is the minimum for Spring Boot 3?",["8","11","17","21"],2,"And jakarta.* packages.","E"],["Text blocks (\"\"\") became standard in?",["11","15","17","21"],1,"Multi-line strings.","M"],["Records became standard in?",["14","16","17","21"],1,"Previewed in 14 and 15.","M"],["Virtual threads became standard in?",["17","19","21","25"],2,"JEP 444.","E"]]},{"id":"t8-1","no":"8.1","title":"Transactions and isolation levels","imp":"must","quiz":[["What is a dirty read?",["Reading a row that another transaction deleted and committed","Reading another transaction's uncommitted change","Reading the same row twice and getting different values","Reading a row while it's being indexed"],1,"Only READ UNCOMMITTED allows it.","E"],["Under READ COMMITTED, T1 reads a balance, T2 updates and commits it, T1 reads again. T1's second read?",["The old value: READ COMMITTED keeps a snapshot","An error","It blocks until T1 commits","The new value: a non-repeatable read"],3,"Each statement sees the latest committed data.","M"],["What is PostgreSQL's default isolation level?",["READ COMMITTED","REPEATABLE READ","SERIALIZABLE","READ UNCOMMITTED"],0,"MySQL InnoDB defaults to REPEATABLE READ.","H"],["What does atomicity guarantee?",["Concurrent transactions never see each other's changes","All statements in a transaction take effect, or none do","Committed changes survive a crash or power loss","Each statement is applied the moment it executes"],1,"The A in ACID.","E"],["Which level prevents dirty reads but allows non-repeatable reads?",["READ UNCOMMITTED","READ COMMITTED","REPEATABLE READ","SERIALIZABLE"],1,"The most common default.","E"],["What is a phantom read?",["A row disappearing after another transaction deletes it","New rows appearing when a range query is repeated","Reading data another transaction hasn't committed yet","A row's value changing when the same row is re-read"],1,"Prevented by SERIALIZABLE.","M"],["MySQL InnoDB's default isolation level?",["READ COMMITTED","REPEATABLE READ","SERIALIZABLE","READ UNCOMMITTED"],1,"PostgreSQL defaults to READ COMMITTED.","M"],["Set isolation for one Spring method?",["@Transactional(propagation = Propagation.REQUIRES_NEW)","@Transactional(isolation = Isolation.REPEATABLE_READ)","spring.jpa.properties.isolation in application.yml","@Lock(LockModeType.PESSIMISTIC_READ) on the method"],1,"Per transaction.","M"]]},{"id":"t8-2","no":"8.2","title":"Indexes and query plans","imp":"must","quiz":[["Without an index, how does the DB answer <code>WHERE customer_id = 42</code> on a big table?",["It uses the primary key automatically","It reads every row (full table scan)","It samples a few rows","It caches the answer forever"],1,"Seq Scan: cost grows with table size.","E"],["Index on (customer_id, created_at). Which query can't use it well?",["WHERE customer_id = 42","WHERE customer_id = 42 ORDER BY created_at","WHERE created_at &gt; yesterday","WHERE customer_id = 42 AND created_at &gt; yesterday"],2,"Leftmost-prefix rule: the leading column isn't constrained.","M"],["An index exists on status, but <code>WHERE lower(status) = 'paid'</code> does a full scan. Fix?",["Add an expression index on lower(status), or store normalised values","Increase work_mem so the sort for lower() fits in memory","Add LIMIT 1 so the planner stops after the first match","Run ANALYZE so the planner picks up the status index"],0,"Functions on the column hide it from a plain index.","H"],["What's the most common index structure in relational databases?",["Hash table","B-tree","Linked list","Bitmap"],1,"Supports equality and range queries.","E"],["Does a primary key create an index?",["No","Yes, automatically","Only in MySQL","Only if named"],1,"Unique constraints too.","E"],["Why does every extra index slow down inserts?",["Each insert must rebuild the index from scratch","Each insert must also update every index","Each index takes a table-level lock on insert","Each insert is replayed once per index in the WAL"],1,"Write cost vs read benefit.","E"],["<code>WHERE name LIKE 'abc%'</code> vs <code>LIKE '%abc'</code>: which can use a B-tree index on name?",["Both","Only 'abc%' (prefix)","Only '%abc'","Neither"],1,"A leading wildcard can't use the sort order.","M"],["What does EXPLAIN (without ANALYZE) show?",["The actual run time of each plan node","The planned execution strategy and estimated costs","The rows the query would return, unsorted","The locks each step would take at runtime"],1,"ANALYZE runs it and shows actual numbers.","M"]]},{"id":"t8-3","no":"8.3","title":"JDBC, PreparedStatement and connection pooling","imp":"good","quiz":[["What does <code>close()</code> on a connection from HikariCP do?",["Closes the TCP connection to the database","Nothing","Returns it to the pool","Commits the transaction"],2,"The pool wraps connections; close hands it back for reuse.","E"],["Why use PreparedStatement parameters instead of string concatenation?",["They avoid round trips by batching all queries into one call","They prevent SQL injection and let the DB reuse the parsed statement","They escape results automatically and return them faster","They're required for JPA and Spring to manage the transaction"],1,"Values are sent as data, never parsed as SQL.","M"],["Requests start failing with \"Connection is not available, request timed out after 30000ms\" while the DB is idle. Likely cause?",["The database is down, so new connections can't be opened","Too many indexes slow every query past the 30 second limit","Long GC pauses stop the pool's housekeeping thread","Connections are leaked or held too long, so the pool is empty"],3,"Enable leak detection; check for unclosed connections or long transactions (6.4).","H"],["What does a JDBC driver do?",["Pools and reuses connections for the app","Implements JDBC for a specific database","Translates JPQL into native SQL queries","Compiles SQL strings into Java bytecode"],1,"e.g. the PostgreSQL driver.","E"],["Which object runs parameterised SQL?",["Statement","PreparedStatement","ResultSet","DriverManager"],1,"With ? placeholders.","E"],["How do you read the next row of a ResultSet?",["rs.get()","rs.next()","rs.read()","rs.row()"],1,"Returns false when there are no more rows.","E"],["Default pool in Spring Boot?",["Tomcat JDBC","HikariCP","C3P0","DBCP 1"],1,"Fast and well tuned.","M"],["What does <code>con.setAutoCommit(false)</code> start?",["A new physical connection reserved for writes","A manual transaction: you must commit or roll back","Read-only mode until you call setAutoCommit(true)","Statement batching: queries run on executeBatch()"],1,"What @Transactional does for you.","M"]]},{"id":"t8-4","no":"8.4","title":"Kafka fundamentals: topics, partitions, consumer groups","imp":"must","quiz":[["Kafka guarantees message order...",["Across the whole topic","Within a partition only","Across all topics","Never"],1,"Use a key so related events go to the same partition.","E"],["A topic has 4 partitions; a group has 6 consumers. How many are actively consuming?",["6","4; 2 sit idle","3","1"],1,"Each partition goes to one consumer in a group.","M"],["A consumer processes a message, then crashes before committing its offset. What happens?",["The message is lost, since it was already read once","Kafka moves it to the dead-letter topic automatically","It's redelivered after the rebalance, so processing must be idempotent","The whole partition is replayed from offset 0 on restart"],2,"At-least-once delivery.","H"],["What is a Kafka topic?",["A table-like store of current values, keyed by id","A named stream of events, split into partitions","A queue owned by one consumer group, split into shards","A broker process that hosts a set of partition replicas"],1,"Producers write, consumers read.","E"],["What is an offset?",["The timestamp at which the broker stored a message","The position of a message within a partition","The id of the partition a message was written to","A global sequence number across the whole topic"],1,"Consumers commit offsets to track progress.","E"],["Two different consumer groups subscribe to the same topic. Each gets?",["Each gets a share of the messages, split across groups","All the messages, independently","Only the group that subscribed first gets the messages","All the messages, but only after the other group commits"],1,"Groups don't share progress.","E"],["Are Kafka messages deleted once consumed?",["Yes, once every consumer group commits its offset","No: they're kept for the retention period","Only after the consumer acknowledges them","Yes, once all in-sync replicas have read them"],1,"Enables replay.","M"],["What does a message key influence?",["Which broker replica handles the consumer's reads","Which partition the message goes to (and so its ordering)","How long the message is kept before it's deleted","Which consumer group the message is delivered to"],1,"Same key → same partition.","M"]]},{"id":"t9-1","no":"9.1","title":"Unit testing with JUnit 5 and Mockito","imp":"must","quiz":[["What does <code>mock(TaxClient.class)</code> return by default for a method returning an object?",["A real TaxClient","null (or an empty value for collections/Optional)","It throws UnsupportedOperationException","The last value returned"],1,"Unstubbed methods return defaults.","E"],["Which should you usually NOT mock in a unit test?",["A remote HTTP client calling a payment API","A repository that talks to the database","A message publisher sending to a broker","Value objects like Money or a record DTO"],3,"Use real value objects; mock collaborators with side effects or slowness.","M"],["<code>assertEquals(new BigDecimal(\"119\"), result)</code> fails though result is 119.00. Why?",["BigDecimal.equals compares scale, and 119 has scale 0","assertEquals can't compare BigDecimals","Rounding error","The mock returned null"],0,"Use compareTo or AssertJ's isEqualByComparingTo.","H"],["What does <code>assertEquals(expected, actual)</code> do when they differ?",["Logs a warning and lets the test continue","Fails the test with both values in the message","Fails the test, but shows only the expected value","Throws a RuntimeException that stops the suite"],1,"Order matters for readable messages.","E"],["What does <code>when(mock.find(1)).thenReturn(car)</code> do?",["Calls the real find(1) and records the result","Stubs the mock to return car for find(1)","Verifies that find(1) was called exactly once","Stubs find() to return car for any argument"],1,"Arrange step.","E"],["Which JUnit 5 annotation runs before each test?",["@Before","@BeforeEach","@BeforeAll","@Setup"],1,"@BeforeAll runs once per class.","E"],["How do you assert an exception in JUnit 5?",["@Test(expected = Type.class) on the method","assertThrows(Type.class, () -> …)","assertException(Type.class, () -&gt; …)","@ExpectedException(Type.class) on the class"],1,"@Test(expected) was JUnit 4.","M"],["<code>verify(repo, never()).save(any())</code> checks?",["save was called once","save was never called","save threw","Nothing"],1,"Useful for \"no side effect on invalid input\".","M"]]},{"id":"t9-2","no":"9.2","title":"JVM troubleshooting toolkit","imp":"good","quiz":[["An app is hung but CPU is idle. First evidence to collect?",["A heap dump to find leaked objects","GC logs covering the last few minutes","Several thread dumps a few seconds apart","A JFR recording of CPU hot methods"],2,"Dumps show what each thread is waiting on, and comparing them shows what's stuck.","E"],["top -H shows thread id 4311 at 98% CPU. How do you find it in a thread dump?",["Search for \"4311\" in the thread names","Convert 4311 to hex (0x10d7) and find nid=0x10d7","It's always the main thread","Take a heap dump instead"],1,"Thread dumps list native thread ids in hex.","M"],["Which is safe to run continuously in production with ~1–2% overhead?",["Java Flight Recorder","A heap dump every minute","-verbose:class","A debugger attached to the JVM"],0,"JFR was designed for always-on production use.","H"],["Which command lists running JVMs?",["java -list or java --running","jcmd (with no arguments) or jps","javap with no arguments","jstat -list or jmap -list"],1,"Then target a pid.","E"],["What does a thread dump contain?",["Every live object and its size","Each thread's state and stack trace","The GC log since the JVM started","Each thread's CPU time and heap usage"],1,"Plus locks held and waited for.","E"],["Which file format does Java Flight Recorder produce?",[".hprof",".jfr",".log",".class"],1,"Open with JDK Mission Control.","E"],["Why take several thread dumps instead of one?",["Each dump only shows a random subset of the threads","To tell stuck threads (same frame every time) from busy ones","Tools like fastThread need at least three to parse","A single dump pauses threads and hides their real state"],1,"A few seconds apart.","M"],["What's the first thing to check for \"OutOfMemoryError: Metaspace\"?",["Heap size: Metaspace is carved out of -Xmx","Class loading: generated classes or class loader leaks","Thread count: each thread stack uses Metaspace","String interning filling the Metaspace pool"],1,"See 1.3 and 1.2.","M"]]},{"id":"t9-3","no":"9.3","title":"Maven and Gradle: dependencies and conflicts","imp":"good","quiz":[["What is a transitive dependency?",["A dependency only used in tests","A dependency you declared twice","A dependency of one of your dependencies","A dependency loaded at run time by reflection"],2,"They come along automatically; inspect them with dependency:tree.","E"],["Two libraries need json-lite 1.2 and 2.0 at the same depth. Which does Maven pick?",["The highest version, 2.0","The one declared first in the pom","The lowest version, 1.2","The build fails with a conflict"],1,"Maven: nearest wins, ties go to the first declaration. Gradle picks the highest.","M"],["The build succeeds, but production throws NoSuchMethodError inside a library. Most likely?",["A dependency version conflict put an older JAR on the classpath","The JIT inlined and removed the method at run time","A compiler warning about the method was ignored","The library was compiled for a newer Java release"],0,"Check dependency:tree and pin the version.","H"],["What identifies a Maven dependency?",["The JAR file name and its checksum","groupId, artifactId and version","The repository URL and its path","groupId, artifactId and packaging"],1,"Coordinates.","E"],["Which scope keeps JUnit out of the production JAR?",["compile","test","runtime","provided"],1,"Test-only dependencies.","E"],["Command to see the full dependency tree in Maven?",["mvn tree","mvn dependency:tree","mvn deps","mvn list"],1,"Gradle: gradle dependencies.","E"],["What does <code>mvn package</code> run?",["Only compile and package, skipping the tests","Compile, test, then package (earlier phases included)","Compile, test, package, then install locally","Only the package phase, using existing classes"],1,"The lifecycle runs phases in order.","M"],["Gradle's default conflict resolution picks?",["The nearest","The highest version","The first declared","The oldest"],1,"Maven picks the nearest.","M"]]},{"id":"t9-4","no":"9.4","title":"Logging, metrics and tracing","imp":"good","quiz":[["Why write <code>log.info(\"Order {} placed\", id)</code> instead of <code>\"Order \" + id + \" placed\"</code>?",["SLF4J rejects string concatenation at compile time","Placeholders make the call thread-safe without locks","The id is masked in the output if it's sensitive","The message is only formatted if INFO is enabled"],3,"Placeholders avoid building strings for disabled levels.","E"],["What's wrong with tagging a metric by userId?",["Tag values must be numeric, so ids are rejected","Unbounded cardinality creates millions of time series","Micrometer drops tags with more than 32 values","User ids leak into traces and break sampling"],1,"Keep tag values to a small, bounded set.","M"],["How does one request's trace id reach the next service?",["Through a shared database table","In the JWT payload","It's propagated in request headers (e.g. traceparent)","Through MDC, which is shared between services"],2,"MDC is per thread, per process; headers carry context across the network.","H"],["Which log level is typical in production?",["TRACE","DEBUG","INFO","OFF"],2,"DEBUG temporarily, when investigating.","E"],["Which library is the logging facade most Java code uses?",["Log4j 1","SLF4J","System.out","JUL only"],1,"Logback or Log4j2 implement it.","E"],["Which metric type measures request durations and percentiles?",["Counter","Timer","Gauge","Tag"],1,"Counters only count.","M"],["What is a trace id?",["The id of the thread that handled the request","An id shared by all spans of one request across services","An id unique to each span within a service","An id the client sends to dedupe retries"],1,"Propagated in headers.","E"],["Why is structured (JSON) logging useful?",["Log files are much smaller than plain text","Fields are searchable and filterable in log tools","Writes are faster since nothing is formatted","SLF4J needs JSON to attach MDC values"],1,"e.g. filter by orderId.","M"]]},{"id":"t9-5","no":"9.5","title":"Java modules (JPMS)","imp":"extra","quiz":[["In module-info.java, what does <code>exports com.shop.api</code> do?",["Makes that package accessible to other modules","Opens that package for deep reflection only","Declares a dependency on that package's module","Makes the package readable by the unnamed module only"],0,"Only exported packages are part of the module's public API.","E"],["A public class sits in a package that isn't exported. Can another module use it?",["Yes, it's public","Only via reflection, always","No: it's encapsulated","Only in the same JAR"],2,"Strong encapsulation: public isn't enough across modules.","M"],["Jackson throws InaccessibleObjectException on a modular app's DTO. Fix?",["Make the DTO fields public static so Jackson can see them","Open the package to Jackson in module-info (opens … to com.fasterxml.jackson.databind)","Add requires transitive com.fasterxml.jackson.databind to module-info","Run with --add-modules ALL-SYSTEM so Jackson sees the module"],1,"Deep reflection needs opens, not just exports.","H"],["What file declares a Java module?",["module.xml","module-info.java","pom.xml","MANIFEST.MF"],1,"At the source root.","E"],["Which keyword declares a dependency on another module?",["imports","requires","uses","needs"],1,"requires java.sql;","E"],["Which module is always available without requires?",["java.sql","java.base","java.desktop","java.logging"],1,"Contains java.lang, java.util…","M"],["What does <code>exports</code> NOT allow by itself?",["Using the package's public types","Deep reflection into private members","Compiling against the package","Calling its public static methods"],1,"That needs opens.","M"],["Since which version are JDK internals strongly encapsulated by default?",["9","11","16/17","21"],2,"JEP 396 (16) then 403 (17).","M"]]},{"id":"t10-1","no":"10.1","title":"Reactive streams with Project Reactor","imp":"extra","quiz":[["You build a Flux pipeline but never call subscribe. What happens?",["It runs once eagerly when the Flux is assembled","Nothing: reactive pipelines are lazy","It runs on a background scheduler by default","An IllegalStateException is thrown at assembly"],1,"Like streams, nothing happens until there's a subscriber.","E"],["How many terminal signals can a Flux emit?",["At most one: onComplete or onError","One onComplete per item","Any number of onError","Both onComplete and onError"],0,"onNext* then a single terminal signal (or none if infinite/cancelled).","M"],["What is backpressure?",["The publisher retrying failed items with growing delays","The server compressing large responses to save bandwidth","The subscriber limiting how many items the publisher may send","The scheduler throttling threads when CPU usage is high"],2,"Via request(n) in the Reactive Streams protocol.","H"],["Mono emits how many values at most?",["Many","One","Zero always","Two"],1,"Flux emits many.","E"],["What starts a Reactor pipeline?",["Creating it","Subscribing to it","Calling map","Logging it"],1,"Lazy until subscribe.","E"],["What does <code>block()</code> do on a Mono?",["Subscribes asynchronously and returns the Mono itself","Waits for and returns the value, blocking the current thread","Cancels the Mono if it hasn't emitted within a timeout","Waits for the value, but only on the event loop thread"],1,"Avoid it on event-loop threads.","M"],["Combine two Monos' results when both complete?",["flatMap","zip / zipWith","take","filter"],1,"Runs them concurrently.","M"],["Recover from an error with another publisher?",["onErrorResume","map","doOnNext","subscribe"],0,"onErrorReturn for a plain value.","M"]]},{"id":"t10-2","no":"10.2","title":"WebFlux vs virtual threads","imp":"good","quiz":[["How many event-loop threads does WebFlux typically use?",["One per request","200, like Tomcat","Unlimited","About one per CPU core"],3,"Few threads, never blocking.","E"],["A WebFlux handler calls blocking JDBC directly. Effect?",["It blocks an event-loop thread, stalling every request on it","WebFlux detects it and offloads it to another thread pool","The app fails at startup when JDBC is on the classpath","Nothing: R2DBC wraps the JDBC driver as non-blocking"],0,"Wrap with subscribeOn(boundedElastic) or use R2DBC.","M"],["For a typical new CRUD service on Java 21, the simplest scalable choice is usually?",["WebFlux with R2DBC everywhere","Bigger Tomcat thread pool (2,000 threads)","Spring MVC with virtual threads enabled","A single-threaded server"],2,"Plain blocking code that scales for I/O-bound work.","H"],["What is an event loop?",["A loop that polls the database for new rows","A thread that handles many connections' events without blocking","A thread pool that gives each connection a thread","A GC phase that reclaims short-lived objects"],1,"Netty powers WebFlux.","E"],["Non-blocking database access for WebFlux?",["JDBC","R2DBC","JPA","JdbcTemplate"],1,"JDBC is blocking.","E"],["Which Spring property enables virtual threads in MVC?",["spring.mvc.virtual-threads=true","spring.threads.virtual.enabled=true","server.tomcat.threads.virtual=on","spring.task.execution.virtual=true"],1,"Java 21+, Boot 3.2+.","M"],["Who benefits from virtual threads most?",["CPU-heavy number crunching","I/O-heavy request handling","GC tuning","Startup time"],1,"Waiting is cheap.","E"],["Detect blocking calls in reactive code during tests?",["jstack","BlockHound","JFR only","EXPLAIN"],1,"Fails tests that block event loops.","M"]]},{"id":"t11-1","no":"11.1","title":"Big-O and the cost of Java collection operations","imp":"must","quiz":[["Two nested loops over the same array of n elements. Time complexity?",["O(n)","O(n²)","O(log n)","O(2n)"],1,"Each of n iterations runs up to n inner iterations.","E"],["What does replacing a nested-loop duplicate check with a HashSet cost?",["Nothing: it's strictly better","O(n) extra memory","O(n²) memory","It only works on sorted data"],1,"Time drops to O(n); space rises to O(n).","M"],["<code>for (x : list) if (otherList.contains(x)) …</code> with both lists of size n. Complexity, and fix?",["O(n): contains is O(1)","O(n log n): contains uses binary search","O(n²); put otherList into a HashSet first","O(1)"],2,"List.contains scans the list.","H"],["What's the time complexity of accessing <code>array[i]</code>?",["O(n)","O(1)","O(log n)","O(n²)"],1,"Direct address calculation.","E"],["Binary search on n sorted items is?",["O(n)","O(log n)","O(1)","O(n log n)"],1,"Halving each step.","E"],["Sorting n items with a comparison sort is at best?",["O(n)","O(n log n)","O(log n)","O(n²)"],1,"Merge/TimSort.","E"],["What's the space complexity of a HashSet holding n items?",["O(1)","O(n)","O(log n)","O(n²)"],1,"Memory grows with the input.","E"],["Two separate (not nested) loops over n items?",["O(n²)","O(n)","O(2ⁿ)","O(log n)"],1,"O(n) + O(n) = O(n).","M"]]},{"id":"t11-2","no":"11.2","title":"Two pointers and sliding window","imp":"must","quiz":[["Two pointers to find a pair with a given sum works directly on which input?",["Any array","Linked lists only","Arrays with no duplicates","Sorted arrays"],3,"Order tells you which pointer to move.","E"],["Sorted array, sum of a[left] + a[right] is too small. Which pointer moves?",["left moves right","right moves left","both move","restart"],0,"Only a bigger left value can increase the sum.","M"],["Why is the sliding window solution for \"longest substring without repeats\" O(n)?",["A HashMap makes each repeat check O(1), so the scan is O(n)","The alphabet is bounded, so the window never exceeds 26 chars","Each index is added once and removed at most once; start never moves back","It stops as soon as the window covers every distinct character"],2,"Both pointers only move forward.","H"],["Reverse an array in place with two pointers: where do they start?",["Both at index 0, one moving twice as fast","One at each end, swapping and moving inward","Both at the middle, moving outward and swapping","One at the start, one at the middle, both moving right"],1,"O(n) time, O(1) space.","E"],["Check if a string is a palindrome efficiently?",["Reverse it with a StringBuilder and compare with equals","Two pointers from both ends comparing characters","Push half onto a stack, then pop while scanning the rest","Compare the hashCode of the string and of its reverse"],1,"O(1) extra space.","E"],["Fixed-size window sum: when moving the window by one, you?",["Recompute the sum of the window from scratch","Add the new element and subtract the one leaving","Add the new element and subtract the window's minimum","Replace the oldest element and re-sort the window"],1,"O(1) per move.","E"],["Remove duplicates from a sorted array in place?",["Nested loops: shift the rest left on each duplicate","Slow/fast pointers: copy each new value forward","Copy everything into a HashSet, then back to the array","Two pointers from both ends, swapping duplicates out"],1,"O(n), O(1) space.","M"],["Merge two sorted arrays?",["Concatenate them, then sort the result: O((n + m) log(n + m))","Two pointers taking the smaller head each time: O(n + m)","Binary search each element of one into the other: O(n log m)","Insert both into a TreeSet and copy them back out in order"],1,"Merge step of merge sort.","M"]]},{"id":"t11-3","no":"11.3","title":"Hashing patterns: two-sum, counting, grouping","imp":"must","quiz":[["In one-pass two-sum, what do you store in the map?",["Each value → its index","Each pair of values","The running sum","Only the target"],0,"Then look up target − a[i] in O(1).","E"],["Best way to count word frequencies in a HashMap?",["map.put(w, map.get(w) + 1)","map.putIfAbsent(w, 1)","map.replace(w, 1)","map.merge(w, 1, Integer::sum)"],3,"get + 1 throws NPE for new words; merge handles both cases.","M"],["Grouping anagrams: why sort each word's letters?",["To make the final output come out in alphabetical order","Anagrams share the same sorted letters, giving a common key","HashMap keys must be sorted strings for lookups to work","Sorting removes duplicate letters, giving shorter keys"],1,"A canonical key maps equivalent items together.","M"],["Check if two strings are anagrams in O(n)?",["Sort both and compare: sorting is linear for strings","Count letters with a map or int[26] and compare","Compare the sum of the character codes of both","Check each char of one with indexOf in the other"],1,"Sorting is O(n log n).","E"],["First duplicate in an array?",["Sort it, then return the first equal neighbours","Scan with a HashSet; the first failed add is the answer","Nested loops, comparing each item with later ones","Two pointers from both ends moving toward each other"],1,"O(n).","E"],["What does <code>map.getOrDefault(k, 0)</code> return for a missing key?",["null","0","Throws","k"],1,"Handy for counting.","E"],["Most frequent element?",["Sort, then take the middle element","Frequency map, then the max entry","A max-heap of the raw values","A Set, then the largest element"],1,"O(n).","M"],["Longest consecutive sequence (e.g. 100, 4, 200, 1, 3, 2 → 4) in O(n)?",["Sort the numbers, then count the longest run of +1 steps","Put all in a HashSet; start counting only from numbers whose n−1 is absent","Put all in a HashSet; count up from every number in the set","Use a min-heap and pop numbers while each is one larger"],1,"Each number is visited a constant number of times.","H"]]},{"id":"t11-4","no":"11.4","title":"Binary search","imp":"must","quiz":[["About how many comparisons does binary search need for 1,000,000 sorted items?",["1,000,000","1,000","20","500,000"],2,"log₂(1,000,000) ≈ 20.","E"],["Why write <code>mid = lo + (hi - lo) / 2</code>?",["It avoids a division, so it's faster","lo + hi can overflow int for very large arrays","lo + hi rounds the wrong way for odd sums","(lo + hi) / 2 breaks when lo is negative"],1,"The overflow bug lived in the JDK for years.","M"],["\"Minimum ship capacity to deliver all packages in D days\" can use binary search because...",["the packages are already sorted by weight","capacities are integers, so the range is finite","D is small enough to try every split of days","if a capacity works, every larger one works too (monotonic)"],3,"Binary search the answer range with a feasibility check.","H"],["Binary search requires the data to be?",["Unique","Sorted (or monotonic)","Small","In a HashMap"],1,"Otherwise halving is meaningless.","E"],["What's the loop condition in the standard version?",["lo &lt; hi - 1","lo &lt;= hi","lo != hi","true"],1,"With hi = length − 1.","E"],["What does <code>Collections.binarySearch(list, key)</code> need?",["A RandomAccess list, sorted or not","A list sorted in ascending order (by the same comparator)","A list sorted in descending order","A list with no duplicate elements"],1,"Otherwise results are undefined.","E"],["On a LinkedList, is binary search O(log n)?",["Yes, the iterator jumps to the middle in O(1) each step","No: reaching the middle is O(n), so overall it's O(n)","Yes, LinkedList caches node positions after the first pass","No: it falls back to a linear scan, so it's O(n log n)"],1,"Random access matters.","M"],["Find the square root (floor) of n without Math.sqrt?",["Linear scan from n downward until x*x ≤ n","Binary search on the answer: largest x with x*x ≤ n","Newton's method on the smallest x with x*x ≥ n","Binary search for the smallest x with x*x &gt; n, then return it"],1,"O(log n).","M"]]},{"id":"t11-5","no":"11.5","title":"Graphs and trees: BFS and DFS","imp":"must","quiz":[["Which traversal finds the fewest hops between two nodes in an unweighted graph?",["DFS","BFS","In-order traversal","Binary search"],1,"BFS reaches nodes in order of distance.","E"],["What data structure drives BFS?",["A queue (FIFO)","A stack (LIFO)","A priority queue","A TreeMap"],0,"DFS uses a stack or recursion; Dijkstra a priority queue.","M"],["DFS on a graph with cycles, without a visited set?",["It's slower but finishes","It finds shortest paths","It can loop forever","It throws ConcurrentModificationException"],2,"Mark nodes visited when you first reach them.","H"],["BFS uses which structure?",["Stack","Queue","Heap","Hash table only"],1,"FIFO gives level order.","E"],["DFS is naturally written with?",["A queue (FIFO)","Recursion (or an explicit stack)","A priority queue","A sorted list"],1,"Go deep, backtrack.","E"],["Why keep a visited set?",["To record the order nodes are visited in for output","To avoid processing nodes twice and looping forever on cycles","To make neighbour lookups O(1) instead of O(n)","To free memory by dropping finished nodes early"],1,"Trees don't need it (no cycles).","E"],["Time complexity of BFS/DFS on a graph?",["O(V × E)","O(V + E)","O(log V)","O(V²) always"],1,"Each vertex and edge once.","M"],["Level-order traversal of a binary tree uses?",["DFS","BFS with a queue","Binary search","A heap"],1,"Process level by level.","M"]]},{"id":"t11-6","no":"11.6","title":"Dynamic programming basics","imp":"good","quiz":[["What makes a problem a good fit for dynamic programming?",["Inputs that are sorted and searchable","Overlapping subproblems and optimal substructure","Choices that are always locally optimal","A recursion that splits into disjoint halves"],1,"Same subproblems recur, and answers combine.","E"],["Naive recursive fib(n) runs in?",["O(n): each call runs once","O(n log n): calls split in two","O(n²): n levels of n calls","Exponential time, about O(2ⁿ)"],3,"Memoisation brings it to O(n).","M"],["Coins {1, 3, 4}, amount 6. Greedy (largest first) vs optimal?",["Both give 2 coins (3+3)","Greedy 3 coins (4+1+1), optimal 2 (3+3)","Greedy 2 coins (4+2), optimal 3 (4+1+1)","Both give 3 coins (4+1+1)"],1,"Greedy isn't always optimal; DP checks every last-coin option.","H"],["What's memoisation?",["Storing a loop's state so it can be resumed later","Caching results of function calls to reuse them","Converting a recursive function into an iterative loop","Sorting inputs so repeated calls are found faster"],1,"Top-down DP.","E"],["Climbing stairs (1 or 2 steps): ways(n) = ?",["ways(n−1) × ways(n−2)","ways(n−1) + ways(n−2)","n²","2n"],1,"Like Fibonacci.","E"],["Bottom-up DP fills the table in which order?",["Random","From base cases towards the answer","From the answer backwards","Alphabetical"],1,"So dependencies are ready.","E"],["Why does greedy fail for coins {1, 3, 4} and amount 6?",["Greedy needs the coins sorted ascending; descending makes it pick 4+1+1","Taking 4 first leads to 4+1+1 (3 coins), but 3+3 (2 coins) is better","Greedy only works when the amount is a multiple of the largest coin, here 4","Taking 3 first leads to 3+1+1+1 (4 coins), while 4+1+1 is better"],1,"DP checks every choice.","M"],["Space for the climbing-stairs DP can be reduced to?",["O(n): the dp array can't shrink","O(1): keep only the last two values","O(log n): by halving the steps","O(√n): keeping a block of values"],1,"Rolling variables.","M"]]}],"db":[{"id":"t0-1","no":"0.1","title":"What a database gives you (vs plain files)","imp":"good","quiz":[["Two programs read qty = 5, each subtracts 1 and writes back 4. What is this called?",["Dirty read","Lost update","Phantom read","Deadlock"],1,"One write overwrote the other.","E"],["Which DBMS component lets it recover after a crash?",["The query optimizer","The write-ahead log","The connection pool","The B-tree index"],1,"Changes are logged before they're applied, so they can be redone or undone.","E"],["What does \"declarative\" mean for SQL?",["You must declare variables first","You state what result you want; the DBMS decides how to compute it","Every query must declare its indexes","Queries run in the order they're declared"],1,"The optimizer picks the execution plan.","E"],["Which is NOT a typical DBMS responsibility?",["Concurrency control","Crash recovery","Rendering the UI","Access control"],2,"Presentation is the application's job.","E"],["Physical data independence means…",["Data is stored on a different physical server","You can change storage or add indexes without changing queries","Each table lives in its own file","Applications can bypass the DBMS"],1,"Queries talk to the logical model.","M"],["Safest way to decrement stock?",["SELECT qty, subtract in Java, UPDATE qty = :new","UPDATE stock SET qty = qty - 1 WHERE id = ? AND qty > 0","DELETE and re-INSERT the row","Cache qty in Redis and write back hourly"],1,"One atomic statement, with a guard against going negative.","M"]]},{"id":"t0-2","no":"0.2","title":"The relational model: tables, rows, keys","imp":"must","quiz":[["In relational terms, a row is a…",["Relation","Tuple","Domain","Attribute"],1,"Relation = table, attribute = column.","E"],["A primary key must be…",["Unique and not NULL","Unique, NULL allowed once","Numeric","The first column"],0,"It identifies exactly one row.","E"],["How do you model a many-to-many relationship?",["A comma-separated column","A junction table with two foreign keys","Two foreign keys pointing at each other","Duplicating rows in both tables"],1,"E.g. enrollments(student_id, course_code).","E"],["Without ORDER BY, the order of rows returned is…",["Insertion order","Primary key order","Undefined; it can change","Alphabetical"],2,"Relations are sets; the engine returns whatever order its plan produces.","M"],["What does a foreign key enforce?",["That the column is unique","That each value exists as a key in the referenced table","That the column is indexed","That the column is never updated"],1,"Referential integrity.","E"],["Why not store the course title in every enrollment row?",["It's slower to read","Copies can disagree after an update (update anomaly)","SQL forbids it","Text columns can't be joined"],1,"One fact, one place.","M"]]},{"id":"t0-3","no":"0.3","title":"NULL and three-valued logic","imp":"must","quiz":[["What does <code>WHERE city = NULL</code> return?",["Rows where city is NULL","No rows","All rows","An error in every database"],1,"Comparison with NULL is UNKNOWN for every row.","E"],["COUNT(*) vs COUNT(email) on a table where 2 of 10 emails are NULL?",["10 and 10","10 and 8","8 and 8","8 and 10"],1,"COUNT(column) skips NULLs.","E"],["<code>TRUE OR UNKNOWN</code> is…",["TRUE","FALSE","UNKNOWN","NULL error"],0,"TRUE OR anything is TRUE.","E"],["Why can <code>x NOT IN (SELECT y …)</code> return no rows unexpectedly?",["NOT IN doesn't use indexes","If the subquery returns a NULL, every comparison becomes UNKNOWN","NOT IN removes duplicates","Subqueries run before the outer query"],1,"x <> NULL is UNKNOWN, so the AND chain is never TRUE.","M"],["Which returns 'n/a' when phone is NULL?",["NULLIF(phone, 'n/a')","COALESCE(phone, 'n/a')","ISNULL(phone) = 'n/a'","phone OR 'n/a'"],1,"First non-NULL argument.","E"],["A CHECK (age >= 18) constraint and an INSERT with age NULL. Result?",["Rejected","Accepted: CHECK only rejects FALSE","age becomes 18","Accepted only in MySQL"],1,"UNKNOWN passes a CHECK; add NOT NULL if needed.","M"]]},{"id":"t0-4","no":"0.4","title":"Constraints: keys, NOT NULL, UNIQUE, CHECK, foreign keys","imp":"must","quiz":[["How many primary keys can a table have?",["One (possibly over several columns)","One per column","As many as unique constraints","None if it has a UNIQUE column"],0,"A composite PK is still one key.","E"],["Which constraint stops a review from pointing at a deleted product?",["CHECK","UNIQUE","FOREIGN KEY","NOT NULL"],2,"Referential integrity.","E"],["ON DELETE CASCADE on order_items → orders means deleting an order…",["Fails if it has items","Deletes its items too","Sets items' order_id to NULL","Archives the items"],1,"Children follow the parent.","E"],["Why is \"SELECT to check the email is free, then INSERT\" not enough?",["SELECT is slow","Two requests can both pass the check before either inserts","INSERT ignores SELECT results","Emails are case-sensitive"],1,"A race; the unique constraint is atomic.","M"],["Which value passes <code>CHECK (qty &gt; 0)</code>?",["0","-1","NULL","None of these"],2,"UNKNOWN isn't FALSE, so it passes.","M"],["Why index a foreign key column?",["It's required by the SQL standard","Joins and parent deletes/updates look up children by it","It makes the constraint deferrable","It prevents NULLs"],1,"Otherwise each parent delete scans the child table.","M"]]},{"id":"t0-5","no":"0.5","title":"SQL sublanguages (DDL, DML, DCL, TCL) and data types","imp":"good","quiz":[["TRUNCATE belongs to…",["DML","DDL","DCL","TCL"],1,"It changes storage, not individual rows.","E"],["GRANT and REVOKE are…",["DDL","DML","DCL","TCL"],2,"Data control.","E"],["Best type for an account balance?",["FLOAT","DOUBLE","NUMERIC(19,4) or integer minor units","VARCHAR"],2,"Exact arithmetic.","E"],["ROLLBACK TO SAVEPOINT s…",["Ends the transaction","Undoes changes after s and keeps the transaction open","Commits up to s","Deletes the savepoint only"],1,"Partial rollback.","M"],["Which can take a WHERE clause?",["TRUNCATE","DROP","DELETE","CREATE"],2,"TRUNCATE empties the whole table.","E"],["Storing an instant for users in many time zones, the safest choice is…",["TIMESTAMP without time zone in local time","TIMESTAMPTZ (UTC internally)","A VARCHAR like '2024-03-01 10:00'","Two columns: date and time"],1,"Convert to local time at display.","M"]]},{"id":"t1-1","no":"1.1","title":"SELECT, WHERE, ORDER BY, LIMIT","imp":"must","quiz":[["<code>WHERE a = 1 OR b = 2 AND c = 3</code> is evaluated as…",["(a = 1 OR b = 2) AND c = 3","a = 1 OR (b = 2 AND c = 3)","Left to right","An error"],1,"AND has higher precedence than OR.","M"],["A query without ORDER BY returns rows…",["In primary key order","In insertion order","In no guaranteed order","Alphabetically"],2,"It depends on the plan.","E"],["<code>LIKE 'a_c'</code> matches…",["'abc'","'ac'","'abbc'","'xabc'"],0,"_ is exactly one character.","E"],["<code>BETWEEN 10 AND 20</code> includes…",["10 to 20 inclusive","11 to 19","10 to 19","11 to 20"],0,"Both ends inclusive.","E"],["Why can LIMIT without ORDER BY be a bug?",["It's not allowed","Which rows you get is arbitrary and can change","It always returns the newest rows","It disables indexes"],1,"Pair LIMIT with a deterministic ORDER BY.","E"],["SQL injection is best prevented by…",["Escaping quotes by hand","Parameterised queries / prepared statements","Using LIKE instead of =","Running queries as admin"],1,"Parameters are never parsed as SQL.","M"]]},{"id":"t1-2","no":"1.2","title":"Logical order of query execution","imp":"must","quiz":[["Which clause is logically evaluated first?",["SELECT","FROM","WHERE","ORDER BY"],1,"The rows must exist before anything else.","E"],["Where do you filter on COUNT(*) &gt; 5?",["WHERE","HAVING","ORDER BY","FROM"],1,"Aggregates exist after GROUP BY.","E"],["Why can ORDER BY use a SELECT alias but WHERE can't?",["ORDER BY is evaluated after SELECT; WHERE before it","Aliases are only for ORDER BY by definition","WHERE runs on the index only","It's a MySQL-only feature"],0,"Logical order.","M"],["Which runs last?",["HAVING","ORDER BY","LIMIT","SELECT"],2,"LIMIT cuts the sorted result.","E"],["A condition on a plain column placed in HAVING instead of WHERE…",["Errors","Gives the same result but filters later (more work)","Changes the result","Is faster"],1,"Valid if the column is a group key, but WHERE is better.","M"],["Filtering rows where ROW_NUMBER() = 1 requires…",["WHERE ROW_NUMBER() OVER (...) = 1","HAVING ROW_NUMBER() = 1","A subquery/CTE, then WHERE rn = 1 outside","LIMIT 1"],2,"Window functions run in SELECT.","M"]]},{"id":"t1-3","no":"1.3","title":"Joins: inner, left, right, full, cross","imp":"must","quiz":[["customers has 3 rows, orders has 4. What does <code>customers CROSS JOIN orders</code> return?",["7 rows","12 rows","4 rows","3 rows"],1,"A Cartesian product has n × m rows.","E"],["A customer with no orders appears in which join with orders?",["INNER JOIN only","LEFT JOIN (customers on the left) with NULL order columns","Neither INNER nor LEFT JOIN","Only CROSS JOIN"],1,"LEFT JOIN keeps every left row and NULL-pads the missing side.","E"],["<code>customers c LEFT JOIN orders o ON … WHERE o.status = 'paid'</code>: what happens to customers with no orders?",["They appear with NULL status","They are removed, because NULL = 'paid' is not true","The query errors","They appear with status 'paid'"],1,"WHERE runs after the join and filters out padded rows; put the condition in ON to keep them.","M"],["Asha has 2 orders with 3 items each. After joining customers → orders → order_items, how many rows does Asha have?",["1","2","3","6"],3,"Each join multiplies rows along one-to-many relationships.","M"],["Which query finds customers with no orders?",["SELECT * FROM customers c JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL","SELECT * FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL","SELECT * FROM customers c LEFT JOIN orders o ON o.customer_id = c.id AND o.id IS NULL","SELECT * FROM customers c CROSS JOIN orders o WHERE o.customer_id <> c.id"],1,"An inner join never produces NULL order ids; the ON variant keeps every customer.","M"],["Which database does NOT support FULL OUTER JOIN natively?",["PostgreSQL","MySQL","SQL Server","Oracle"],1,"MySQL needs LEFT JOIN … UNION … RIGHT JOIN.","E"],["For an INNER JOIN, is a condition in ON equivalent to the same condition in WHERE?",["Yes, the result is the same","No, WHERE keeps unmatched rows","No, ON is evaluated after GROUP BY","Only if the column is indexed"],0,"Only outer joins treat ON and WHERE differently.","M"],["A RIGHT JOIN B is the same as:",["A LEFT JOIN B","B LEFT JOIN A (with columns in a different order)","A FULL JOIN B","A INNER JOIN B"],1,"Most teams avoid RIGHT JOIN and write it as a LEFT JOIN with the tables swapped.","E"]]},{"id":"t1-4","no":"1.4","title":"Self joins, semi-joins (EXISTS) and anti-joins (NOT EXISTS)","imp":"must","quiz":[["What makes a self join possible?",["A special SELF JOIN keyword","Two different aliases for the same table","A recursive CTE","A foreign key to another table"],1,"e and m are two \"copies\" of employees.","E"],["Why LEFT JOIN when listing employees with managers?",["It's faster","So employees without a manager (the CEO) still appear","To remove duplicates","INNER JOIN can't join a table to itself"],1,"NULL-padded manager columns.","E"],["EXISTS returns TRUE when…",["The subquery returns at least one row","The subquery returns exactly one row","The subquery's first column is TRUE","No NULLs are found"],0,"The select list doesn't matter.","E"],["<code>WHERE id NOT IN (SELECT dept_id FROM employees)</code> returns 0 rows. Most likely cause?",["No index","A NULL dept_id in the subquery","Duplicates in the subquery","NOT IN is deprecated"],1,"x <> NULL is UNKNOWN.","M"],["Semi-join vs inner join for \"departments with employees\"?",["Same rows, no duplicates with the semi-join","Semi-join returns more rows","Inner join can't do it","Semi-join needs DISTINCT"],0,"JOIN repeats a department per employee.","M"],["To list each same-department pair once, add…",["a.id <> b.id","a.id < b.id","DISTINCT","GROUP BY a.id"],1,"<> still lists (A,B) and (B,A).","M"]]},{"id":"t1-5","no":"1.5","title":"GROUP BY, aggregates and HAVING","imp":"must","quiz":[["How many rows does <code>SELECT category, COUNT(*) FROM products GROUP BY category</code> return?",["One per product","One per distinct category","One","Depends on COUNT"],1,"One row per group.","E"],["Which can appear in SELECT with GROUP BY category?",["name","category and aggregates","Any column","Only aggregates"],1,"Group keys and aggregates.","E"],["Find categories with more than 2 products: the condition goes in…",["WHERE COUNT(*) > 2","HAVING COUNT(*) > 2","GROUP BY COUNT(*) > 2","ORDER BY"],1,"Group filter.","E"],["COUNT(DISTINCT customer_id) on orders gives…",["Number of orders","Number of customers who ordered","Number of NULLs","Always 1"],1,"Distinct non-NULL ids.","E"],["After joining orders to order_items, COUNT(*) per customer counts…",["Orders","Order lines","Customers","Products"],1,"The join is at line grain; use COUNT(DISTINCT o.id) for orders.","M"],["AVG(x) where x has values 10, NULL, 20 returns…",["10","15","NULL","30"],1,"NULL is skipped.","M"]]},{"id":"t1-6","no":"1.6","title":"Subqueries: scalar, list, correlated and derived tables","imp":"must","quiz":[["A scalar subquery returns two rows at runtime. Result?",["The first row is used","An error","NULL","Both rows are compared"],1,"\"more than one row returned by a subquery used as an expression\".","E"],["What makes a subquery correlated?",["It uses GROUP BY","It references a column of the outer query","It's in the FROM clause","It returns many rows"],1,"It depends on the outer row.","E"],["A subquery in FROM is called…",["A scalar subquery","A derived table / inline view","A correlated subquery","A semi-join"],1,"It needs an alias.","E"],["How is an uncorrelated scalar subquery evaluated?",["Once","Once per outer row","Once per group","Never: it's inlined as text"],0,"It doesn't depend on the outer row.","M"],["<code>salary &gt; ALL (SELECT salary FROM … WHERE dept_id = 2)</code> means…",["Greater than at least one salary in dept 2","Greater than every salary in dept 2","Equal to the max","Greater than the average"],1,"ALL = every.","M"],["Best rewrite for a slow correlated \"above dept average\" on a big table?",["Add DISTINCT","Join to a GROUP BY dept derived table, or AVG() OVER (PARTITION BY dept)","Use NOT IN","ORDER BY salary"],1,"Compute each average once.","M"]]},{"id":"t1-7","no":"1.7","title":"Set operations: UNION, UNION ALL, INTERSECT, EXCEPT","imp":"good","quiz":[["UNION vs UNION ALL?",["UNION keeps duplicates","UNION removes duplicates; UNION ALL keeps them","They're identical","UNION ALL removes NULLs"],1,"UNION ALL is cheaper.","E"],["Requirement for UNION?",["Same table","Same number of columns with compatible types","Same column names","A shared key"],1,"Matched by position.","E"],["A EXCEPT B returns…",["Rows in both","Rows in A not in B","Rows in B not in A","All rows"],1,"Oracle calls it MINUS.","E"],["Where does ORDER BY go in a UNION?",["In each query","Once at the end, sorting the combined result","Only in the first query","Not allowed"],1,"It applies to the whole result.","M"],["A has (1),(1),(2); B has (2),(3). A UNION ALL B has how many rows?",["3","4","5","2"],2,"Plain concatenation.","E"],["Output column names of a UNION come from…",["The last query","The first query","Both, joined with _","They're unnamed"],1,"Alias in the first SELECT.","M"]]},{"id":"t1-8","no":"1.8","title":"Changing data: INSERT, UPDATE, DELETE, UPSERT, RETURNING","imp":"good","quiz":[["<code>UPDATE products SET price = 0;</code> affects…",["No rows","One row","Every row","It's a syntax error"],2,"No WHERE = all rows.","E"],["Why list columns in INSERT?",["Required by SQL","Protects against column order changes and makes intent explicit","Faster parsing","Enables RETURNING"],1,"Schema evolution safety.","E"],["What does an upsert need to detect \"already exists\"?",["An index on any column","A unique constraint or primary key on the conflict columns","A trigger","SERIALIZABLE isolation"],1,"The conflict target.","M"],["In <code>ON CONFLICT … DO UPDATE SET price = excluded.price</code>, excluded refers to…",["The existing row","The row you tried to insert","Deleted rows","The previous transaction"],1,"MySQL uses VALUES(price) / new alias.","M"],["Best way to get an auto-generated id in Postgres?",["SELECT MAX(id) after insert","INSERT … RETURNING id","A second query by name","currval of a random sequence"],1,"Same round trip, no race.","E"],["Deleting 50M rows in one statement in production risks…",["Nothing","Long locks, huge WAL/replication lag, bloat","Faster vacuums","Index corruption"],1,"Batch it, or drop partitions.","M"]]},{"id":"t1-9","no":"1.9","title":"CASE expressions, conditional aggregation and pivots","imp":"good","quiz":[["CASE with no matching WHEN and no ELSE returns…",["0","''","NULL","An error"],2,"ELSE defaults to NULL.","E"],["price = 900 with WHEN price >= 100 THEN 'mid' WHEN price >= 500 THEN 'premium' gives…",["'premium'","'mid'","both","NULL"],1,"First TRUE branch wins: order WHENs carefully.","E"],["Conditional aggregation means…",["Aggregating only indexed columns","An aggregate over a CASE expression, e.g. SUM(CASE WHEN … THEN 1 ELSE 0 END)","HAVING with CASE","GROUP BY CASE"],1,"Several filtered counts in one pass.","M"],["COUNT(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) counts…",["Paid rows","All rows (0 is not NULL)","Unpaid rows","Nothing"],1,"Use SUM, or drop the ELSE.","M"],["<code>CASE x WHEN NULL THEN 'none' END</code> for x NULL returns…",["'none'","NULL","Error","'x'"],1,"Simple CASE uses =; use WHEN x IS NULL.","M"],["Safe ratio a/b when b can be 0?",["a / b","a / NULLIF(b, 0)","a / COALESCE(b, 0)","a / ABS(b)"],1,"Division by NULL → NULL.","E"]]},{"id":"t2-1","no":"2.1","title":"CTEs (WITH) and recursive queries","imp":"must","quiz":[["A CTE is defined with…",["CREATE VIEW","WITH name AS (…)","DECLARE CURSOR","TEMP TABLE"],1,"It lives for one statement.","E"],["The two parts of a recursive CTE are…",["SELECT and FROM","Anchor member and recursive member, joined by UNION ALL","Base table and index","Parent and child views"],1,"The anchor seeds; the recursive member repeats.","E"],["When does a recursive CTE stop?",["After 100 rounds always","When the recursive member produces no new rows","When the anchor returns NULL","At the first duplicate"],1,"Fixpoint.","E"],["What can make a recursive CTE run forever?",["An index","A cycle in the data with no guard","ORDER BY","UNION ALL"],1,"Add a depth limit or visited-path check.","M"],["In each round the recursive member joins against…",["All rows produced so far","Only the rows produced in the previous round","The base table only","The anchor only"],1,"The working table.","H"],["Main advantage of a CTE over a nested subquery?",["Always faster","Readability and reuse within the statement","Persists across sessions","Can be indexed"],1,"Performance depends on the planner.","E"]]},{"id":"t2-2","no":"2.2","title":"Window functions I: OVER, PARTITION BY, ROW_NUMBER, RANK, DENSE_RANK","imp":"must","quiz":[["How is a window function different from GROUP BY?",["It's faster","It keeps every row and adds a computed column","It can't use aggregates","It needs an index"],1,"No collapsing.","E"],["Scores 100, 90, 90, 80. RANK gives…",["1,2,3,4","1,2,2,3","1,2,2,4","1,1,2,3"],2,"Gap after ties.","E"],["Same scores, DENSE_RANK gives…",["1,2,2,3","1,2,2,4","1,2,3,4","1,1,1,2"],0,"No gaps.","E"],["What does PARTITION BY do?",["Physically partitions the table","Splits rows into independent windows for the function","Sorts the output","Removes duplicates"],1,"Like GROUP BY without collapsing.","E"],["Why can't you write WHERE ROW_NUMBER() OVER (…) = 1?",["Syntax limitation of ROW_NUMBER only","Window functions are computed after WHERE (SELECT phase)","It needs HAVING","It can't be compared to integers"],1,"Wrap it in a CTE.","M"],["For \"top 3 salaries per dept, include ties\", use…",["ROW_NUMBER","DENSE_RANK (or RANK)","NTILE","COUNT"],1,"ROW_NUMBER would cut ties arbitrarily.","M"]]},{"id":"t2-3","no":"2.3","title":"Window functions II: running totals, moving averages, LAG / LEAD, frames","imp":"must","quiz":[["SUM(x) OVER (ORDER BY d) computes…",["The grand total on every row","A running total up to the current row","A moving average","The previous row's x"],1,"ORDER BY makes it cumulative.","E"],["LAG(x) on the first row of a partition returns…",["0","NULL (unless a default is given)","The last row's x","An error"],1,"No previous row.","E"],["A 7-day moving average over daily rows uses…",["ROWS BETWEEN 6 PRECEDING AND CURRENT ROW","ROWS BETWEEN 7 PRECEDING AND 7 FOLLOWING","RANGE UNBOUNDED","PARTITION BY 7"],0,"Current + 6 previous = 7 rows.","M"],["LEAD(x) returns…",["The previous row's x","The next row's x","The first value","The max"],1,"Looks forward.","E"],["Per-user time between events requires…",["PARTITION BY user_id ORDER BY ts","GROUP BY user_id","ORDER BY user_id only","DISTINCT user_id"],0,"Otherwise LAG crosses users.","M"],["SUM(x) OVER (PARTITION BY g) with no ORDER BY gives…",["A running total","The group total on every row of the group","An error","x itself"],1,"Frame = whole partition.","M"]]},{"id":"t2-4","no":"2.4","title":"Classic interview SQL: Nth highest, duplicates, top-N per group, running balance","imp":"must","quiz":[["Salaries 300, 300, 200, 100. \"Second highest salary\" is usually…",["300","200","100","NULL"],1,"Distinct values: 300, 200, 100.","E"],["Which function is right for Nth highest distinct salary?",["ROW_NUMBER","RANK","DENSE_RANK","NTILE"],2,"No gaps after ties.","M"],["<code>SELECT salary FROM e ORDER BY salary DESC LIMIT 1 OFFSET 1</code> on 300, 300, 200 returns…",["200","300","NULL","Error"],1,"Without DISTINCT the duplicate 300 occupies offset 1.","M"],["MAX(salary) WHERE salary < (SELECT MAX(salary) …) when all salaries are equal returns…",["That salary","NULL","0","An error"],1,"MAX over no rows is NULL.","M"],["Find duplicate emails…",["SELECT DISTINCT email","GROUP BY email HAVING COUNT(*) > 1","WHERE COUNT(email) > 1","ORDER BY email"],1,"Groups with more than one row.","E"],["To delete duplicates keeping one copy…",["DELETE … WHERE COUNT(*) > 1","ROW_NUMBER() OVER (PARTITION BY key ORDER BY id), delete rn > 1","DISTINCT then TRUNCATE","DELETE with LIMIT 1"],1,"Deterministic survivor.","M"]]},{"id":"t2-5","no":"2.5","title":"Gaps and islands: streaks and consecutive runs","imp":"good","quiz":[["In gaps-and-islands, an \"island\" is…",["A missing range","A maximal run of consecutive values","A partition","A NULL group"],1,"Gaps are the missing ranges.","E"],["Why does date − ROW_NUMBER() identify a streak?",["It's always unique","Within a consecutive run both increase by 1 per row, so the difference is constant","It sorts dates","It removes gaps"],1,"A gap changes the difference.","M"],["Logins on days 1, 2, 4. date − rn gives…",["0, 0, 1","0, 0, 0","1, 2, 4","0, 1, 2"],0,"1−1, 2−2, 4−3.","M"],["Two logins on the same day break the trick because…",["ROW_NUMBER increases while the date doesn't","Dates can't repeat","GROUP BY fails","LAG returns NULL"],0,"Deduplicate days first or use DENSE_RANK.","H"],["To find missing ids, compare each id with…",["LAG(id) or LEAD(id)","MAX(id)","COUNT(*)","RANK()"],0,"A jump > 1 is a gap.","E"],["Sessionizing clicks with a 30-minute timeout uses…",["date − ROW_NUMBER()","LAG to flag new sessions + running SUM","NTILE(30)","GROUP BY minute"],1,"Time gaps aren't uniform steps.","M"]]},{"id":"t2-6","no":"2.6","title":"Views and materialized views","imp":"good","quiz":[["A plain view stores…",["The result rows","The query definition","An index","A copy of each base table"],1,"Re-evaluated on each use.","E"],["A materialized view's main drawback?",["Slow reads","Staleness until refreshed","Can't be queried with WHERE","Can't contain joins"],1,"Speed for freshness.","E"],["Main reasons to use a plain view?",["Speed","Abstraction and security (hiding columns/joins)","Lower storage","Automatic indexing"],1,"It doesn't cache.","E"],["REFRESH MATERIALIZED VIEW CONCURRENTLY in Postgres requires…",["SERIALIZABLE isolation","A unique index on the materialized view","No indexes","Superuser"],1,"To diff old and new rows.","M"],["A view with GROUP BY is usually…",["Updatable","Read-only (unless INSTEAD OF triggers)","Materialized automatically","Invalid"],1,"Can't map an update to base rows.","M"],["WITH CHECK OPTION on a view…",["Validates SQL syntax","Rejects inserts/updates that would produce rows the view can't see","Refreshes it","Adds a CHECK constraint to the base table"],1,"E.g. a view WHERE region = 'EU'.","M"]]},{"id":"t2-7","no":"2.7","title":"Stored procedures, functions and triggers","imp":"good","quiz":[["A trigger runs…",["When called with CALL","Automatically on a table event like INSERT/UPDATE/DELETE","On a schedule","Only during backups"],1,"Event-driven.","E"],["In a row-level UPDATE trigger, OLD and NEW are…",["Old and new tables","The row before and after the change","Old and new transactions","The previous and next rows by id"],1,"INSERT has only NEW; DELETE only OLD.","E"],["If the UPDATE that fired an AFTER trigger rolls back, the trigger's audit insert…",["Stays","Rolls back too (same transaction)","Is retried","Is logged elsewhere"],1,"Atomic with the triggering statement.","M"],["Main benefit of a stored procedure for multi-statement work?",["Automatic indexing","One network round trip and logic close to the data","No locks","It's always faster than SQL"],1,"Fewer round trips.","E"],["Which can modify the row being inserted before it is written?",["AFTER INSERT trigger","BEFORE INSERT trigger (changing NEW)","A view","A CHECK constraint"],1,"BEFORE triggers can change NEW.","M"],["A common risk of heavy trigger use?",["Faster writes","Hidden side effects and slower writes","No transactions","Data loss on restart"],1,"Invisible to app developers.","M"]]},{"id":"t3-1","no":"3.1","title":"ER modeling: entities, relationships, cardinality","imp":"must","quiz":[["In a 1:N relationship, the foreign key goes…",["On the \"one\" side","On the \"many\" side","In a junction table","On both sides"],1,"courses.instructor_id.","E"],["An M:N relationship is implemented with…",["A foreign key on one side","A junction table with two foreign keys","An array column","A 1:1 table"],1,"Two 1:N relationships.","E"],["How is a 1:1 typically enforced?",["A foreign key with a UNIQUE constraint (or as the PK)","Two foreign keys","A CHECK constraint","It can't be"],0,"At most one match on each side.","M"],["Where does \"grade\" go for students ↔ courses?",["students","courses","enrollments (the junction table)","a separate grades table with no keys"],2,"It describes the pair.","E"],["\"Every order must have a customer\" translates to…",["A UNIQUE customer_id","orders.customer_id NOT NULL with an FK","A junction table","A CHECK on customers"],1,"Mandatory participation.","M"],["An employee's manager is another employee. This is…",["An M:N","A recursive (self-referencing) 1:N","A 1:1","A weak entity"],1,"FK to the same table.","E"]]},{"id":"t3-2","no":"3.2","title":"Keys: super, candidate, primary, alternate, surrogate, composite","imp":"must","quiz":[["A candidate key is…",["Any unique column set","A minimal superkey","The primary key","A foreign key"],1,"Remove a column and it's no longer unique.","E"],["How many primary keys per table?",["One","One per candidate key","Unlimited","Zero or more"],0,"Possibly composite.","E"],["{emp_no, name} where emp_no is unique is…",["A candidate key","A superkey but not a candidate key","Not a key","A foreign key"],1,"Not minimal.","M"],["Main argument for a surrogate primary key?",["It's human-readable","It never changes, so foreign keys never need updating","It enforces business uniqueness","It's required by SQL"],1,"Stability.","M"],["Alternate keys should be…",["Ignored","Declared UNIQUE","Declared as foreign keys","Indexed only"],1,"Still keys.","E"],["Why can't data alone prove a column is a key?",["It can","Today's data may be unique by accident; keys come from business rules","Because of NULLs only","Because indexes are missing"],1,"Rules, not samples.","M"]]},{"id":"t3-3","no":"3.3","title":"Functional dependencies and update/insert/delete anomalies","imp":"good","quiz":[["customer_id → city means…",["city determines customer_id","rows with the same customer_id have the same city","customer_id is unique","city is a key"],1,"Equal X ⇒ equal Y.","E"],["Changing a customer's city in some rows but not others is…",["An insertion anomaly","An update anomaly","A deletion anomaly","A phantom read"],1,"Copies disagree.","E"],["Can't add a product until it's ordered: which anomaly?",["Update","Insertion","Deletion","None"],1,"The key requires an order.","E"],["With key (order_id, product_id), order_id → order_date is a…",["Full dependency","Partial dependency","Transitive dependency","Multivalued dependency"],1,"Depends on part of the key.","M"],["order_id → customer_id → customer_city: city's dependency on order_id is…",["Partial","Transitive","Trivial","Multivalued"],1,"Through a non-key column.","M"],["A lossless decomposition guarantees…",["Fewer rows","Joining the parts recreates exactly the original table","No foreign keys needed","Faster queries"],1,"No spurious rows.","M"]]},{"id":"t3-4","no":"3.4","title":"Normalization: 1NF, 2NF, 3NF step by step","imp":"must","quiz":[["A column holding 'red,green,blue' violates…",["1NF","2NF","3NF","BCNF only"],0,"Not atomic.","E"],["2NF removes…",["Repeating groups","Partial dependencies on a composite key","Transitive dependencies","Multivalued dependencies"],1,"Columns depending on part of the key.","E"],["employees(id, dept_id, dept_name): which NF is violated?",["1NF","2NF","3NF","None"],2,"id → dept_id → dept_name is transitive.","M"],["A table whose primary key is a single column is automatically in…",["3NF","2NF (if it's in 1NF)","BCNF","4NF"],1,"No part of the key to depend on.","M"],["\"The key, the whole key, and nothing but the key\" summarises…",["1NF","1NF through 3NF","Indexes","ACID"],1,"Key (1NF), whole key (2NF), nothing but (3NF).","E"],["Main cost of normalization?",["More storage","More joins on reads","More anomalies","No foreign keys"],1,"Writes get simpler; reads join.","M"]]},{"id":"t3-5","no":"3.5","title":"BCNF, 4NF and when to stop normalizing","imp":"good","quiz":[["BCNF requires that…",["All columns are atomic","Every determinant of a non-trivial FD is a superkey","No NULLs","Every table has a surrogate key"],1,"Stricter than 3NF.","E"],["Every BCNF table is also in 3NF.",["True","False","Only with single-column keys","Only without NULLs"],0,"BCNF ⊂ 3NF.","E"],["A table is 3NF but not BCNF typically when…",["It has no key","It has overlapping candidate keys and a non-key determinant","It has a repeating group","It has a partial dependency"],1,"tutor → subject.","M"],["Downside of decomposing to BCNF?",["It can be lossy","It may not preserve all dependencies","It adds repeating groups","It breaks 1NF"],1,"Lossless is always achievable; preservation isn't.","M"],["4NF deals with…",["Transitive dependencies","Multivalued dependencies","Atomicity","Indexes"],1,"Independent lists.","E"],["person(skill, language) storing every combination is fixed by…",["Adding an index","Splitting into person_skills and person_languages","A CHECK constraint","Denormalizing"],1,"4NF.","M"]]},{"id":"t3-6","no":"3.6","title":"Denormalization, OLTP vs OLAP, star and snowflake schemas","imp":"good","quiz":[["OLTP workloads are mostly…",["Few huge scans","Many small reads and writes by key","Batch loads","Graph traversals"],1,"Transactional.","E"],["A star schema's central table is the…",["Dimension table","Fact table","Junction table","Lookup table"],1,"Events and measures.","E"],["Measures are…",["Descriptive text attributes","Numeric values you aggregate (qty, revenue)","Primary keys","Indexes"],1,"Live in the fact table.","E"],["Main risk of denormalization?",["Slower reads","Copies getting out of sync","Too few joins","No indexes"],1,"You must maintain consistency.","E"],["Snowflake vs star?",["Snowflake normalizes dimensions (more joins)","Snowflake has no fact table","Star normalizes dimensions","They're identical"],0,"Star is usually preferred.","M"],["\"One row per order line per day\" is a statement of…",["Cardinality","Grain","Isolation","Selectivity"],1,"Define it first.","M"]]},{"id":"t3-7","no":"3.7","title":"Modeling patterns: soft delete, history tables, polymorphism, EAV, JSON","imp":"good","quiz":[["Main downside of soft deletes?",["Data loss","Every query must filter deleted rows; unique constraints need care","Breaks foreign keys","Can't be undone"],1,"Use views/scopes and partial indexes.","E"],["Reusing a soft-deleted user's email requires…",["Dropping the unique constraint","A partial unique index on active rows","Hard delete only","A trigger"],1,"UNIQUE … WHERE deleted_at IS NULL.","M"],["target_type + target_id polymorphic columns can't…",["Be indexed","Have a real foreign key","Be joined","Store integers"],1,"The FK target varies.","E"],["EAV's biggest weakness?",["Too many tables","No types/constraints and painful multi-attribute queries","Can't store text","Needs JSON"],1,"Everything is a string row.","M"],["A current row in a validity-range history table has…",["valid_from NULL","valid_to NULL (or a far-future date)","deleted_at set","No product_id"],1,"Open-ended range.","E"],["When should a field inside a JSON column become a real column?",["Never","When it's frequently filtered, joined, aggregated or constrained","When it's a string","When the JSON is large"],1,"Promote hot fields.","M"]]},{"id":"t4-1","no":"4.1","title":"How data is stored: pages, heap files, the buffer pool","imp":"good","quiz":[["The basic unit of disk I/O in a database is…",["A row","A page/block","A column","A table"],1,"Whole pages are read and written.","E"],["Without an index, WHERE customer_id = 7 on a heap table requires…",["Reading one page","Reading every page (full scan)","A hash lookup","Reading the WAL"],1,"Rows aren't ordered.","E"],["What is the buffer pool?",["A pool of DB connections","An in-memory cache of data pages","A queue of transactions","A log file"],1,"Shared buffers in Postgres.","E"],["Roughly how much slower is a random SSD read than a RAM access?",["2×","~1000×","1,000,000,000×","Same"],1,"~100 ns vs ~100 µs.","M"],["A column store is best for…",["Fetching one whole customer row","Aggregating one column over billions of rows","High-rate single-row updates","Foreign key checks"],1,"Reads only needed columns.","M"],["Postgres page size by default?",["4 KB","8 KB","16 KB","1 MB"],1,"InnoDB uses 16 KB.","M"]]},{"id":"t4-2","no":"4.2","title":"B+ tree indexes: search, range scan, insert and split","imp":"must","quiz":[["In a B+ tree, row pointers (or rows) are stored in…",["Only the root","Only the leaves","Every node","A separate hash table"],1,"Internal nodes hold separators only.","E"],["A point lookup costs about…",["One page per tree level","One page per row in the table","Always exactly one page","log₂(n) pages"],0,"Height ~3–4.","E"],["Why can a B+ tree serve range queries efficiently?",["It hashes ranges","Leaves are sorted and linked","It stores ranges in the root","It caches results"],1,"Descend once, then walk.","E"],["What happens when inserting into a full leaf?",["The insert fails","The leaf splits and a separator is pushed to the parent","The tree is rebuilt","The key goes to an overflow file"],1,"Keeps the tree balanced.","M"],["Why are B+ trees only 3–4 levels for 100M rows?",["Rows are small","High fanout: hundreds of children per page","They're binary","They store only 1000 keys"],1,"Height ≈ log_fanout(n).","M"],["Downside of many indexes on a table?",["Slower reads","Every write must update every index","They make tables read-only","They break foreign keys"],1,"Write amplification + memory.","E"]]},{"id":"t4-3","no":"4.3","title":"Clustered vs secondary indexes, covering and index-only scans","imp":"must","quiz":[["How many clustered indexes can a table have?",["One","Two","One per column","Unlimited"],0,"Rows have one physical order.","E"],["In InnoDB, a secondary index leaf stores…",["The full row","The indexed columns + the primary key","A physical page address","Nothing"],1,"Then the clustered tree is searched.","M"],["An index-only scan happens when…",["The table is empty","The index contains every column the query needs","The index is clustered","There's no WHERE clause"],1,"Covering index.","E"],["PostgreSQL tables are stored as…",["Clustered PK B-trees","Heaps; indexes point to ctids","LSM trees","Column stores"],1,"CLUSTER reorders once only.","M"],["INCLUDE columns in an index are…",["Part of the search key","Stored in leaves only, to cover queries","Hashed","Unique"],1,"Payload, not key.","M"],["Why keep InnoDB primary keys short?",["Faster DDL","They're copied into every secondary index entry","InnoDB limits PK length to 8 bytes","For replication"],1,"Index size and cache efficiency.","M"]]},{"id":"t4-4","no":"4.4","title":"Composite indexes and the leftmost-prefix rule","imp":"must","quiz":[["Index (a, b). Which WHERE can seek using it?",["b = 1","a = 1","b > 1","None"],1,"Leftmost prefix.","E"],["Index (last_name, first_name) is most like…",["A hash table","A phone book","A heap","A queue"],1,"Sorted by last, then first.","E"],["With index (a, b), WHERE a > 5 AND b = 3…",["Seeks on both a and b","Range on a; b is filtered entry by entry","Can't use the index at all","Seeks on b only"],1,"A range ends the seekable prefix.","M"],["Best index for WHERE status = ? AND created_at > ?",["(created_at, status)","(status, created_at)","(status) only","(created_at) only"],1,"Equality first, range second.","M"],["Given index (a, b), an index on (a) alone is…",["Required","Usually redundant","Faster for everything","Needed for ORDER BY a"],1,"(a, b) already serves a-only queries.","M"],["WHERE a = 1 ORDER BY b with index (a, b) needs a sort?",["Yes","No: entries for a = 1 are already ordered by b","Only with LIMIT","Only for DESC"],1,"Index order provides sort order.","E"]]},{"id":"t4-5","no":"4.5","title":"Why isn't my index used? Sargability, functions, casts, selectivity","imp":"must","quiz":[["Which predicate can use an index on created_at?",["DATE(created_at) = '2024-03-01'","created_at >= '2024-03-01' AND created_at < '2024-03-02'","created_at + 1 > NOW()","CAST(created_at AS TEXT) LIKE '2024%'"],1,"Raw column vs constants.","E"],["\"Sargable\" means…",["Sorted","Usable as an index search argument","Saved in RAM","Secured"],1,"Search ARGument ABLE.","E"],["LIKE 'abc%' vs LIKE '%abc' on an indexed column…",["Both use the index","Only 'abc%' can seek","Only '%abc' can seek","Neither"],1,"A fixed prefix is a range.","E"],["VARCHAR phone compared to a numeric literal in MySQL…",["Uses the index","Converts each value to a number, preventing index seeks","Errors","Is faster"],1,"Implicit conversion.","M"],["An index on status, where 90% of rows are 'active'. WHERE status = 'active'…",["Index is ideal","A full scan is likely cheaper","Always errors","Uses a hash"],1,"Low selectivity.","M"],["To use an index for lower(email) = ?…",["Impossible","Create an expression index on lower(email)","Index email twice","Use LIKE"],1,"Functional index.","M"]]},{"id":"t4-6","no":"4.6","title":"Beyond B-trees: hash, bitmap, inverted (GIN), BRIN and partial indexes","imp":"good","quiz":[["A hash index can answer…",["WHERE x > 5","WHERE x = 5","ORDER BY x","WHERE x LIKE 'a%'"],1,"Equality only.","E"],["Bitmap indexes suit…",["High-cardinality, write-heavy columns","Low-cardinality columns in read-mostly analytics","Primary keys","Full-text search"],1,"Bitwise AND/OR.","E"],["GIN / inverted index maps…",["Row → values","Value/term → rows containing it","Page → min/max","Key → bucket"],1,"Containment queries.","E"],["BRIN works well when…",["Values are random","Values correlate with physical row order (e.g. append-only timestamps)","The table is tiny","Columns are text"],1,"Min/max per block range.","M"],["A partial index on orders WHERE status = 'placed' is used by…",["Any query on orders","Queries whose WHERE implies status = 'placed'","Only UPDATEs","Only joins"],1,"Otherwise it might miss rows.","M"],["Why is B-tree the default index type?",["Smallest","Handles equality, ranges, sorting and prefixes","Fastest writes","Only one supported"],1,"Versatile.","E"]]},{"id":"t4-7","no":"4.7","title":"LSM trees: memtables, SSTables, compaction (write-optimised storage)","imp":"good","quiz":[["An LSM write goes to…",["The right B-tree page, in place","A WAL append and the in-memory memtable","Every SSTable","A bloom filter only"],1,"Sequential and cheap.","E"],["SSTables are…",["Mutable heap files","Immutable sorted files","In-memory only","Hash tables"],1,"Never modified after writing.","E"],["A delete in an LSM tree writes…",["Nothing","A tombstone","Zeros over the old value","A new SSTable per key"],1,"Older files may hold the key.","E"],["A bloom filter can return…",["False negatives","\"Definitely not present\" or \"maybe present\"","Exact counts","The value"],1,"No false negatives.","M"],["Compaction…",["Compresses the WAL","Merges SSTables, keeping newest versions and dropping obsolete data","Deletes the memtable","Rebuilds B-trees"],1,"Background merge.","E"],["LSM trees trade…",["Write speed for read speed","Some read cost and write amplification for high write throughput","Durability for speed","Nothing"],1,"Write-optimised.","M"]]},{"id":"t5-1","no":"5.1","title":"Life of a query: parse, rewrite, plan, execute","imp":"good","quiz":[["Which stage chooses between an index scan and a full scan?",["Parser","Analyzer","Optimizer","Executor"],2,"Cost-based choice.","E"],["\"column does not exist\" is raised by…",["The parser","The analyzer/binder","The optimizer","The storage engine"],1,"Name resolution against the catalog.","M"],["In the iterator (volcano) model, operators…",["Push all rows at once","Expose next() and pull rows from their children","Run in separate processes","Use only indexes"],1,"Rows flow upward.","M"],["Which operator is blocking?",["Filter","Projection","Sort","Index scan"],2,"Needs all input first.","E"],["Prepared statements mainly help by…",["Caching result rows","Reusing parsing/planning and separating parameters from SQL","Skipping transactions","Disabling locks"],1,"Also prevents injection.","E"],["View expansion happens in…",["The rewriter","The executor","The buffer pool","The WAL"],0,"Replace the view name with its definition.","M"]]},{"id":"t5-2","no":"5.2","title":"Reading EXPLAIN / EXPLAIN ANALYZE","imp":"must","quiz":[["EXPLAIN ANALYZE differs from EXPLAIN because it…",["Only parses","Actually runs the query and reports real rows and times","Shows only costs","Rewrites the query"],1,"Careful with writes.","E"],["In a plan tree, which nodes run first?",["The top node","The most indented (leaf) nodes","Alphabetical order","Joins"],1,"Data flows up.","E"],["cost=10.5..200.0 means…",["10.5 ms to 200 ms","Estimated startup cost 10.5 and total cost 200 (abstract units)","10 to 200 rows","Memory used"],1,"Not milliseconds.","M"],["rows=100 estimated, actual rows=500000. Most likely cause?",["Network latency","Stale or inadequate statistics","Too many indexes","A syntax error"],1,"Run ANALYZE.","M"],["An inner index scan shows actual time=0.05 ms loops=20000. Its total time is about…",["0.05 ms","1 second","20 seconds","0.0025 ms"],1,"0.05 × 20000 = 1000 ms.","M"],["\"Sort Method: external merge Disk\" indicates…",["An index was used","The sort spilled to disk (not enough memory)","Parallel query","A covering index"],1,"Raise work_mem or avoid the sort.","E"]]},{"id":"t5-3","no":"5.3","title":"Join algorithms: nested loop, hash join, sort-merge join","imp":"good","quiz":[["Index nested loop cost is roughly…",["|outer| × cost of one index lookup","|A| + |B|","|A| × |B| always","log |A|"],0,"Fast with a small outer side.","M"],["In a hash join, the build side is usually…",["The larger input","The smaller input","Always the left table","The indexed table"],1,"So the hash table fits in memory.","E"],["Merge join requires inputs…",["Hashed","Sorted on the join key","Indexed on every column","Smaller than work_mem"],1,"Then a linear walk.","E"],["Which algorithm handles WHERE a.ts BETWEEN b.start AND b.end?",["Hash join","Merge join (equality only)","Nested loop","None"],2,"Hash needs equality.","M"],["A hash join's build side doesn't fit in memory. Result?",["Query fails","It spills to disk in batches (slower)","Switches to merge join at runtime","Returns partial results"],1,"Grace/hybrid hash join.","M"],["Nested loop without an inner index on 100k × 100k rows…",["Fast","~10 billion comparisons: very slow","Same as hash join","Impossible"],1,"O(n × m).","E"]]},{"id":"t5-4","no":"5.4","title":"The cost-based optimizer: statistics, selectivity, cardinality estimates","imp":"good","quiz":[["The optimizer picks a plan by…",["Running each candidate","Estimating costs from statistics","Choosing the first index","Random choice"],1,"Cost-based estimation.","E"],["Selectivity 0.01 on 2M rows estimates…",["200 rows","20,000 rows","2M rows","0.01 rows"],1,"2,000,000 × 0.01.","E"],["Statistics are refreshed by…",["VACUUM FULL only","ANALYZE (or autovacuum's autoanalyze)","REINDEX","Restarting the server"],1,"Samples the table.","E"],["An MCV list contains…",["Most common values and their frequencies","Every distinct value","Index pages","Query plans"],0,"Used for equality estimates.","M"],["Two correlated predicates cause the planner to…",["Overestimate","Underestimate (it multiplies selectivities)","Ignore one","Fail"],1,"Independence assumption.","M"],["After bulk-loading 10× more rows, plans get worse. First fix?",["Add hints","ANALYZE the table","Drop all indexes","Restart"],1,"Stale statistics.","M"]]},{"id":"t5-5","no":"5.5","title":"N+1 queries and pagination: OFFSET vs keyset (seek) pagination","imp":"must","quiz":[["What is the N+1 problem?",["N joins in one query","One query for a list plus one extra query per item","N indexes on a table","A deadlock among N transactions"],1,"Usually ORM lazy loading.","E"],["Which fixes N+1 for many-to-one relations?",["More indexes","A fetch join or batched IN query","OFFSET","Higher isolation"],1,"Fewer round trips.","E"],["OFFSET 100000 LIMIT 10 typically…",["Reads only 10 rows","Reads and discards ~100,000 rows first","Is constant time with an index","Errors"],1,"Linear in depth.","E"],["Keyset pagination requires…",["A unique, ordered sort key (add a tiebreaker) and ideally a matching index","OFFSET","Temporary tables","SERIALIZABLE"],0,"WHERE key > last.","M"],["Why can OFFSET pages show duplicates?",["Bugs in LIMIT","Rows inserted/deleted between requests shift positions","Indexes are stale","Caching"],1,"Keyset is stable.","M"],["Keyset pagination's main limitation?",["Slow deep pages","No direct jump to an arbitrary page number","Needs NoSQL","Unstable ordering"],1,"Next/previous navigation.","M"]]},{"id":"t6-1","no":"6.1","title":"Transactions and ACID","imp":"must","quiz":[["Atomicity guarantees…",["Transactions run one at a time","All of a transaction's changes happen or none do","Data is never lost after commit","Constraints are checked"],1,"All or nothing.","E"],["Durability is typically implemented with…",["Indexes","A write-ahead log flushed before COMMIT returns","Replication only","Caching"],1,"WAL + fsync.","E"],["Isolation means…",["Each transaction has its own server","Concurrent transactions don't see each other's partial work (to a degree)","No locks are used","Only one user at a time"],1,"Strength = isolation level.","E"],["A CHECK constraint failing during a transaction relates to…",["Atomicity","Consistency","Isolation","Durability"],1,"Valid state to valid state.","E"],["In autocommit mode, an UPDATE…",["Waits for an explicit COMMIT","Commits immediately on its own","Is rolled back at disconnect","Is buffered"],1,"Each statement is a transaction.","M"],["ACID \"C\" vs CAP \"C\"…",["Same thing","Different: integrity constraints vs linearizable reads across replicas","CAP C is stronger ACID C","Both mean durability"],1,"Common interview trap.","M"]]},{"id":"t6-2","no":"6.2","title":"Isolation levels: dirty reads, non-repeatable reads, phantoms, lost updates","imp":"must","quiz":[["A dirty read is…",["Reading a row deleted and committed","Reading another transaction's uncommitted change","Reading the same row twice and getting different values","Reading from a stale replica"],1,"Only READ UNCOMMITTED allows it.","E"],["Under READ COMMITTED, T1 reads, T2 updates and commits, T1 reads again. T1 sees…",["The old value","The new value (non-repeatable read)","An error","It blocks until T1 commits"],1,"Fresh snapshot per statement.","M"],["PostgreSQL's default isolation level?",["READ UNCOMMITTED","READ COMMITTED","REPEATABLE READ","SERIALIZABLE"],1,"MySQL InnoDB: REPEATABLE READ.","E"],["A phantom read is…",["A NULL value appearing","New rows appearing when a range query is repeated","A deleted table","A dirty write"],1,"Range-level anomaly.","E"],["Higher isolation levels typically cost…",["Nothing","More blocking or aborted transactions that must be retried","More disk space only","Lower durability"],1,"Concurrency trade-off.","M"],["Two transactions read 100 and each write 100 − x. Name?",["Phantom","Lost update","Dirty read","Deadlock"],1,"Read-modify-write race.","E"]]},{"id":"t6-3","no":"6.3","title":"Locking: shared vs exclusive, row vs table, FOR UPDATE, two-phase locking","imp":"must","quiz":[["Shared and exclusive locks on the same row are…",["Compatible","Incompatible: one must wait","Merged","Ignored with MVCC"],1,"X conflicts with everything.","E"],["In strict two-phase locking, locks are released…",["After each statement","At COMMIT/ROLLBACK","Every second","When memory is low"],1,"End of transaction.","M"],["SELECT … FOR UPDATE is used to…",["Speed up reads","Lock rows you intend to modify, preventing concurrent conflicting writes","Create an index","Avoid transactions"],1,"Safe read-modify-write.","E"],["FOR UPDATE SKIP LOCKED is ideal for…",["Reports","Job queues with many workers","Schema migrations","Backups"],1,"Workers don't block each other.","M"],["In Postgres, does a plain SELECT block a concurrent UPDATE of the same row?",["Yes","No: MVCC readers don't take row locks","Only in SERIALIZABLE","Only with an index"],1,"Readers and writers don't block each other.","M"],["Main cost of 2PL?",["Data loss","Waiting and the possibility of deadlocks","Dirty reads","More disk"],1,"See 6.4.","E"]]},{"id":"t6-4","no":"6.4","title":"Deadlocks: how they happen, detection, prevention","imp":"must","quiz":[["A deadlock is…",["A slow query","A cycle of transactions each waiting for a lock another holds","A crashed transaction","A full disk"],1,"Circular wait.","E"],["Most common cause of deadlocks in apps?",["Too many indexes","Locking the same rows in different orders","Using SELECT","Large tables"],1,"A→B vs B→A.","E"],["How does the database resolve a deadlock?",["Waits forever","Rolls back one victim transaction","Commits both","Restarts the server"],1,"App must retry.","E"],["Best prevention technique?",["Bigger timeouts","Acquire locks in a consistent global order","SERIALIZABLE everywhere","Disable locking"],1,"Breaks circular wait.","M"],["Postgres runs deadlock detection…",["Before every lock","After waiting deadlock_timeout (default 1 s)","Never","Only at COMMIT"],1,"Detection is expensive, so it's delayed.","H"],["Missing indexes can increase deadlocks because…",["They don't","UPDATE/DELETE scan and lock more rows than needed","Indexes hold locks","Statistics go stale"],1,"Smaller lock footprint with good indexes.","M"]]},{"id":"t6-5","no":"6.5","title":"MVCC: row versions, snapshots, and VACUUM","imp":"must","quiz":[["In MVCC, an UPDATE…",["Overwrites the row in place, locking readers","Creates a new row version; old versions remain for older snapshots","Deletes the table","Waits for all readers"],1,"Versions, not overwrites.","E"],["MVCC's main benefit?",["Smaller tables","Readers don't block writers and writers don't block readers","No need for indexes","No transactions needed"],1,"Writers still block writers.","E"],["In Postgres, xmin is…",["The minimum value in a column","The id of the transaction that created the row version","The oldest snapshot","An index"],1,"xmax = deleter.","M"],["What does VACUUM do?",["Deletes live rows","Reclaims space from dead row versions","Rebuilds the database","Compresses the WAL"],1,"Autovacuum runs it.","E"],["A session idle in transaction for 6 hours causes…",["Nothing","VACUUM can't remove dead versions newer than its snapshot → bloat","Deadlocks only","Faster queries"],1,"Set idle_in_transaction_session_timeout.","M"],["Do two transactions updating the same row block each other under MVCC?",["No, never","Yes: the second waits for the first's row lock","Only in READ UNCOMMITTED","Only with indexes"],1,"MVCC is about readers.","M"]]},{"id":"t6-6","no":"6.6","title":"Optimistic vs pessimistic locking (version columns, FOR UPDATE)","imp":"must","quiz":[["Pessimistic locking means…",["Retrying on conflict","Locking data before using it so others wait","Never locking","Using a NoSQL store"],1,"SELECT … FOR UPDATE.","E"],["An optimistic UPDATE returns 0 rows affected. This means…",["Success","Someone else changed the row (version mismatch) → conflict","The table is empty","A deadlock"],1,"Reload and retry.","E"],["Optimistic locking suits…",["High contention on one row","Low contention, long think time (web forms)","Batch jobs only","Read-only workloads"],1,"No locks held.","M"],["The version check must be in the UPDATE's WHERE because…",["It's faster","Check-and-write in one atomic statement avoids a race","SQL requires it","It creates an index"],1,"Separate SELECT then UPDATE races.","M"],["For decrementing stock safely, the simplest correct approach is often…",["Read stock in app, write new value","UPDATE … SET stock = stock - 1 WHERE id = ? AND stock > 0","DELETE and INSERT","A cache"],1,"Atomic conditional update.","E"],["HTTP equivalent of optimistic locking?",["Cookies","ETag + If-Match (412 on mismatch)","CORS","Keep-alive"],1,"Precondition check.","M"]]},{"id":"t6-7","no":"6.7","title":"Write skew and SERIALIZABLE (snapshot isolation is not enough)","imp":"good","quiz":[["Write skew involves two transactions that…",["Update the same row","Read overlapping data and write different rows","Read uncommitted data","Deadlock"],1,"Disjoint writes, shared premise.","M"],["Why doesn't snapshot isolation catch write skew?",["It doesn't use snapshots","It only detects conflicts when two transactions write the same row","It ignores commits","It locks too much"],1,"No write-write conflict here.","M"],["Which level prevents write skew?",["READ COMMITTED","REPEATABLE READ (snapshot)","SERIALIZABLE","READ UNCOMMITTED"],2,"True serializability.","E"],["Postgres SERIALIZABLE uses…",["Table locks","Serializable Snapshot Isolation (tracking rw-dependencies)","No checks","Two-phase commit"],1,"Aborts on dangerous cycles.","M"],["At SERIALIZABLE, the application must…",["Do nothing extra","Retry transactions that fail with serialization errors","Disable indexes","Use NOLOCK hints"],1,"SQLSTATE 40001.","E"],["\"Materialising the conflict\" means…",["Creating a materialized view","Making competing transactions update a shared row so they conflict","Logging conflicts","Using a bigger server"],1,"Turns write skew into a write-write conflict.","H"]]},{"id":"t7-1","no":"7.1","title":"Write-ahead log (WAL), checkpoints and crash recovery","imp":"good","quiz":[["The WAL rule says…",["Data pages are written before log records","A change's log record must reach disk before the data page","The log is optional","Checkpoints happen on every commit"],1,"Write-ahead.","E"],["At COMMIT the database must flush…",["All data pages","The WAL up to the commit record","Nothing","The indexes"],1,"Data pages can wait.","E"],["Why are WAL-based commits fast?",["They skip durability","Log writes are sequential appends (and can be grouped)","They use RAM only","They compress data"],1,"Random page writes are deferred.","M"],["A checkpoint…",["Deletes the WAL","Flushes dirty pages and sets where recovery's redo starts","Commits all transactions","Locks the database"],1,"Bounds recovery time.","M"],["During recovery, a transaction with no COMMIT record is…",["Kept","Undone/rolled back","Committed automatically","Moved to a replica"],1,"Atomicity.","E"],["Redo during recovery replays…",["Only committed transactions","All logged changes since the last checkpoint (\"repeat history\")","Nothing","Only DDL"],1,"Then undo removes uncommitted ones (ARIES).","H"]]},{"id":"t7-2","no":"7.2","title":"Backups and point-in-time recovery (RPO, RTO)","imp":"good","quiz":[["Why isn't a replica a backup?",["Replicas are slower","Mistakes and deletes replicate to it instantly","Replicas can't be read","They have no indexes"],1,"It protects against hardware failure only.","E"],["PITR requires…",["Only nightly dumps","A base backup plus continuous WAL archive","A replica","A materialized view"],1,"Replay WAL to a target time.","E"],["RPO measures…",["Downtime","Maximum acceptable data loss (time window)","Query speed","Replication lag"],1,"Recovery point.","E"],["RTO measures…",["Maximum acceptable downtime","Data loss","Disk usage","Index size"],0,"Recovery time.","E"],["Main drawback of logical dumps for large databases?",["Not portable","Slow restore (re-insert + rebuild indexes) and only one point in time","Can't be compressed","Need superuser"],1,"Fine for small DBs or single tables.","M"],["A backup you have never restored is…",["Fine","Unverified: it may not work when needed","Faster","Encrypted"],1,"Test restores regularly.","E"]]},{"id":"t8-1","no":"8.1","title":"Replication: leader–follower, synchronous vs asynchronous, failover","imp":"must","quiz":[["In leader–follower replication, writes go to…",["Any replica","Only the primary","All nodes at once","The fastest node"],1,"Replicas apply the primary's changes.","E"],["Asynchronous replication risk?",["Slow commits","Losing recently committed transactions if the primary fails before shipping them","Dirty reads on the primary","Deadlocks"],1,"The acknowledgement gap.","E"],["Synchronous replication cost?",["Data loss","Higher commit latency; writes may stall if the sync replica is down","No read scaling","Corruption"],1,"Waits for an ack.","M"],["Do read replicas increase write capacity?",["Yes","No: every write still goes through the primary","Only with sync","Only for inserts"],1,"Sharding scales writes.","E"],["Split brain is…",["A replica with corrupted data","Two nodes both acting as primary and accepting writes","A slow failover","A network partition between replicas"],1,"Prevent with fencing/consensus.","M"],["Reading from a replica right after writing to the primary may…",["Fail","Return stale data","Deadlock","Corrupt the replica"],1,"Replication lag (8.2).","E"]]},{"id":"t8-2","no":"8.2","title":"Replication lag and consistency models: read-your-writes, monotonic reads, eventual, strong","imp":"good","quiz":[["Eventual consistency guarantees…",["Reads always see the latest write","Replicas converge if writes stop","Monotonic reads","Causality"],1,"Weakest common guarantee.","E"],["A user updates their profile and the next page shows the old data. Violated guarantee?",["Monotonic reads","Read-your-writes","Linearizability only","Durability"],1,"Their own write.","E"],["Seeing 3 comments then 2 on refresh violates…",["Read-your-writes","Monotonic reads","Atomicity","Isolation"],1,"Time went backwards.","M"],["A common fix for monotonic reads?",["Read from random replicas","Stick each user to one replica","Disable replication","Use UNION"],1,"Same replica, non-decreasing state.","M"],["Linearizability means…",["Transactions are serializable","The system behaves like a single copy: reads see the latest completed write","Data is eventually consistent","Writes are batched"],1,"Strong consistency.","M"],["Seeing an answer before its question violates…",["Consistent prefix / causal consistency","Durability","Read-your-writes","Atomicity"],0,"Cause before effect.","M"]]},{"id":"t8-3","no":"8.3","title":"Partitioning and sharding: range, hash, directory; hot spots and cross-shard queries","imp":"must","quiz":[["Main reason to shard rather than add read replicas?",["Read latency","To scale writes and storage beyond one server","Backups","Simpler queries"],1,"Replicas copy everything; writes still hit one primary.","E"],["Range sharding on an auto-increment id causes…",["Even load","A hot spot on the newest shard","Data loss","Faster joins"],1,"All new rows go to the last range.","M"],["Hash sharding's main downside?",["Hot spots","Range queries must hit all shards; modulo resharding moves most keys","Uneven distribution","No indexes"],1,"Use consistent hashing.","M"],["A query without the shard key must…",["Fail","Scatter to all shards and merge (scatter-gather)","Use the primary","Use a cache"],1,"Expensive at scale.","E"],["Partition pruning means…",["Deleting old partitions","Skipping partitions that can't contain matching rows","Compressing partitions","Splitting partitions"],1,"Based on the partition key in WHERE.","E"],["A good shard key has…",["Low cardinality","High cardinality, even distribution, and appears in most queries","Sequential values","NULLs"],1,"And co-locates related data.","M"]]},{"id":"t8-4","no":"8.4","title":"Consistent hashing: the hash ring, adding nodes, virtual nodes","imp":"must","quiz":[["With hash % N, going from 4 to 5 nodes remaps about…",["1/5 of keys","4/5 of keys","None","Exactly half"],1,"Most keys move.","E"],["In consistent hashing, a key belongs to…",["The node with the same hash","The first node clockwise from the key's position","A random node","The least loaded node"],1,"With wrap-around.","E"],["Adding a node moves keys from…",["All nodes","Only its successor's arc","No node","The previous node only after restart"],1,"About K/N keys.","M"],["Virtual nodes are used to…",["Encrypt keys","Balance load and spread a failed node's keys across many nodes","Replace replication","Reduce memory"],1,"Many positions per server.","M"],["Which system uses consistent hashing for data placement?",["SQLite","Cassandra / DynamoDB","Postgres (single node)","Excel"],1,"Dynamo-style.","E"],["Without virtual nodes, removing a node sends its load to…",["All remaining nodes evenly","Its single successor on the ring","The coordinator","Nowhere"],1,"Hence vnodes.","M"]]},{"id":"t8-5","no":"8.5","title":"CAP theorem and PACELC: consistency vs availability under partitions","imp":"must","quiz":[["In CAP, \"C\" means…",["ACID consistency","Linearizability: reads see the latest write","Constraints hold","Caching"],1,"Not ACID's C.","E"],["During a partition, a CP system…",["Returns possibly stale data","Refuses some requests to avoid inconsistency","Loses durability","Becomes CA"],1,"Minority side stops.","E"],["During a partition, an AP system…",["Refuses all requests","Keeps answering, possibly with stale or conflicting data","Guarantees linearizability","Shuts down"],1,"Reconciles later.","E"],["Why is \"CA\" not a real option for distributed databases?",["It is common","Partitions happen regardless; you can't opt out of P","CA is illegal","CA means cache"],1,"CA ≈ single node.","M"],["PACELC's \"ELC\" refers to…",["Encryption, logging, compression","Else (no partition): trade Latency vs Consistency","Eventual, linear, causal","Elections, leaders, consensus"],1,"Everyday trade-off.","M"],["Which is typically CP?",["Cassandra (consistency ONE)","etcd / ZooKeeper","DNS","A CDN cache"],1,"Consensus-based.","E"]]},{"id":"t8-6","no":"8.6","title":"Distributed transactions: two-phase commit, sagas, transactional outbox","imp":"good","quiz":[["2PC phase 1 is…",["Commit","Prepare/vote: participants durably promise they can commit","Rollback","Replication"],1,"Then commit/abort.","E"],["2PC's main weakness?",["Can't abort","Participants block (holding locks) if the coordinator fails after prepare","No atomicity","Requires NoSQL"],1,"In-doubt transactions.","M"],["A saga handles failure by…",["Rolling back a global transaction","Running compensating local transactions in reverse","Retrying forever","Locking all services"],1,"Eventual consistency.","E"],["The transactional outbox solves…",["Deadlocks","The dual-write problem between the DB and the message broker","Slow queries","Replication lag"],1,"State + event atomically.","M"],["Outbox relays deliver events…",["Exactly once by magic","At least once, so consumers must be idempotent","At most once","Never in order"],1,"Dedupe by event id.","M"],["Where should an irreversible step (sending email) go in a saga?",["First","Last, after the steps that can fail","In parallel with everything","Inside 2PC"],1,"Can't compensate it.","M"]]},{"id":"t8-7","no":"8.7","title":"Consensus and leader election: Raft in five steps","imp":"extra","quiz":[["A 5-node Raft cluster tolerates how many failed nodes?",["1","2","3","4"],1,"Needs 3 alive for a majority.","E"],["An entry is committed in Raft when…",["The leader writes it","A majority of nodes have stored it","All nodes have stored it","The client acks"],1,"Majority replication.","E"],["What triggers a Raft election?",["A client request","A follower's election timeout without hearing from a leader","A full log","Every second"],1,"Randomised timeouts.","M"],["Why are election timeouts randomised?",["Security","To make simultaneous candidacies (split votes) unlikely","To save power","To balance load"],1,"One node usually times out first.","M"],["An old leader partitioned with a minority…",["Keeps committing writes","Can't commit because it can't reach a majority","Corrupts data","Becomes leader of a new cluster"],1,"No split brain.","M"],["Which system uses Raft?",["etcd","Memcached","SQLite","Redis (standalone)"],0,"Also Consul, CockroachDB, TiKV.","E"]]},{"id":"t8-8","no":"8.8","title":"Leaderless replication and quorums: N, W, R; read repair, hinted handoff","imp":"good","quiz":[["With N = 3, W = 2, R = 2, reads see the latest write because…",["There's a leader","W + R > N, so read and write sets overlap","Writes are synchronous to all","Clocks are synchronized"],1,"Overlap argument.","E"],["N = 3, W = 1, R = 1 means…",["Always consistent","Fast and available, but reads may be stale","Writes fail if one node is down","Linearizable"],1,"1 + 1 ≤ 3.","E"],["Read repair…",["Rebuilds indexes","Writes the newest value back to replicas that returned stale data during a read","Repairs disks","Deletes tombstones"],1,"Heals frequently read keys.","M"],["Hinted handoff…",["Moves leadership","Stores writes for an unavailable replica on another node and replays them later","Encrypts hints","Is a read optimisation"],1,"With sloppy quorums.","M"],["Anti-entropy uses…",["B-trees","Merkle trees to find differing ranges efficiently","Bloom filters only","Consensus"],1,"nodetool repair.","M"],["W = N (ALL) means…",["Highest availability","Any single replica failure makes writes fail","No consistency","R must be N"],1,"Availability cost.","E"]]},{"id":"t8-9","no":"8.9","title":"Connection pooling: why, how big, and PgBouncer modes","imp":"good","quiz":[["Main benefit of a connection pool?",["Encrypts queries","Reuses connections, avoiding expensive setup and bounding concurrency","Caches results","Replicates data"],1,"Setup costs ≫ query time.","E"],["Why can a larger pool make things slower?",["It can't","More concurrent queries than cores/disks cause contention and context switching","Pools use locks","Network limits"],1,"Queue in the app instead.","M"],["A connection not returned to the pool is…",["Recycled automatically","Leaked, shrinking the pool until requests block","Faster","Committed"],1,"Return in finally.","E"],["PgBouncer transaction mode lets…",["Each client keep a server connection forever","Many clients share few server connections, one transaction at a time","Queries run without transactions","Replication"],1,"Big multiplexing gain.","M"],["What breaks under transaction pooling?",["Simple SELECTs","Session state like SET, advisory locks, LISTEN, temp tables","INSERTs","Indexes"],1,"State doesn't persist.","M"],["50 pods × pool 30 against max_connections 500…",["Fine","Exceeds the limit at peak (1,500)","Uses 30 connections","Uses 50 connections"],1,"Bound the total.","E"]]},{"id":"t8-10","no":"8.10","title":"Caching: cache-aside, write-through, invalidation, stampedes","imp":"must","quiz":[["In cache-aside, on a cache miss the app…",["Returns an error","Reads from the DB and populates the cache","Waits for the cache to fill itself","Writes to the DB"],1,"Lazy loading.","E"],["After updating the DB, the safest cache action is usually…",["SET the new value","DELETE the key","Nothing","FLUSHALL"],1,"Avoids racing writers.","M"],["Why set a TTL even when you invalidate on writes?",["Required by Redis","Safety net against missed invalidations and races","Faster reads","Saves CPU"],1,"Bounds staleness.","M"],["Write-behind caching risks…",["Slow writes","Losing writes acknowledged by the cache if it crashes before flushing","Stale reads only","Deadlocks"],1,"Async durability.","M"],["A cache stampede is…",["Too many keys","Many concurrent misses for one hot key overwhelming the DB","Memory fragmentation","Replication lag"],1,"Thundering herd.","E"],["Which mitigates stampedes?",["Longer queries","Single-flight rebuild + stale-while-revalidate + TTL jitter","Disabling TTLs","More replicas only"],1,"One rebuild per key.","E"]]},{"id":"t9-1","no":"9.1","title":"SQL vs NoSQL: data models and how to choose","imp":"must","quiz":[["Which model is best for \"friends of friends who like X\"?",["Key-value","Graph","Column store","Blob storage"],1,"Multi-hop traversals.","E"],["A key-value store is weak at…",["Lookups by key","Queries by attributes other than the key","Caching","Session storage"],1,"Get/put by key only.","E"],["In Cassandra you typically design…",["One normalized schema","One table per query pattern (denormalized)","Tables with joins","Only key-value pairs"],1,"Query-first modeling.","M"],["Document databases fit best when…",["Data is highly relational with many joins","Data forms self-contained aggregates read/written as a unit","You need multi-table ACID constantly","You need graph traversals"],1,"An order with its lines.","E"],["Strongest reason to choose a relational DB?",["Hype","Ad-hoc queries, joins, constraints and ACID transactions over related data","Unlimited write scale","No schema"],1,"General-purpose default.","E"],["Polyglot persistence means…",["Writing SQL in many languages","Using several data stores, each for its strengths","Multi-master replication","Sharding"],1,"E.g. Postgres + Redis + Elasticsearch.","M"]]},{"id":"t9-2","no":"9.2","title":"Key-value stores and Redis: data structures, TTLs, persistence","imp":"good","quiz":[["Why are Redis commands atomic?",["They use row locks","Commands execute one at a time on a single thread","They use 2PC","They aren't"],1,"No interleaving within a command.","M"],["Best structure for a real-time leaderboard?",["List","Sorted set","String","Bitmap"],1,"ZADD/ZREVRANGE.","E"],["SET key value NX PX 30000 means…",["Set always, expire in 30 s","Set only if the key doesn't exist, expire in 30 s","Set if exists","Increment by 30000"],1,"Locks/idempotency.","M"],["AOF with fsync everysec can lose about…",["Nothing","Up to ~1 second of writes","Everything","One day"],1,"Durability trade-off.","M"],["Redis is a poor fit for…",["Session storage","Ad-hoc queries over large datasets bigger than RAM","Counters","Rate limiting"],1,"In-memory key-value.","E"],["Which structure approximates distinct counts in tiny memory?",["Set","HyperLogLog","Hash","List"],1,"~12 KB, ~0.8% error.","M"]]},{"id":"t9-3","no":"9.3","title":"Document databases: embedding vs referencing, indexes, aggregation (MongoDB)","imp":"good","quiz":[["When should you embed data in a document?",["Always","When it's one-to-few, owned by the parent and read together","When it's unbounded","When it's shared across many documents"],1,"Otherwise reference.","E"],["Main risk of embedding comments in a post document?",["Slower reads","Unbounded growth (16 MB limit) and rewriting large documents","No indexes","No JSON support"],1,"Reference unbounded data.","M"],["A multikey index in MongoDB indexes…",["Multiple collections","Each element of an array field","Only keys","Two databases"],1,"Queries on any element use it.","M"],["$group in an aggregation pipeline corresponds to SQL's…",["WHERE","GROUP BY","JOIN","ORDER BY"],1,"$match = WHERE.","E"],["$lookup corresponds to…",["A LEFT JOIN","A UNION","An index","A trigger"],0,"Join between collections.","E"],["In MongoDB, a single-document update is…",["Not atomic","Atomic","Atomic only with transactions","Eventually consistent only"],1,"Even with nested fields.","M"]]},{"id":"t9-4","no":"9.4","title":"Wide-column stores (Cassandra): partition keys, clustering keys, query-first design","imp":"good","quiz":[["In PRIMARY KEY ((a), b), a is…",["The clustering key","The partition key, deciding which nodes store the row","An index","Optional"],1,"b orders rows within a.","E"],["The clustering key determines…",["Which node stores the row","The sort order of rows within a partition","Replication factor","TTL"],1,"Range queries within a partition.","E"],["Why does Cassandra reject WHERE on a non-key column by default?",["Syntax error","It would have to scan every partition on every node","Columns are encrypted","It's a bug"],1,"ALLOW FILTERING = scan.","M"],["The idiomatic way to support a second query pattern is…",["A join","Another table, denormalized for that query","A view only","A bigger cluster"],1,"Query-first.","E"],["An unbounded partition (sensor_id only) causes…",["Nothing","Huge partitions on a few nodes: hot spots, slow reads, repair problems","Faster writes","Data loss"],1,"Bucket by time.","M"],["Writes in Cassandra are cheap mainly because of…",["B-trees","LSM storage: commit log append + memtable","Joins","Locks"],1,"See 4.7.","M"]]},{"id":"t9-5","no":"9.5","title":"Graph databases: nodes, relationships, traversals (Cypher vs SQL)","imp":"extra","quiz":[["In a property graph, relationships…",["Are stored only as foreign keys","Are first-class records with a type, direction and properties","Can't have properties","Are computed at query time"],1,"FOLLOWS {since: …}.","E"],["Index-free adjacency means…",["No indexes exist","Nodes store direct references to their relationships, so each hop is a pointer follow","Edges are hashed","Joins use indexes"],1,"Cost ∝ edges touched.","M"],["A 4-hop traversal in SQL typically needs…",["One join","Four self-joins (or a recursive CTE)","A UNION","A view"],1,"One join per hop.","E"],["Neo4j's query language is…",["SQL","Cypher","CQL","MQL"],1,"Pattern matching with ASCII-art arrows.","E"],["Graph databases are a strong fit for…",["Monthly revenue reports","Fraud rings, recommendations, shortest paths","Key-value caching","Bulk log storage"],1,"Relationship-centric queries.","E"],["A super-node is…",["A powerful server","A node with an enormous number of relationships, which makes traversals through it expensive","The root node","A cluster leader"],1,"Celebrity problem.","M"]]},{"id":"t9-6","no":"9.6","title":"Full-text search: analyzers, inverted index, relevance (BM25), Elasticsearch","imp":"good","quiz":[["Why doesn't LIKE '%term%' scale?",["It's not SQL","It can't use a B-tree index (leading wildcard), so it scans; and it doesn't rank","It's case-sensitive","It returns NULL"],1,"See 4.5.","E"],["An inverted index maps…",["Documents → terms","Terms → documents containing them","Rows → pages","Keys → values"],1,"Posting lists.","E"],["Stemming turns \"laptops\" into…",["\"LAPTOPS\"","\"laptop\"","\"lap\"","\"laptopss\""],1,"Root form.","E"],["IDF gives more weight to…",["Common terms","Rare terms","Long documents","Stop words"],1,"Rare terms discriminate.","M"],["An AND query across two terms is answered by…",["Scanning all docs","Intersecting their posting lists","Hashing documents","Sorting by date"],1,"Merge of sorted lists.","M"],["Elasticsearch is usually…",["The system of record","A near-real-time search index fed from the primary database","Strongly consistent with the DB","A cache for sessions"],1,"Sync via CDC.","M"]]},{"id":"t9-7","no":"9.7","title":"Column stores, data warehouses and time-series databases","imp":"good","quiz":[["Column stores are best for…",["Single-row lookups by key","Scanning a few columns over many rows (analytics)","High-rate single-row updates","Foreign key checks"],1,"OLAP.","E"],["Why do column stores compress well?",["They use ZIP on rows","Values within a column are similar, enabling dictionary/RLE/delta encoding","They drop data","They store less precision"],1,"Homogeneous data.","E"],["A zone map lets the engine…",["Join faster","Skip blocks whose min/max can't match the filter","Update rows","Encrypt blocks"],1,"Like BRIN.","M"],["Which is NOT typically columnar?",["BigQuery","ClickHouse","Snowflake","MySQL InnoDB"],3,"InnoDB is a row store.","E"],["Downsampling in time-series DBs means…",["Deleting all old data","Aggregating old data into coarser time buckets","Sampling random rows","Compressing indexes"],1,"Keep summaries longer.","M"],["A column store's weakness?",["Large scans","Frequent single-row updates/deletes","Compression","Aggregations"],1,"Batch loads preferred.","M"]]},{"id":"t10-1","no":"10.1","title":"Scenario: design the schema for an online store","imp":"must","quiz":[["First step in a schema design interview?",["Write CREATE TABLE","Clarify requirements, scale and what must be exact","Pick NoSQL","Add indexes"],1,"Assumptions out loud.","E"],["Why store unit_price on order_items?",["Faster joins","Orders must keep the price actually charged even if the product price changes","It's required by 3NF","To avoid indexes"],1,"Historical fact.","E"],["Why separate inventory from products?",["3NF requires it","Stock is updated constantly and contended; product details are read-mostly","To save space","For security"],1,"Hot row isolation.","M"],["How should old products referenced by orders be removed?",["DELETE CASCADE","Soft delete (active = false)","TRUNCATE","Drop the FK"],1,"History stays valid.","E"],["Index for \"my orders, newest first\"?",["(created_at)","(customer_id, created_at DESC)","(status)","(id)"],1,"Equality then sort (4.4).","M"],["What prevents a double charge on payment retry?",["A CHECK","A unique idempotency key on payments","SERIALIZABLE","A trigger"],1,"See 10.5.","M"]]},{"id":"t10-2","no":"10.2","title":"Scenario: \"the orders page takes 8 seconds\" — debugging a slow query","imp":"must","quiz":[["First thing to do when paged for latency?",["Add indexes everywhere","Triage: scope, recent changes, DB saturation vs waits","Restart the database","Upgrade hardware"],1,"Method before action.","E"],["Which ranking finds the query with the biggest impact?",["Slowest single execution","Total execution time across calls","Number of joins","Query length"],1,"Mean × calls.","M"],["A plan reads 48M rows to return 20. Most likely fix?",["More RAM","An index matching the filter and sort","VACUUM FULL","Lower isolation"],1,"Access path problem.","E"],["Why CREATE INDEX CONCURRENTLY in production?",["Faster build","It doesn't block writes during the build","It uses less disk","It's required for composite indexes"],1,"Plain CREATE INDEX blocks writes.","M"],["An index on status (95% 'active') isn't used for status <> 'cancelled'. Why?",["Bug","Low selectivity: a scan is cheaper","Wrong type","Index corrupt"],1,"See 4.5.","M"],["After fixing, you should also…",["Nothing","Verify with the plan/metrics and remove indexes that are now unused","Disable autovacuum","Raise max_connections"],1,"Close the loop.","E"]]},{"id":"t10-3","no":"10.3","title":"Scenario: hot rows — like counters and a 100-unit flash sale","imp":"good","quiz":[["Why does a single counter row limit write throughput?",["Rows are small","All writers serialize on the same row lock","Indexes","Replication"],1,"Hot row.","E"],["A sharded counter…",["Uses one row","Splits the count across N rows; writes go to one, reads sum all","Requires NoSQL","Is exact only with SERIALIZABLE"],1,"÷N contention.","E"],["Buffering likes in Redis and flushing every 5 s risks…",["Overselling","Losing a few seconds of likes if Redis crashes","Deadlocks","Dirty reads in the DB"],1,"Acceptable for likes.","M"],["Flash sale correctness in the DB comes from…",["Reading stock in the app first","A guarded atomic decrement and checking affected rows","A bigger cache","READ UNCOMMITTED"],1,"WHERE remaining > 0.","E"],["Purpose of a Redis DECR gate in front of the DB?",["Durability","Reject late buyers cheaply so only potential winners hit the database","Replication","Backups"],1,"Protect the hot row.","M"],["Why idempotency keys in a flash sale checkout?",["Speed","Retries (timeouts, double clicks) must not create two orders","Encryption","Sharding"],1,"See 10.5.","M"]]},{"id":"t10-4","no":"10.4","title":"Scenario: zero-downtime schema migrations (expand → migrate → contract)","imp":"good","quiz":[["Why does renaming a column in one deploy break things?",["Renames are slow","During a rolling deploy, old app instances still use the old name","Indexes are lost","It's not SQL"],1,"Old + new code coexist.","E"],["Correct order of expand/contract?",["Drop old, add new","Add new → dual-write → backfill → switch reads → stop old writes → drop old","Backfill → add → drop","Rename then fix"],1,"Each step compatible.","E"],["Why backfill in small batches?",["SQL limits","Short transactions: brief locks, bounded WAL, replicas keep up","Faster overall","Indexes require it"],1,"Throttle too.","M"],["lock_timeout on migrations prevents…",["Deadlocks","A waiting ALTER from blocking all queries queued behind it","Replication lag","Data loss"],1,"Fail fast, retry.","M"],["Adding NOT NULL to a big Postgres table without a long lock:",["ALTER COLUMN SET NOT NULL directly","CHECK (col IS NOT NULL) NOT VALID, then VALIDATE CONSTRAINT","DROP and recreate","TRUNCATE first"],1,"VALIDATE doesn't block writes.","H"],["Building an index on a busy Postgres table:",["CREATE INDEX","CREATE INDEX CONCURRENTLY","REINDEX","VACUUM"],1,"No write blocking.","E"]]},{"id":"t10-5","no":"10.5","title":"Scenario: the double charge — idempotency keys and unique constraints","imp":"good","quiz":[["Why must clients retry, and why is that dangerous?",["They don't need to","A timeout doesn't say whether the server did the work; retrying a non-idempotent call can duplicate it","Retries are always safe","Servers block retries"],1,"Ambiguous failures.","E"],["Why doesn't \"SELECT for the key, then INSERT\" prevent duplicates?",["SELECT is slow","Two concurrent requests can both see no key and both insert","INSERT ignores constraints","Keys are random"],1,"Not atomic.","M"],["Who should generate the idempotency key?",["The server per attempt","The client, once per logical operation, reused on retries","The database sequence","The load balancer"],1,"Otherwise each retry looks new.","M"],["What enforces at most one payment per key?",["An index","A UNIQUE constraint on the key","A cache","A trigger only"],1,"Atomic in the DB.","E"],["On a duplicate key, the server should…",["Charge again","Return the stored response from the first attempt","Delete the key","Crash"],1,"Same result for the client.","E"],["At-least-once delivery + idempotent processing gives…",["At-most-once","An exactly-once effect","Duplicates","Ordering guarantees"],1,"Dedup by message id.","M"]]}],"os":[{"id":"t0-1","no":"0.1","title":"What an operating system does","imp":"must","quiz":[["The kernel is…",["The shell","The privileged core of the OS that manages hardware","A C library","The bootloader"],1,"It runs in kernel mode and is always resident.","E"],["How does a user program ask the OS to write to a file?",["Writes to the disk controller directly","A system call","Calls the scheduler","Edits the page table"],1,"System calls are the only entry into the kernel.","E"],["Which is NOT a core OS abstraction?",["Process","File","Virtual address space","Spreadsheet"],3,"Spreadsheets are applications.","E"],["What lets the OS regain the CPU from a program stuck in a loop?",["The program yielding","A hardware timer interrupt","The disk","The C library"],1,"Timer interrupts make preemption possible.","M"],["Multiprogramming mainly improves…",["Security","CPU utilisation","Disk capacity","Screen resolution"],1,"Run something else while one program waits for I/O.","M"],["Why are a process's memory addresses not physical RAM addresses?",["Performance only","They are virtual and translated by the MMU, which gives isolation","RAM has no addresses","The compiler randomises them"],1,"Virtual memory isolates processes.","M"]]},{"id":"t0-2","no":"0.2","title":"User mode, kernel mode and system calls","imp":"must","quiz":[["Why do CPUs have a user mode and a kernel mode?",["Speed","To stop programs from executing instructions that could take over the machine","To save power","For debugging only"],1,"Protection.","E"],["A system call is entered via…",["An ordinary function call","A trap instruction such as syscall","A device interrupt","A signal"],1,"Synchronous, deliberate trap.","E"],["Where does the syscall number usually go on x86-64 Linux?",["The stack","rax","A file","The page table"],1,"Arguments in rdi, rsi, rdx, r10, r8, r9.","M"],["printf is…",["A system call","A library function that eventually calls write()","A kernel thread","An interrupt"],1,"Library vs syscall.","E"],["What does the kernel do first with syscall arguments?",["Trust them","Validate them","Ignore them","Send them to the scheduler"],1,"Never trust user input.","M"],["Which reduces syscall overhead?",["Smaller buffers","Batching work into fewer, larger calls","More threads","Disabling caching"],1,"Fewer crossings.","M"]]},{"id":"t0-3","no":"0.3","title":"Interrupts, traps and exceptions","imp":"good","quiz":[["A hardware timer firing is a(n)…",["Exception","Interrupt","System call","Signal handler"],1,"Asynchronous, from hardware.","E"],["A page fault is a(n)…",["Interrupt from the disk","Exception caused by the current instruction","System call","Abort always"],1,"Synchronous, usually recoverable.","E"],["The interrupt vector table maps…",["Files to inodes","Interrupt/exception numbers to handler addresses","Pages to frames","PIDs to processes"],1,"Hardware indexes it.","E"],["Device interrupts mainly save the CPU from…",["Crashing","Polling devices in a loop","Paging","Scheduling"],1,"Event-driven instead of busy-waiting.","M"],["After a page fault is handled, the faulting instruction…",["Is skipped","Re-executes","Is killed","Moves to another CPU"],1,"That's what makes it a fault.","M"],["Preemptive scheduling depends on…",["System calls","Timer interrupts","DMA","Signals"],1,"The timer returns control to the kernel.","M"]]},{"id":"t0-4","no":"0.4","title":"Kernel architectures: monolithic, microkernel, hybrid","imp":"good","quiz":[["Linux is a…",["Microkernel","Monolithic kernel with loadable modules","Exokernel","Unikernel"],1,"Modules still run in kernel space.","E"],["A microkernel keeps in kernel space…",["Everything","Only essentials like IPC, scheduling, address spaces","Only drivers","Nothing"],1,"Minimal privileged core.","E"],["The main advantage of a microkernel is…",["Raw speed","Fault isolation and a small trusted code base","Fewer processes","No IPC"],1,"Isolation.","E"],["The main cost of a microkernel is…",["More IPC and mode switches","No drivers","No multitasking","Large kernel size"],0,"Messages between servers.","M"],["Windows NT and macOS XNU are usually called…",["Monolithic","Hybrid","Microkernels","Exokernels"],1,"Microkernel structure, services in kernel for speed.","M"],["A buggy driver in a monolithic kernel can…",["Only crash itself","Crash or compromise the whole system","Never run","Only slow the system"],1,"Full privilege.","M"]]},{"id":"t0-5","no":"0.5","title":"Booting: from power-on to the first process","imp":"extra","quiz":[["The first code the CPU runs at power-on is…",["The kernel","Firmware (UEFI/BIOS) in ROM/flash","The shell","GRUB from RAM"],1,"RAM is empty.","E"],["The bootloader's job is to…",["Run apps","Load the kernel (and initramfs) into memory and start it","Test RAM","Manage processes"],1,"GRUB, systemd-boot.","E"],["PID 1 is…",["The kernel","The first user process, ancestor of all others","The bootloader","A zombie"],1,"systemd or init.","E"],["initramfs exists to…",["Store user files","Provide drivers/tools to mount the real root file system","Replace the kernel","Speed up the CPU"],1,"Early boot helper.","M"],["Who adopts orphaned processes?",["The kernel","PID 1 (or a subreaper)","The shell","Nobody"],1,"And reaps them.","M"],["Secure Boot verifies…",["User passwords","Signatures of the bootloader and kernel","Disk speed","Network"],1,"Chain of trust.","M"]]},{"id":"t1-1","no":"1.1","title":"The process: PCB and address-space layout","imp":"must","quiz":[["Program vs process:",["Same thing","A program is a file; a process is a running instance of it","A process is a file","Programs run inside threads"],1,"Many processes can run one program.","E"],["malloc'd memory comes from the…",["Stack","Heap","Text segment","BSS"],1,"Heap grows up.","E"],["Local variables live on the…",["Heap","Stack","Data segment","Disk"],1,"In the function's frame.","E"],["The text segment is usually…",["Writable","Read-only and executable","Zero-filled","On the heap"],1,"Code shouldn't change.","M"],["Uninitialised globals go in…",["Data","BSS","Stack","Heap"],1,"Zero pages, no file space.","M"],["Which is NOT normally in a PCB?",["PID","Saved registers","Open file table","The program's source code"],3,"Source code isn't part of a process.","M"]]},{"id":"t1-2","no":"1.2","title":"Process states and the lifecycle","imp":"must","quiz":[["A process waiting for a disk read is in state…",["Ready","Running","Waiting/blocked","Terminated"],2,"Blocked on an event.","E"],["A process preempted by the timer goes to…",["Waiting","Ready","Terminated","New"],1,"It can still run.","E"],["How many processes can be running at once on a 4-core CPU?",["1","Up to 4","Unlimited","2"],1,"One per core.","E"],["When an awaited I/O completes, the process moves to…",["Running","Ready","Terminated","New"],1,"Must be dispatched first.","M"],["Which transition is impossible?",["Running → waiting","Waiting → ready","Ready → waiting","Running → ready"],2,"Only a running process can block.","M"],["In Linux ps, state D means…",["Dead","Uninterruptible sleep (usually I/O)","Daemon","Debugging"],1,"Can't be killed until the I/O ends.","M"]]},{"id":"t1-3","no":"1.3","title":"fork, exec and wait: creating processes","imp":"must","quiz":[["fork() returns in the parent…",["0","The child's pid","The parent's pid","-1 always"],1,"Child gets 0.","E"],["After a successful exec, the code after the exec call…",["Runs once","Never runs","Runs in the parent","Runs twice"],1,"The program has been replaced.","E"],["exec keeps the…",["Heap","Stack","Process ID and open file descriptors","Old code"],2,"Same process, new program.","M"],["fork(); fork(); results in how many processes total?",["2","3","4","8"],2,"2² = 4.","E"],["A parent that never calls wait leaves…",["Orphans","Zombies","Deadlocks","Threads"],1,"Exited children can't be fully removed.","M"],["Copy-on-write fork means…",["All memory copied at fork","Pages are shared until one process writes, then copied","Nothing is shared","Only code is copied"],1,"Makes fork cheap.","M"]]},{"id":"t1-4","no":"1.4","title":"Zombies, orphans and signals","imp":"must","quiz":[["A zombie process is…",["Using 100% CPU","Terminated but not yet reaped by its parent","An orphan","Stopped with SIGSTOP"],1,"Status waits for wait().","E"],["An orphan is adopted by…",["The kernel scheduler","PID 1 (or a subreaper)","Its sibling","Nobody"],1,"Reparenting.","E"],["kill -9 on a zombie…",["Removes it","Has no effect","Kills its parent","Reboots"],1,"It's already dead.","E"],["Which signal cannot be caught?",["SIGTERM","SIGINT","SIGKILL","SIGCHLD"],2,"Also SIGSTOP.","M"],["The parent is notified of a child's exit by…",["SIGTERM","SIGCHLD","SIGSEGV","SIGHUP"],1,"Default action: ignore.","M"],["Why can many zombies break a system?",["They use all RAM","They hold pids, so fork can fail when pids run out","They hold locks","They use CPU"],1,"PID exhaustion.","M"]]},{"id":"t1-5","no":"1.5","title":"Context switching: saving and restoring a process","imp":"must","quiz":[["During a context switch the kernel saves…",["Only the PC","The CPU registers, PC, SP and flags of the old process","The whole RAM","The disk"],1,"Into the PCB/kernel stack.","E"],["Switching to a different process also requires…",["Rebooting","Switching the page table (address space)","Recompiling","Closing files"],1,"CR3 on x86.","E"],["Which is cheaper?",["Process switch","Thread switch within the same process","They're identical","Neither happens"],1,"No address-space change.","M"],["An indirect cost of context switching is…",["Disk wear","Cache and TLB misses after the switch","Lost files","More RAM"],1,"Cold caches.","M"],["A system call by itself is…",["Always a context switch","A mode switch; a context switch only if the process blocks or is preempted","Impossible","A page fault"],1,"Don't confuse the two.","M"],["vmstat's cs column shows…",["CPU speed","Context switches per second","Cache size","Swap"],1,"Watch for spikes.","E"]]},{"id":"t1-6","no":"1.6","title":"IPC: pipes, shared memory, message queues, sockets","imp":"must","quiz":[["A pipe is…",["Bidirectional","A one-way kernel buffer between processes","Shared memory","A network socket"],1,"Use two pipes or a socketpair for two-way.","E"],["The fastest IPC mechanism is usually…",["Pipes","Shared memory","Signals","Files"],1,"No copying, no syscalls per access.","E"],["Shared memory requires…",["Nothing else","Explicit synchronisation (mutex/semaphore)","A network","Root"],1,"Races otherwise.","E"],["A pipe reader gets EOF when…",["The buffer is empty","All write ends are closed and the buffer is empty","The writer sleeps","Never"],1,"Close unused ends!","M"],["Which IPC works across machines?",["Pipes","Shared memory","Sockets","Signals"],2,"TCP/UDP sockets.","M"],["ls | wc runs ls and wc…",["One after the other","Concurrently, connected by a pipe","In the same process","Only if wc starts first"],1,"Pipelines are concurrent.","M"]]},{"id":"t2-1","no":"2.1","title":"Threads vs processes","imp":"must","quiz":[["Threads of the same process share…",["Stacks","Registers","The heap and globals","Program counters"],2,"Each has its own stack, regs, PC.","E"],["Each thread has its own…",["Heap","Address space","Stack","Open file table"],2,"For its function frames.","E"],["Creating a thread vs a process is usually…",["Slower","Much cheaper","Identical","Impossible on Linux"],1,"No address-space copy.","E"],["If one thread segfaults…",["Only it dies","The whole process dies","Nothing happens","The OS reboots"],1,"Shared fate.","M"],["pthread_join is analogous to…",["fork","exec","wait","kill"],2,"Wait for completion.","M"],["Why do threads need locks more than processes?",["They don't","They share memory by default, so concurrent writes can race","Locks are faster","Processes can't use locks"],1,"Sharing → races.","M"]]},{"id":"t2-2","no":"2.2","title":"User threads vs kernel threads: 1:1, N:1, M:N","imp":"good","quiz":[["User-level threads are scheduled by…",["The kernel","A runtime/library in user space","The CPU","The disk"],1,"Kernel is unaware.","E"],["In many-to-one, a blocking syscall…",["Blocks one thread","Blocks all user threads of the process","Is impossible","Speeds up"],1,"One kernel thread.","E"],["Linux pthreads are…",["N:1","1:1","M:N","Not threads"],1,"NPTL.","E"],["Go goroutines use…",["1:1","N:1","M:N","Processes"],2,"GOMAXPROCS kernel threads.","M"],["Java virtual threads mainly help…",["CPU-bound code","I/O-bound code with high concurrency","GPU code","Startup time"],1,"Waiting is cheap.","M"],["A drawback of 1:1 is…",["No parallelism","Each thread is relatively expensive","One block blocks all","No preemption"],1,"Kernel structures, big stacks.","M"]]},{"id":"t2-3","no":"2.3","title":"Concurrency vs parallelism, thread pools and Amdahl's law","imp":"good","quiz":[["Concurrency on a single core is…",["Impossible","Possible by interleaving tasks","The same as parallelism","Only for GPUs"],1,"Time slicing.","E"],["Parallelism requires…",["Threads only","Multiple execution units (cores)","A thread pool","Async I/O"],1,"Simultaneous execution.","E"],["A thread pool's main benefit is…",["Unlimited threads","Reusing a bounded set of threads instead of creating one per task","Removing locks","Faster CPUs"],1,"Bounded resources.","E"],["For CPU-bound tasks, a good pool size is about…",["1","The number of cores","1000","Number of tasks"],1,"More just adds switching.","M"],["Amdahl's law says speedup is limited by…",["Memory","The serial fraction of the program","Disk speed","The compiler"],1,"1/(1−p).","M"],["With p = 0.5, the maximum possible speedup is…",["2×","4×","10×","Unlimited"],0,"1/(1−0.5).","M"]]},{"id":"t3-1","no":"3.1","title":"Scheduling criteria and FCFS (the convoy effect)","imp":"must","quiz":[["Turnaround time is…",["Burst time","Completion − arrival","Start − arrival","Waiting + arrival"],1,"Total time in the system.","E"],["Waiting time equals…",["Turnaround − burst","Completion − burst","Burst − arrival","Response time always"],0,"Time spent ready, not running.","E"],["FCFS is…",["Preemptive","Non-preemptive","Priority-based","Random"],1,"Runs to completion or block.","E"],["The convoy effect means…",["Processes crash together","Short processes wait behind a long one","Too many context switches","Deadlock"],1,"Order-sensitive waiting.","M"],["Response time is most important for…",["Batch payroll","Interactive applications","Backups","Compilers"],1,"Users notice the first reaction.","M"],["FCFS with jobs 10, 1, 1 (all at 0) has average waiting…",["1","7","10","3.67"],1,"(0 + 10 + 11)/3 = 7.","M"]]},{"id":"t3-2","no":"3.2","title":"Shortest job first (SJF) and shortest remaining time (SRTF)","imp":"must","quiz":[["SJF picks the process with…",["Earliest arrival","Shortest next CPU burst","Highest priority","Most memory"],1,"Shortest job.","E"],["SRTF is…",["Non-preemptive SJF","Preemptive SJF","Round robin","FCFS"],1,"Shortest remaining time first.","E"],["SJF/SRTF minimise…",["Response time for long jobs","Average waiting time","Context switches","Memory use"],1,"Provably optimal.","E"],["The main practical problem with SJF is…",["Too slow","Burst lengths aren't known in advance","Needs more memory","Can't handle arrivals"],1,"Must be predicted.","M"],["Which can starve?",["FCFS","SRTF","Round robin","All equally"],1,"Long jobs behind a stream of short ones.","M"],["In SRTF, a new process with burst 3 arrives while the current one has 5 left. The scheduler…",["Ignores it","Preempts the current process","Kills the current process","Waits for a timer"],1,"3 < 5.","M"]]},{"id":"t3-3","no":"3.3","title":"Priority scheduling, starvation and aging","imp":"must","quiz":[["Priority scheduling picks…",["Shortest job","The highest-priority ready process","The oldest process","Randomly"],1,"By definition.","E"],["The main problem with priority scheduling is…",["Convoy effect","Starvation of low-priority processes","Too many switches","Thrashing"],1,"Indefinite blocking.","E"],["Aging…",["Lowers priority over time","Raises the priority of processes that have waited long","Kills old processes","Is a memory technique"],1,"Prevents starvation.","E"],["SJF is priority scheduling with priority =…",["Arrival time","Predicted next burst","Process size","PID"],1,"Shorter = higher.","M"],["In Unix, nice 19 means…",["Highest priority","Lowest priority (most \"nice\" to others)","Real-time","Root only"],1,"−20 is most favoured.","M"],["In preemptive priority, a higher-priority arrival…",["Waits for the running one","Preempts the running process","Is rejected","Runs on another machine"],1,"Immediately.","M"]]},{"id":"t3-4","no":"3.4","title":"Round robin and choosing the time quantum","imp":"must","quiz":[["Round robin is…",["Non-preemptive","Preemptive with a fixed time quantum","Priority-only","SJF"],1,"Timer-driven slices.","E"],["With a very large quantum, RR behaves like…",["SJF","FCFS","Priority","MLFQ"],1,"No preemption happens.","E"],["A very small quantum causes…",["Starvation","High context-switch overhead","Convoy effect","Deadlock"],1,"Overhead dominates.","E"],["RR's main strength is…",["Minimum turnaround","Fairness and good response time","No context switches","Optimal waiting"],1,"Everyone gets turns.","M"],["With n processes and quantum q, the maximum wait before a process runs is…",["q","n·q","(n−1)·q","Unbounded"],2,"Bounded wait.","M"],["Can RR starve a process?",["Yes, often","No","Only with priorities","Only on multicore"],1,"Everyone cycles.","M"]]},{"id":"t3-5","no":"3.5","title":"Multilevel queues and the multilevel feedback queue (MLFQ)","imp":"good","quiz":[["In MLFQ, new jobs start…",["At the bottom","At the top (highest priority)","Randomly","In the middle"],1,"Assume short until proven otherwise.","E"],["A job that uses its whole quantum is…",["Promoted","Demoted","Killed","Kept"],1,"Looks CPU-bound.","E"],["MLFQ approximates…",["FCFS","SJF without knowing burst times","Random scheduling","EDF"],1,"Short jobs finish high up.","E"],["The priority boost prevents…",["Deadlock","Starvation","Page faults","Convoy effect"],1,"Everyone returns to the top.","M"],["A multilevel queue (without feedback) differs from MLFQ because…",["It has one queue","Processes stay in a fixed queue","It's non-preemptive","It has no priorities"],1,"No movement.","M"],["Lower MLFQ levels usually have…",["Smaller quanta","Larger quanta","No quanta","Higher priority"],1,"CPU-bound jobs, fewer switches.","M"]]},{"id":"t3-6","no":"3.6","title":"Real schedulers: Linux CFS, fair share and multicore","imp":"good","quiz":[["CFS always runs the task with…",["The highest nice","The smallest virtual runtime","The oldest PID","The most memory"],1,"Least CPU received so far.","E"],["CFS keeps runnable tasks in…",["A FIFO","A red-black tree","A hash table","A stack"],1,"Ordered by vruntime.","E"],["A higher nice value…",["Gives more CPU","Gives a smaller CPU share","Makes it real-time","Pins it"],1,"Lower weight.","E"],["Why does CFS favour interactive tasks?",["Explicit heuristics","They sleep a lot, so their vruntime stays low","They have lower PIDs","They use less memory"],1,"Falls out of fairness.","M"],["Multicore Linux uses…",["One global run queue","A run queue per CPU plus load balancing","No queues","One queue per process"],1,"Scalability.","M"],["Processor affinity mainly preserves…",["Disk space","Warm caches","File handles","Priorities"],1,"Migration is costly.","M"]]},{"id":"t3-7","no":"3.7","title":"Real-time scheduling: rate-monotonic and EDF","imp":"extra","quiz":[["Hard real-time means…",["Very fast","Missing a deadline is a failure","Uses hardware threads","High throughput"],1,"Correctness depends on timing.","E"],["Rate-monotonic assigns higher priority to…",["Longer periods","Shorter periods","Larger C","Older tasks"],1,"Fixed by rate.","E"],["EDF runs the job with…",["Shortest period","Earliest absolute deadline","Highest nice","Smallest PID"],1,"Dynamic priority.","E"],["EDF on one CPU is guaranteed to meet all deadlines when U ≤…",["0.69","0.83","1.0","2.0"],2,"Optimal.","M"],["The RM bound for two tasks is about…",["0.5","0.69","0.83","1.0"],2,"2(√2 − 1).","M"],["Utilisation of a task with C=5, T=20 is…",["0.25","4","0.2","5"],0,"5/20.","E"]]},{"id":"t4-1","no":"4.1","title":"Race conditions and the critical-section problem","imp":"must","quiz":[["A race condition occurs when…",["Threads run too fast","The result depends on the timing/interleaving of threads","A thread deadlocks","The CPU overheats"],1,"Nondeterministic outcome.","E"],["count++ in C compiles to roughly…",["One atomic instruction","Load, add, store","A system call","A lock"],1,"Read-modify-write.","E"],["A critical section is…",["A kernel function","Code that accesses shared data","A crash handler","A CPU mode"],1,"Must be protected.","E"],["Which is NOT a critical-section requirement?",["Mutual exclusion","Progress","Bounded waiting","Highest throughput"],3,"Throughput is nice, not required.","M"],["Bounded waiting prevents…",["Deadlock only","Starvation of a waiting thread","Context switches","Page faults"],1,"Limit on bypasses.","M"],["Can a race occur on a single-core CPU?",["No","Yes, via preemption between instructions","Only with SMT","Only in the kernel"],1,"Interleaving needs no parallelism.","M"]]},{"id":"t4-2","no":"4.2","title":"Peterson's algorithm and hardware atomics (TAS, CAS)","imp":"good","quiz":[["Peterson's algorithm works for…",["Any number of threads","Two threads","Only processes","Only kernels"],1,"Classic 2-thread solution.","E"],["Test-and-set atomically…",["Reads a value","Sets a flag to true and returns its old value","Adds one","Locks memory forever"],1,"Basis of spinlocks.","E"],["Compare-and-swap writes the new value only if…",["The lock is free","The current value equals the expected value","It's the first call","The thread has priority"],1,"Conditional atomic update.","E"],["Why can Peterson's fail on modern multicore CPUs?",["It's too slow","Memory operations can be reordered/delayed (store buffers)","It uses too much memory","It needs interrupts"],1,"Needs fences.","M"],["Peterson's turn variable ensures…",["Speed","Only one thread wins when both want in","Fairness only","Deadlock"],1,"Last writer yields.","M"],["Atomic fetch-and-add is useful for…",["File I/O","Lock-free counters","Paging","Scheduling"],1,"Indivisible increment.","M"]]},{"id":"t4-3","no":"4.3","title":"Mutex locks and spinlocks","imp":"must","quiz":[["A mutex guarantees…",["Speed","Only one thread in the critical section at a time","No context switches","Fair scheduling"],1,"Mutual exclusion.","E"],["A spinlock's waiter…",["Sleeps","Busy-waits in a loop","Is killed","Moves to another core"],1,"Burns CPU.","E"],["Spinlocks are a good choice when…",["Critical sections are long","Holds are very short and there are multiple cores","On a single core","While doing disk I/O"],1,"Spin < sleep cost.","M"],["An uncontended futex lock…",["Always makes a syscall","Needs no syscall (atomic in user space)","Sleeps","Spins forever"],1,"Kernel only on contention.","M"],["Who may unlock a mutex?",["Any thread","Its owner","The kernel only","The last waiter"],1,"Ownership.","E"],["Why use try/finally around a lock?",["Speed","To release it even if an exception is thrown","Required by the compiler","To make it reentrant"],1,"Avoid leaked locks.","M"]]},{"id":"t4-4","no":"4.4","title":"Semaphores: counting, binary and signalling","imp":"must","quiz":[["sem_wait on a semaphore with value 0…",["Returns an error","Blocks until another thread signals","Sets it to -1 and continues","Kills the thread"],1,"Wait for a unit.","E"],["A counting semaphore initialised to 5 allows…",["Unlimited threads","Up to 5 threads in at once","1 thread","0 threads"],1,"N resources.","E"],["Signal (V) does…",["Decrement","Increment and wake a waiter","Nothing if nobody waits","Reset to 0"],1,"Remembered if nobody waits.","E"],["To make thread B wait for thread A's event, initialise the semaphore to…",["1","0","N","-1"],1,"B blocks until A signals.","M"],["Key difference between a mutex and a binary semaphore?",["Speed","A mutex has an owner; a semaphore can be signalled by any thread","Semaphores can't block","None"],1,"Ownership.","M"],["If signal happens before wait, the waiter…",["Blocks forever","Passes immediately (count was raised)","Crashes","Waits for the next signal"],1,"State persists.","M"]]},{"id":"t4-5","no":"4.5","title":"Monitors and condition variables","imp":"must","quiz":[["pthread_cond_wait(&cv, &m)…",["Spins","Atomically unlocks m and sleeps; relocks m before returning","Locks m","Signals other threads"],1,"Atomic release + sleep.","E"],["Why wait in a while loop?",["Style","The condition may be false again by the time the thread runs (Mesa, spurious wakeups)","To avoid locking","Faster"],1,"Re-check.","E"],["notifyAll() wakes…",["One thread","All threads waiting on that object","All threads in the JVM","Nobody"],1,"Broadcast.","E"],["A monitor is…",["A debugger","A lock plus condition variables plus the data they protect","A hardware timer","A type of semaphore"],1,"High-level sync construct.","M"],["If signal is called with no waiters…",["The next wait returns immediately","Nothing happens (signal is lost)","Deadlock","Error"],1,"CVs have no memory.","M"],["In Java, calling wait() without holding the object's lock…",["Works","Throws IllegalMonitorStateException","Deadlocks","Is ignored"],1,"Must be in synchronized.","M"]]},{"id":"t4-6","no":"4.6","title":"Producer–consumer: the bounded buffer","imp":"must","quiz":[["In the bounded buffer, \"empty\" is initialised to…",["0","N","1","-1"],1,"All slots free.","E"],["\"full\" is initialised to…",["0","N","1","N-1"],0,"No items yet.","E"],["A producer finding the buffer full…",["Overwrites","Blocks on empty","Spins on mutex","Exits"],1,"Waits for space.","E"],["Why must the producer wait on empty before the mutex?",["Speed","Otherwise it can sleep holding the mutex and deadlock","Semaphores require it","To be fair"],1,"Never block while holding the lock.","M"],["The mutex protects…",["The semaphores","The buffer and its indices","The CPU","Nothing"],1,"Index updates.","M"],["A Go buffered channel behaves like…",["A mutex","A bounded buffer","A spinlock","A barrier"],1,"Blocks on full/empty.","M"]]},{"id":"t4-7","no":"4.7","title":"Readers–writers and read-write locks","imp":"good","quiz":[["Readers-writers allows…",["One reader at a time","Many readers or one writer","Many writers","Readers and writers together"],1,"Shared vs exclusive.","E"],["In the classic solution, the first reader…",["Does nothing special","Acquires the write lock on behalf of all readers","Blocks other readers","Signals writers"],1,"Locks out writers.","E"],["Readers-preference can starve…",["Readers","Writers","Nobody","The kernel"],1,"Readers keep overlapping.","E"],["A fair RW lock…",["Prefers readers","Serves requests roughly in arrival order","Prefers writers always","Is a spinlock"],1,"No starvation.","M"],["RW locks are NOT worth it when…",["Reads dominate","Critical sections are tiny or writes are frequent","There are many cores","Data is large"],1,"Overhead.","M"],["Two readers both trying to upgrade to write locks…",["Works","Can deadlock","Is faster","Starves writers"],1,"Each waits for the other.","M"]]},{"id":"t4-8","no":"4.8","title":"Dining philosophers","imp":"good","quiz":[["The naive dining philosophers solution can…",["Never fail","Deadlock when all pick up their left fork","Only starve","Crash the OS"],1,"Circular wait.","E"],["Resource ordering prevents deadlock by breaking…",["Mutual exclusion","Circular wait","Preemption","Fairness"],1,"No cycle possible.","E"],["With 5 forks, allowing at most how many philosophers to try at once avoids deadlock?",["5","4","2","1 only"],1,"N−1.","E"],["Try-lock + immediate retry by everyone can cause…",["Deadlock","Livelock","Page faults","Priority inversion"],1,"Busy but no progress.","M"],["The problem models…",["Disk scheduling","Processes needing multiple shared resources","Paging","Booting"],1,"Multi-lock acquisition.","M"],["A deadlock-free solution may still allow…",["Mutual exclusion violations","Starvation of one philosopher","Two philosophers sharing a fork","Nothing bad"],1,"Fairness is separate.","M"]]},{"id":"t5-1","no":"5.1","title":"Deadlock: the four conditions and resource-allocation graphs","imp":"must","quiz":[["Which is NOT a necessary condition for deadlock?",["Mutual exclusion","Hold and wait","Preemption","Circular wait"],2,"It's NO preemption.","E"],["In a RAG, an edge from resource R to thread T means…",["T requests R","R is assigned to (held by) T","T released R","R is free"],1,"Assignment edge.","E"],["With single-instance resources, a cycle in the RAG means…",["Possible deadlock","Deadlock","No deadlock","Starvation"],1,"Necessary and sufficient.","E"],["With multi-instance resources, a cycle means…",["Certain deadlock","Deadlock is possible, not certain","No deadlock","A bug in the graph"],1,"Others may release.","M"],["The most practical way to prevent lock deadlocks in code is…",["More threads","A consistent global lock order","Larger timeouts","Fewer CPUs"],1,"Breaks circular wait.","M"],["Minimum number of threads for a lock deadlock?",["1 (self-deadlock on a non-reentrant lock)","3","4","5"],0,"Or 2 with two locks.","M"]]},{"id":"t5-2","no":"5.2","title":"Deadlock prevention: break one condition","imp":"must","quiz":[["Global lock ordering prevents deadlock by breaking…",["Mutual exclusion","Hold and wait","No preemption","Circular wait"],3,"No cycle possible.","E"],["Requesting all resources at once breaks…",["Circular wait","Hold and wait","Mutual exclusion","Preemption"],1,"Never hold while waiting.","E"],["Spooling a printer breaks…",["Mutual exclusion (from the clients' view)","Circular wait","No preemption","Starvation"],0,"Clients share the spool queue.","M"],["Releasing held locks when a request fails breaks…",["No preemption","Mutual exclusion","Circular wait","Bounded waiting"],0,"Voluntary preemption.","E"],["A drawback of all-at-once allocation is…",["Deadlocks","Low utilisation and needing to know needs in advance","Livelock","Race conditions"],1,"Resources idle while held early.","M"],["Try-lock + immediate retry by all threads risks…",["Deadlock","Livelock","Data races","Page faults"],1,"Add random back-off.","M"]]},{"id":"t5-3","no":"5.3","title":"Deadlock avoidance: safe states and the Banker's algorithm","imp":"must","quiz":[["Need equals…",["Max + Allocation","Max − Allocation","Available − Max","Allocation − Available"],1,"Remaining claim.","E"],["A safe state guarantees…",["Deadlock","That all processes can finish in some order","No waiting","Maximum throughput"],1,"At least one safe sequence.","E"],["An unsafe state…",["Is always deadlocked","May lead to deadlock","Is impossible","Is always safe later"],1,"No guarantee.","E"],["The Banker's algorithm requires processes to…",["Run in order","Declare their maximum resource needs in advance","Use one resource","Never wait"],1,"Key assumption.","M"],["When a request leads to an unsafe state, Banker's…",["Grants it","Makes the process wait","Kills the process","Reboots"],1,"Even if resources are free.","M"],["Time complexity of the safety algorithm is about…",["O(1)","O(n)","O(m·n²)","O(2ⁿ)"],2,"n processes, m resource types.","M"]]},{"id":"t5-4","no":"5.4","title":"Deadlock detection and recovery","imp":"good","quiz":[["Deadlock detection uses each process's…",["Maximum need","Current outstanding request","Priority","Burst time"],1,"No advance knowledge needed.","E"],["With single-instance resources, detection looks for…",["A safe sequence","A cycle in the wait-for graph","Starvation","Free memory"],1,"Cycle ⇔ deadlock.","E"],["A common recovery method is…",["Adding RAM","Aborting a victim process/transaction","Increasing the quantum","Ignoring it"],1,"Release its resources.","E"],["Aborting all deadlocked processes is…",["Optimal","Simple but wastes work","Impossible","Used by Banker's"],1,"Lots of lost computation.","M"],["Running detection on every request…",["Is cheap","Detects immediately but is expensive","Is impossible","Prevents deadlock"],1,"Trade-off.","M"],["Victim starvation is avoided by…",["Picking randomly","Including the number of past rollbacks in the cost","Never aborting","Aborting the oldest always"],1,"Fair victim selection.","M"]]},{"id":"t5-5","no":"5.5","title":"Livelock, starvation and priority inversion","imp":"good","quiz":[["In a livelock, threads are…",["Blocked","Running but making no progress","Terminated","Sleeping forever"],1,"Busy, no progress.","E"],["Starvation means…",["No thread runs","A particular thread is indefinitely denied service","A cycle of waits","Out of memory"],1,"Others progress.","E"],["Priority inversion occurs when…",["Priorities are reversed by the user","A high-priority task waits for a resource held by a lower-priority task","All tasks have equal priority","A task lowers its own priority"],1,"Made worse by medium tasks.","E"],["Priority inheritance…",["Lowers H's priority","Temporarily raises the lock holder's priority to the waiter's","Kills M","Uses aging"],1,"Bounded waiting for H.","M"],["A good fix for livelock is…",["Fixed retry delays","Randomised back-off","More threads","Larger quantum"],1,"Breaks symmetry.","M"],["Aging addresses…",["Livelock","Starvation","Priority inheritance","Deadlock detection"],1,"Waiting improves priority.","M"]]},{"id":"t6-1","no":"6.1","title":"Logical vs physical addresses and the MMU","imp":"must","quiz":[["The CPU generates…",["Physical addresses","Logical (virtual) addresses","Disk addresses","Port numbers"],1,"MMU translates.","E"],["The MMU is…",["Software in the kernel","Hardware that translates addresses","A compiler pass","A cache"],1,"On every access.","E"],["With base and limit, the physical address is…",["limit + logical","base + logical","base × logical","logical − base"],1,"Relocation.","E"],["Accessing logical address ≥ limit causes…",["Wrap-around","A trap (addressing error / segfault)","Nothing","A page swap"],1,"Protection.","M"],["Who can change the base and limit registers?",["Any process","Only the kernel (privileged instructions)","The compiler","The MMU"],1,"Otherwise no protection.","M"],["Execution-time binding allows…",["Faster compilation","Moving a process in memory while it runs","No MMU","Smaller programs"],1,"Relocation.","M"]]},{"id":"t6-2","no":"6.2","title":"Contiguous allocation: first, best, worst fit and fragmentation","imp":"must","quiz":[["First fit chooses…",["The largest hole","The first hole that is big enough","The smallest hole","A random hole"],1,"Fast.","E"],["Best fit chooses…",["The first hole","The smallest hole that fits","The largest hole","The last hole"],1,"Least leftover.","E"],["External fragmentation is…",["Waste inside a block","Free memory split into holes too small to use","Disk errors","Paging overhead"],1,"Between allocations.","E"],["Internal fragmentation is…",["Waste inside an allocated block due to rounding up","Holes between processes","TLB misses","Swapping"],0,"Inside blocks.","M"],["Compaction requires…",["Static binding","Execution-time (dynamic) relocation","A TLB","No MMU"],1,"Processes move.","M"],["Which typically performs worst?",["First fit","Best fit","Worst fit","They're equal"],2,"Breaks up large holes.","M"]]},{"id":"t6-3","no":"6.3","title":"Paging: pages, frames and page tables","imp":"must","quiz":[["Pages and frames are…",["Different sizes","The same size","Variable size","Only on disk"],1,"Any page fits any frame.","E"],["With 4 KB pages, the offset is…",["4 bits","12 bits","20 bits","32 bits"],1,"2¹² = 4096.","E"],["Paging eliminates…",["Internal fragmentation","External fragmentation","Page faults","The TLB"],1,"No contiguity needed.","E"],["The physical address is…",["page + offset","frame number combined with the same offset","page × frame","offset only"],1,"Offset unchanged.","M"],["The dirty bit tells the OS…",["The page is invalid","The page was modified and must be written back before eviction","The page is shared","The page is executable"],1,"Saves writes for clean pages.","M"],["If a PTE's present bit is 0, an access causes…",["A TLB hit","A page fault","A segfault always","Nothing"],1,"Kernel decides.","M"]]},{"id":"t6-4","no":"6.4","title":"The TLB and effective access time","imp":"must","quiz":[["The TLB caches…",["Data","Page-table translations","Disk blocks","Instructions only"],1,"page → frame.","E"],["On a TLB miss with a one-level table, an access costs…",["1 memory access","2 memory accesses (PTE + data)","No memory access","A disk read"],1,"Plus the TLB check.","E"],["High TLB hit ratios come from…",["Large disks","Locality of reference","Many processes","Small pages"],1,"Programs reuse nearby pages.","E"],["On a context switch without ASIDs, the TLB…",["Is kept","Must be flushed","Is doubled","Is written to disk"],1,"Old translations are wrong for the new process.","M"],["Huge pages reduce TLB misses because…",["They're faster RAM","Each entry covers more memory (larger TLB reach)","They disable paging","They're cached in L1"],1,"2 MB vs 4 KB.","M"],["EAT = 0.9×120 + 0.1×220 equals…",["130","140","120","200"],0,"108 + 22.","M"]]},{"id":"t6-5","no":"6.5","title":"Multi-level, hashed and inverted page tables","imp":"good","quiz":[["Multi-level page tables mainly save…",["Time","Memory for page tables","Disk space","TLB entries"],1,"Unused regions need no tables.","E"],["x86-64 normally uses how many page-table levels?",["1","2","4","8"],2,"5 with LA57.","E"],["The cost of more levels is…",["More internal fragmentation","More memory accesses on a TLB miss","Fewer pages","No protection"],1,"One per level.","E"],["An inverted page table has one entry per…",["Virtual page","Physical frame","Process","Segment"],1,"Size ∝ RAM.","M"],["Looking up an inverted table usually requires…",["Indexing by page number","A hash on (pid, page)","A tree walk","The TLB only"],1,"It's indexed by frame.","M"],["Each level's table is sized to fit in…",["A cache line","One page","The TLB","A register"],1,"That fixes the bits per level.","M"]]},{"id":"t6-6","no":"6.6","title":"Segmentation (and segmentation with paging)","imp":"good","quiz":[["A segmented address consists of…",["Page and frame","Segment number and offset","Base and limit only","Virtual and physical"],1,"<s, d>.","E"],["Segments are…",["Fixed size","Variable size logical units","Always 4 KB","Hardware cache lines"],1,"Code, data, stack…","E"],["Pure segmentation suffers from…",["Internal fragmentation only","External fragmentation","No fragmentation","TLB thrashing"],1,"Variable-size contiguous blocks.","E"],["If offset ≥ limit…",["It wraps","The hardware traps","It goes to the next segment","Nothing"],1,"Protection.","M"],["Segmentation makes it easy to…",["Avoid fragmentation","Share and protect logical units like code","Remove the MMU","Speed up I/O"],1,"Whole segments.","M"],["Modern x86-64 Linux uses segmentation for…",["All memory protection","Little beyond FS/GS for thread-local storage","Paging","Swapping"],1,"Flat model.","M"]]},{"id":"t6-7","no":"6.7","title":"Kernel allocators: the buddy system and slab allocation","imp":"extra","quiz":[["Buddy system block sizes are…",["Arbitrary","Powers of two","Always 4 KB","Prime numbers"],1,"Easy split/merge.","E"],["When a block is freed, it merges with its buddy if…",["Any neighbour is free","Its buddy (same size, split from the same parent) is free","Memory is low","Never"],1,"Only true buddies.","E"],["The buddy system's main drawback is…",["Slow merging","Internal fragmentation from rounding up","No contiguity","External fragmentation only"],1,"Up to ~50%.","E"],["The slab allocator provides…",["Disk caching","Caches of fixed-size kernel objects","Page replacement","Swap"],1,"Per-type caches.","M"],["A buddy's address can be computed by…",["Searching a list","address XOR block size","address + 1","A hash table"],1,"Alignment trick.","M"],["Linux shows free buddy blocks per order in…",["/proc/meminfo","/proc/buddyinfo","/proc/slabinfo","/proc/swaps"],1,"slabinfo is for slabs.","M"]]},{"id":"t7-1","no":"7.1","title":"Demand paging and handling a page fault","imp":"must","quiz":[["Demand paging loads a page…",["At program start","When it is first accessed","Every second","Never"],1,"Lazily.","E"],["A page fault on a valid but non-present page leads to…",["SIGSEGV","The kernel loading the page and restarting the instruction","A reboot","Skipping the instruction"],1,"Transparent to the program.","E"],["A major page fault…",["Needs disk I/O","Needs no I/O","Is a segfault","Is a TLB miss"],0,"Minor faults don't.","E"],["Accessing an address outside any mapping causes…",["A minor fault","SIGSEGV","A major fault","Nothing"],1,"Invalid access.","M"],["During a major fault the process…",["Spins","Blocks while the disk read happens; others run","Is killed","Runs in kernel mode the whole time"],1,"I/O wait.","M"],["Even a fault rate of 1/1000 makes memory roughly…",["1% slower","Tens of times slower","Faster","Unchanged"],1,"Disk is ~10⁵× slower.","M"]]},{"id":"t7-2","no":"7.2","title":"Page replacement: FIFO, OPT, LRU and Belady's anomaly","imp":"must","quiz":[["FIFO evicts…",["The least recently used page","The page loaded earliest","The most used page","A random page"],1,"Oldest in memory.","E"],["OPT evicts the page…",["Loaded earliest","Whose next use is farthest in the future","Used least often","With the dirty bit set"],1,"Optimal, needs the future.","E"],["LRU evicts…",["The page not used for the longest time","The newest page","The biggest page","A random page"],0,"Past predicts future.","E"],["Belady's anomaly can occur with…",["LRU","OPT","FIFO","All algorithms"],2,"Not a stack algorithm.","M"],["Why is OPT not used in real OSes?",["It's too slow","It requires knowing future references","It has Belady's anomaly","It wastes memory"],1,"Benchmark only.","M"],["Galvin's 20-reference string with 3 frames: LRU faults =",["9","12","15","20"],1,"FIFO 15, OPT 9.","M"]]},{"id":"t7-3","no":"7.3","title":"LRU approximations: the clock (second-chance) algorithm","imp":"good","quiz":[["The clock algorithm uses…",["Timestamps","A reference bit per page","A future reference string","Page sizes"],1,"Set by hardware.","E"],["A page under the hand with R = 1…",["Is evicted","Has R cleared and is skipped","Is written to disk","Moves to frame 0"],1,"Second chance.","E"],["If all R bits are 1, clock behaves like…",["LRU","OPT","FIFO","Random"],2,"Full sweep, back to start.","M"],["Who sets the reference bit?",["The OS on each access","The MMU hardware on each access","The compiler","The disk"],1,"For free.","E"],["The enhanced clock prefers to evict…",["(R=1, dirty)","(R=0, clean)","(R=0, dirty)","(R=1, clean)"],1,"No write-back needed.","M"],["Clock is used because exact LRU…",["Is less accurate","Needs work on every memory access","Has Belady's anomaly","Needs the future"],1,"Too costly.","M"]]},{"id":"t7-4","no":"7.4","title":"Thrashing and the working-set model","imp":"must","quiz":[["Thrashing is…",["A CPU bug","Spending more time paging than executing","A disk failure","Deadlock"],1,"Paging dominates.","E"],["A sign of thrashing is…",["High CPU, low disk","Low CPU utilisation with the paging disk saturated","No page faults","High network use"],1,"Everyone waits on paging.","E"],["The working set is…",["All pages of a process","Pages referenced in the last Δ references","Pages on disk","The heap"],1,"Recent locality.","E"],["If the sum of working sets exceeds memory, the OS should…",["Add processes","Suspend a process","Increase the quantum","Disable paging"],1,"Reduce multiprogramming.","M"],["Page-fault-frequency control gives a process more frames when…",["Its fault rate is too low","Its fault rate is too high","It's idle","It's new"],1,"Keep the rate in a band.","M"],["Why does adding processes during thrashing make it worse?",["It doesn't","Each gets even fewer frames, so faults rise further","The CPU overheats","The TLB fills up"],1,"Positive feedback.","M"]]},{"id":"t7-5","no":"7.5","title":"Copy-on-write fork and memory-mapped files","imp":"good","quiz":[["With copy-on-write, fork…",["Copies all memory","Shares frames read-only and copies a page on first write","Shares memory writable","Swaps memory out"],1,"Lazy copying.","E"],["A write to a COW page causes…",["A segfault","A protection fault the kernel handles by copying the page","Nothing","A TLB hit"],1,"Then restart.","E"],["mmap'd file pages are loaded…",["All at mmap time","On demand via page faults","Never","Only with read()"],1,"Lazy.","E"],["MAP_SHARED writes…",["Are private","Go to the file and are visible to other mappers","Are discarded","Need root"],1,"Shared page cache.","M"],["Why is fork + exec cheap with COW?",["exec is fast","Almost no pages are copied before exec replaces the address space","The kernel skips fork","Pages are compressed"],1,"Nothing written in between.","M"],["Shared libraries use little extra RAM per process because…",["They're small","Their pages are mapped from the same page-cache frames","They're on disk","They're compressed"],1,"One copy.","M"]]},{"id":"t8-1","no":"8.1","title":"Disk structure and disk scheduling (FCFS, SSTF, SCAN, LOOK)","imp":"good","quiz":[["The dominant cost of a random HDD access is usually…",["Transfer time","Seek time","CPU time","Interrupt time"],1,"Moving the arm.","E"],["SSTF can cause…",["Deadlock","Starvation of far requests","Belady's anomaly","Thrashing"],1,"Like SJF.","E"],["SCAN is also called…",["Round robin","The elevator algorithm","Clock","Buddy"],1,"Sweep and reverse.","E"],["LOOK differs from SCAN by…",["Serving randomly","Reversing at the last request instead of the disk end","Only going up","Using priorities"],1,"No wasted travel.","M"],["C-SCAN gives more uniform waiting times because…",["It's faster","It serves in one direction and treats the disk as circular","It uses SSTF","It ignores far requests"],1,"Fairness.","M"],["For SSDs, Linux typically uses…",["SSTF","none or mq-deadline","SCAN","C-LOOK"],1,"No seek to optimise.","M"]]},{"id":"t8-2","no":"8.2","title":"Files, directories and inodes: opening /home/me/notes.txt","imp":"must","quiz":[["An inode does NOT contain…",["File size","Permissions","The file's name","Block pointers"],2,"Names live in directories.","E"],["A directory is…",["An inode type with no data","A file mapping names to inode numbers","A disk partition","A process"],1,"Name → inode.","E"],["open() returns…",["An inode number","A file descriptor","A block number","A path"],1,"Small integer per process.","E"],["To traverse /home/me you need on each directory…",["Read","Write","Execute (search) permission","Sticky bit"],2,"x on directories.","M"],["Renaming a file within the same file system is fast because…",["Data is compressed","Only directory entries change; the inode and data stay","It's cached","It's async"],1,"Same inode.","M"],["After fork, parent and child reading the same inherited fd…",["Have independent offsets","Share one offset","Can't read","Deadlock"],1,"Shared open-file object.","M"]]},{"id":"t8-3","no":"8.3","title":"File allocation: contiguous, linked (FAT), indexed and extents","imp":"good","quiz":[["Contiguous allocation suffers from…",["Slow random access","External fragmentation","Fragile pointers","No sequential speed"],1,"Like contiguous memory.","E"],["Linked allocation's main weakness is…",["External fragmentation","Slow random access","Huge index blocks","No growth"],1,"Follow the chain.","E"],["FAT stores…",["File names","The next-block pointers for all files in one table","Inodes","Extents"],1,"Cached in RAM.","E"],["A Unix inode has how many direct pointers in ext2?",["4","12","64","1024"],1,"Then indirect levels.","M"],["With 4 KB blocks and 4 B pointers, an indirect block holds…",["256","512","1024","4096"],2,"4096 / 4.","M"],["ext4 and XFS describe file data with…",["FAT","Extents","Linked lists","Bitmaps only"],1,"(start, length) runs.","M"]]},{"id":"t8-4","no":"8.4","title":"Hard links, symbolic links and file descriptors","imp":"must","quiz":[["A hard link is…",["A file containing a path","Another directory entry for the same inode","A copy of the file","A shortcut file"],1,"Same inode.","E"],["A symbolic link…",["Shares the target's inode","Is a separate file containing the target's path","Can't cross file systems","Can't dangle"],1,"Resolved by path.","E"],["rm actually…",["Erases the data","Removes a name (unlink) and decrements the link count","Moves to trash","Deletes all links"],1,"Data freed at count 0.","E"],["Hard links cannot…",["Be renamed","Cross file systems","Point to regular files","Be deleted"],1,"Inode numbers are per FS.","M"],["dup2(fd, 1) does what?",["Closes fd","Makes fd 1 refer to the same open file as fd","Duplicates the file on disk","Forks"],1,"Redirection.","M"],["After deleting a target, a symlink to it…",["Still works","Dangles","Is deleted automatically","Becomes a hard link"],1,"Path no longer resolves.","M"]]},{"id":"t8-5","no":"8.5","title":"Journaling and crash consistency","imp":"good","quiz":[["Crash consistency problems arise because…",["Disks are slow","One logical update requires several separate disk writes","CPUs crash","RAM is volatile"],1,"A crash can split them.","E"],["A file-system journal is…",["A log of user activity","A write-ahead log of pending updates","A backup","A cache"],1,"Like a database WAL.","E"],["On recovery, a journal transaction without a commit record is…",["Replayed","Discarded","Half applied","Sent to fsck"],1,"Never happened.","E"],["fsck's main drawback is…",["It loses data","Its time grows with disk size","It needs a journal","It can't fix bitmaps"],1,"Full scan.","M"],["ext4's default data mode is…",["journal","ordered","writeback","none"],1,"Data before metadata.","M"],["Does journaling replace fsync for application data?",["Yes","No","Only on SSDs","Only for directories"],1,"It guarantees FS consistency, not your data's durability.","M"]]},{"id":"t8-6","no":"8.6","title":"RAID levels and how SSDs work","imp":"extra","quiz":[["RAID 0 provides…",["Redundancy","Striping for performance, no redundancy","Mirroring","Parity"],1,"Any failure loses data.","E"],["RAID 1 is…",["Striping","Mirroring","Parity","Double parity"],1,"Two copies.","E"],["RAID 5 survives how many disk failures?",["0","1","2","n−1"],1,"Single parity.","E"],["A lost RAID 5 block is reconstructed by…",["Reading a mirror","XOR of the remaining blocks in the stripe","Checksums","Backups"],1,"Parity math.","M"],["TRIM helps SSDs by…",["Speeding up reads","Telling the drive which blocks are free so GC avoids copying dead data","Compressing data","Disabling wear levelling"],1,"Less write amplification.","M"],["Is RAID a backup?",["Yes","No: deletions and corruption are replicated","Only RAID 1","Only RAID 6"],1,"Keep real backups.","M"]]},{"id":"t9-1","no":"9.1","title":"I/O hardware: polling, interrupt-driven I/O and DMA","imp":"good","quiz":[["Polling means the CPU…",["Sleeps until an interrupt","Repeatedly checks a device status register","Uses DMA","Disables the device"],1,"Busy-waiting.","E"],["DMA lets…",["The CPU copy faster","A device transfer data to memory without the CPU copying it","Programs access disks directly","The OS skip interrupts entirely"],1,"One interrupt at the end.","E"],["Interrupt-driven I/O improves on polling by…",["Copying faster","Letting the CPU do other work while waiting","Removing device drivers","Using no interrupts"],1,"No spinning.","E"],["With DMA, the CPU…",["Copies every byte","Sets up the transfer and handles a completion interrupt","Polls continuously","Is not involved at all, ever"],1,"Setup + completion.","M"],["Cycle stealing refers to…",["Interrupt handlers","DMA using memory-bus cycles","Scheduler preemption","Page faults"],1,"Bus contention.","M"],["For a 10-million-packets-per-second NIC, Linux often…",["Interrupts per packet","Switches to polling (NAPI)","Uses programmed I/O","Drops DMA"],1,"Interrupt overhead too high.","M"]]},{"id":"t9-2","no":"9.2","title":"Blocking, non-blocking and async I/O; select, poll and epoll","imp":"must","quiz":[["A blocking read on an empty socket…",["Returns 0","Puts the thread to sleep until data arrives","Returns EAGAIN","Crashes"],1,"Default behaviour.","E"],["A non-blocking read with no data…",["Sleeps","Returns -1 with EAGAIN","Returns garbage","Closes the socket"],1,"Would block.","E"],["epoll is preferred over select for many connections because…",["It's older","It registers fds once and returns only ready ones","It blocks less","It supports files"],1,"O(ready) vs O(n).","E"],["The golden rule of an event loop is…",["Use many threads","Never block inside a handler","Always poll","Use select"],1,"One slow handler stalls everyone.","M"],["io_uring is…",["A readiness API like epoll","A completion-based async I/O interface with shared rings","A file system","A scheduler"],1,"Linux 5.1+.","M"],["nginx and Node.js handle many connections using…",["One thread per connection","Event loops over epoll/kqueue","Busy polling","fork per request"],1,"C10k solution.","M"]]},{"id":"t9-3","no":"9.3","title":"Buffering, the page cache and fsync","imp":"good","quiz":[["When write() returns, the data is typically…",["On disk","In the kernel page cache","Still in your stdio buffer","Lost"],1,"Dirty page.","E"],["fflush() moves data…",["From the page cache to disk","From the user-space buffer into the kernel","To the network","Nowhere"],1,"Calls write().","E"],["To make data survive a power failure, call…",["close()","fsync()","fflush()","free()"],1,"Durability.","E"],["The page cache…",["Only caches writes","Caches file pages in RAM for reads and writes","Is on disk","Is per process"],1,"Shared kernel cache.","M"],["O_DIRECT…",["Guarantees durability","Bypasses the page cache","Speeds up all I/O","Is a scheduler"],1,"Still need fsync.","M"],["Group commit improves…",["Latency of each commit","Durable commit throughput","Read performance","Memory use"],1,"One fsync, many transactions.","M"]]},{"id":"t10-1","no":"10.1","title":"Virtual machines and hypervisors","imp":"good","quiz":[["A hypervisor…",["Is a container runtime","Runs and isolates multiple guest operating systems","Is a shell","Is a file system"],1,"VMM.","E"],["Trap-and-emulate means…",["Every instruction is emulated","Sensitive guest instructions trap to the hypervisor, which emulates them","Guests can't run privileged code","Interrupts are ignored"],1,"Normal code runs natively.","E"],["VirtualBox is a…",["Type 1 hypervisor","Type 2 (hosted) hypervisor","Container engine","Microkernel"],1,"Runs on a host OS.","E"],["EPT / NPT provide…",["Faster disks","Hardware translation from guest-physical to host-physical memory","Network virtualization","Scheduling"],1,"Nested page tables.","M"],["virtio devices are fast because…",["They're real hardware","Guest and host exchange batches through shared rings with few VM exits","They skip the kernel","They use polling only"],1,"Paravirtual.","M"],["Compared with containers, VMs…",["Share the host kernel","Run their own kernel with stronger isolation","Start in milliseconds","Use less memory"],1,"Hardware-level isolation.","M"]]},{"id":"t10-2","no":"10.2","title":"Containers: namespaces, cgroups and layered file systems","imp":"must","quiz":[["Containers share…",["Nothing with the host","The host's kernel","The host's PID numbers","A hypervisor"],1,"It's the key difference from VMs.","E"],["Namespaces control…",["How much CPU a process uses","What a process can see (PIDs, mounts, network…)","Disk speed","Scheduling priority"],1,"Isolation of views.","E"],["cgroups control…",["File names","Resource limits and accounting","Hostnames","Image layers"],1,"CPU, memory, PIDs, I/O.","E"],["When a container exceeds memory.max…",["It's throttled","The OOM killer kills a process in the cgroup","It's paused","Swap is always used"],1,"Exit 137.","M"],["When a container exceeds its CPU quota…",["It's killed","It's throttled until the next period","It's migrated","Nothing"],1,"Latency spikes.","M"],["OverlayFS provides containers with…",["Networking","Read-only image layers plus a writable copy-on-write layer","Memory limits","PID isolation"],1,"Layered images.","M"]]},{"id":"t10-3","no":"10.3","title":"What happens when you type ./app and press Enter","imp":"must","quiz":[["The first thing that happens when you press Enter is…",["fork","A keyboard interrupt","exec","A page fault"],1,"Hardware event.","E"],["The shell creates the new process with…",["exec","fork (then exec)","mmap","clone of the kernel"],1,"Then exec in the child.","E"],["During execve, the program's code is…",["Fully read into RAM","Mapped, then loaded page by page on demand","Compiled","Copied from bash"],1,"Demand paging.","E"],["The dynamic linker ld.so…",["Compiles code","Maps shared libraries and resolves symbols before main","Schedules the process","Reaps zombies"],1,"Named by PT_INTERP.","M"],["Shared libraries load quickly because…",["They're small","Their pages are usually already in the page cache and shared","They're compiled at boot","They're on the GPU"],1,"7.5.","M"],["The shell prints the next prompt after…",["fork returns","waitpid reaps the child","exec returns","The page cache flushes"],1,"Foreground job finished.","M"]]},{"id":"t10-4","no":"10.4","title":"Debugging a slow machine: load, CPU, memory, I/O","imp":"good","quiz":[["High load average on Linux always means CPU saturation.",["True","False: it includes tasks blocked on I/O","True on SSDs","Only for VMs"],1,"D state counts.","E"],["vmstat's wa column is…",["Write activity","CPU idle time while waiting for I/O","Swap usage","Wait queue length"],1,"iowait.","E"],["iostat -x %util at 100% with a long queue suggests…",["CPU bound","A saturated disk","Too much RAM","A network issue"],1,"Utilisation + saturation.","E"],["Non-zero si/so in vmstat means…",["Network traffic","Swapping pages in/out","System interrupts","Signals"],1,"Memory pressure.","M"],["The USE method checks each resource's…",["Users, Services, Events","Utilisation, Saturation, Errors","Uptime, Swap, Entropy","Usage, Speed, Energy"],1,"Brendan Gregg.","M"],["\"free\" shows little free memory but lots of buff/cache. This is…",["A memory leak","Normal: page cache is reclaimable","Swap exhaustion","A kernel bug"],1,"Check \"available\".","M"]]}],"sd":[{"id":"/client-server","no":"W1","title":"Client–server architecture","imp":"core","quiz":[["Why should application servers be stateless?",["Stateless code runs faster on a CPU","So any instance can serve any request and instances can be added or killed freely","Because databases cannot store sessions","To avoid needing a load balancer"],1,"Statelessness makes instances interchangeable. Interchangeable instances are what make horizontal scaling and failure recovery easy.","M"],["A request passes through an LB (1ms), an app server (20ms) and a DB (8ms). The network RTT is 80ms. Roughly what latency does the user see?",["20 ms","29 ms","~110 ms","80 ms"],2,"Latencies along a path add up: 80 + 1 + 20 + 8 ≈ 109 ms.","M"]]},{"id":"/http-dns-rest","no":"W1","title":"HTTP, DNS & REST APIs","imp":"core","quiz":[["Which request is safe to retry blindly after a timeout?",["POST /payments","PUT /users/42/email with the full new value","POST /orders","POST /messages"],1,"PUT is idempotent: applying the same full replacement twice leaves the same result. POSTs need an idempotency key before they are safe to retry.","M"],["Why is cursor pagination preferred over <code>?page=N</code> for large feeds?",["Cursors are shorter strings","Offsets force the DB to scan and discard all skipped rows, and pages shift as new items arrive","Browsers cache cursors","REST forbids page numbers"],1,"OFFSET 100000 still walks 100k rows; a cursor (&quot;items after id X&quot;) uses the index to jump straight there and stays stable when new rows are inserted.","M"],["A failover DNS record has TTL 3600s. A region dies. Worst case, how long do some clients keep trying it?",["Instantly redirected","Up to ~1 hour","Exactly 60 seconds","Until the user reloads"],1,"Resolvers and clients cache the answer for the TTL. Failover records use short TTLs (30–60s) for exactly this reason.","M"]]},{"id":"/latency-throughput","no":"W1","title":"Latency vs. throughput","imp":"core","quiz":[["A service has 100 worker threads. Average request takes 50 ms. What is its maximum throughput?",["50 req/s","500 req/s","2,000 req/s","5,000 req/s"],2,"Little's law: throughput = concurrency / time = 100 / 0.05 s = 2,000 req/s.","M"],["Why do teams target ~60% utilization instead of 95%?",["Cloud providers charge more above 60%","Queueing makes latency grow sharply as utilization approaches 100%, and you need headroom for spikes","CPUs overheat","It is a Kubernetes limit"],1,"Waiting time scales roughly with 1/(1−ρ): 3× at 70%, 20× at 95%. Headroom buys predictable latency and spike absorption.","M"],["A page fans out to 20 backend calls in parallel. Each call has p99 = 100 ms. Roughly what fraction of page loads see at least one call ≥ 100 ms?",["1%","~18%","50%","99%"],1,"1 − 0.99²⁰ ≈ 18%. Tail latency compounds with fan-out, which is why p99 (or p99.9) of leaf services matters so much.","M"]]},{"id":"/scaling","no":"W1","title":"Horizontal vs. vertical scaling","imp":"core","quiz":[["Which is the strongest argument for horizontal over vertical scaling of a web tier?",["It is always cheaper per CPU","It removes the single point of failure and has no hard capacity ceiling","It needs no load balancer","It makes each request faster"],1,"Scale-out adds redundancy and keeps going past the biggest instance. Per-request speed is unchanged.","M"],["A flash sale will send 10× traffic at exactly 12:00. What helps most?",["Autoscaling on CPU with default settings","Scheduled pre-scaling before 12:00, plus a queue or rate limiter for anything beyond","A bigger database","Lower the autoscaling target to 90%"],1,"Reactive autoscaling lags minutes behind a step change. Known spikes call for scheduled scaling, with load shedding or queueing as a safety net.","M"]]},{"id":"/estimation","no":"W1","title":"Back-of-the-envelope estimation","imp":"core","quiz":[["10M DAU, each making 30 requests/day. Average QPS?",["~300","~3,000","~30,000","~300,000"],1,"10⁷ × 30 / 10⁵ = 3,000 QPS average (peak maybe 6–15k).","M"],["100M photos uploaded per day at 500 KB, stored for 5 years with 3 replicas. Storage?",["~90 TB","~900 TB","~270 PB","~270 TB"],2,"100M × 0.5 MB = 50 TB/day → ×365×5 ≈ 91 PB → ×3 ≈ 270 PB. This is why media goes to object storage with erasure coding, not databases.","M"]]},{"id":"/sql-vs-nosql","no":"W3","title":"SQL vs. NoSQL","imp":"core","quiz":[["Which workload is the strongest fit for a wide-column store like Cassandra?",["Bank transfers between accounts","Chat messages written at 200k/s, read per conversation newest-first","Ad-hoc analyst reports joining 12 tables","A product catalog with 5,000 items"],1,"Huge write volume with a single, predictable access pattern (partition = conversation, clustering = time) is exactly what wide-column stores are built for.","M"],["A Cassandra cluster has 9 nodes, RF=3, each node does ~5k writes/s. Roughly what cluster-wide write rate can it sustain?",["5k/s","15k/s","45k/s","135k/s"],1,"Each logical write lands on 3 replicas: 9 × 5k ÷ 3 = 15k writes/s.","M"]]},{"id":"/indexing-transactions","no":"W3","title":"Indexing & transactions","imp":"core","quiz":[["An index exists on (country, city, created_at). Which query can NOT use it efficiently?",["WHERE country='IN'","WHERE country='IN' AND city='Pune'","WHERE city='Pune'","WHERE country='IN' AND city='Pune' ORDER BY created_at"],2,"Leftmost-prefix rule: the index is sorted by country first; filtering only on city skips the leading column.","M"],["Two transactions each check &quot;is at least one doctor on call?&quot; (yes, two are), then each takes a doctor off call. Both commit. Which anomaly is this?",["Dirty read","Phantom read","Write skew","Lost update caused by no WAL"],2,"Each transaction read a shared condition and wrote a different row based on it. Only serializable isolation (or explicit locking of the rows read) prevents write skew.","M"],["Why not index every column?",["Databases limit tables to 3 indexes","Each index slows every write and uses storage; unused indexes are pure cost","Indexes make reads slower","Indexes break transactions"],1,"Every insert/update must maintain every affected index. Index for your actual query patterns.","M"]]},{"id":"/replication","no":"W3","title":"Replication & partitioning","imp":"core","quiz":[["Synchronous replication to a single replica. The replica crashes. What happens to writes?",["They continue at full speed","They block or fail until the replica returns or is removed from the sync set","They go to the replica","Nothing; sync only affects reads"],1,"A sync write needs every sync replica to ack. That is why semi-sync (any one of several replicas) is common.","M"],["N = 3 replicas. Which (W, R) combination guarantees reads see the latest acknowledged write?",["W=1, R=1","W=1, R=2","W=2, R=2","W=2, R=1"],2,"R + W &gt; N (2 + 2 &gt; 3) forces the read set and write set to overlap in at least one replica.","M"]]},{"id":"/sharding","no":"W3","title":"Sharding","imp":"core","quiz":[["Orders are range-sharded by auto-increment order_id. What goes wrong?",["Reads become cross-shard","All new inserts hit the last shard, which becomes a hot spot","Order IDs collide","Nothing; range sharding balances automatically"],1,"Monotonic keys map every new write to the highest range: one hot shard, N−1 idle ones.","M"],["You go from 10 to 11 shards using hash(key) mod N. Roughly how much data moves?",["~9%","~50%","~91%","0%"],2,"With mod-N, a key stays only if hash mod 10 == hash mod 11, which is true for ~1/11 of keys. Consistent hashing would move only ~1/11.","M"],["Best shard key for a multi-tenant B2B SaaS where every query is scoped to one tenant?",["created_at","tenant_id (with a plan for very large tenants)","A random UUID per row","Country"],1,"tenant_id keeps each tenant’s queries on one shard. Giant tenants may need a dedicated shard or sub-partitioning.","M"]]},{"id":"/caching","no":"W5","title":"Redis & cache invalidation","imp":"core","quiz":[["Which pattern risks losing acknowledged writes if the cache crashes?",["Cache-aside","Read-through","Write-through","Write-behind (write-back)"],3,"Write-back acknowledges before the DB has the data. Anything still buffered when the node dies is gone.","M"],["A hot key with TTL 60s expires and 5,000 requests miss simultaneously. Best mitigation?",["Increase TTL to 1 day","Request coalescing / single-flight so only one request recomputes it","Add more app servers","Disable the cache"],1,"Coalescing collapses the 5,000 concurrent misses into one DB query. Longer TTLs only delay the problem and add staleness.","M"],["With cache-aside, why delete the key on write rather than update it?",["Deletes are faster than sets","It avoids writing a value computed from a possibly stale read, and avoids caching data nobody reads","Redis does not support updates","It makes the cache write-through"],1,"Deleting lets the next reader repopulate from the source of truth. Updating in place can race with other writers and leave the cache wrong.","M"]]},{"id":"/cdn","no":"W5","title":"CDN & edge caching","imp":"core","quiz":[["You deploy a new app.js but users keep getting the old file for a day. Best fix for the future?",["Purge the CDN after every deploy","Disable CDN caching for JS","Content-hashed filenames (app.&lt;hash&gt;.js) with long TTLs","Lower TTL to 1 second"],2,"A new hash means a new URL, so there is nothing stale to purge, and the old file can stay cached forever.","M"],["Which response should NOT be cached at a shared CDN edge?",["A product image","GET /me returning the logged-in user's profile","Football scores updated every 10s","A versioned CSS bundle"],1,"Personalized responses must be private/no-store, or users could see each other’s data.","M"]]},{"id":"/load-balancing","no":"W5","title":"Load balancing","imp":"core","quiz":[["One of 4 servers is 10× slower but passes health checks. With round robin, what happens to p99?",["Unaffected: only 25% of requests are slow","p99 becomes roughly the slow server’s latency, since 25% ≫ 1%","It improves","The LB ejects the server automatically"],1,"Any server getting ≥1% of traffic defines the p99. A quarter of all requests being slow makes p99 (and p75!) slow.","M"],["Why is &quot;power of two choices&quot; popular at very large scale?",["It guarantees perfect balance","Near-optimal balance using only two random samples, so no global coordination is needed","It is the only algorithm that supports TLS","It keeps sessions sticky"],1,"Sampling two and choosing the less loaded dramatically reduces max load compared with random, without a shared view of all servers.","M"]]},{"id":"/rate-limiting","no":"W5","title":"Rate limiting","imp":"core","quiz":[["Limit: 100 req/min with a fixed window. What is the worst-case burst a client can achieve?",["100 in any 60s","~200 within a couple of seconds around the window boundary","50","Unlimited"],1,"100 at 12:00:59 plus 100 at 12:01:00, because the counter resets at the boundary.","M"],["Why return 429 quickly instead of queuing excess requests indefinitely?",["429 is cached by CDNs","Unbounded queues turn overload into timeouts for everyone, consuming resources and triggering retries; fast rejection keeps the system healthy for admitted requests","Browsers prefer 429","Queues are illegal in HTTP"],1,"Overload plus unbounded queues means everything gets slow and fails. Bounded admission keeps latency predictable for the traffic you accept.","M"]]},{"id":"/cap","no":"W7","title":"CAP theorem & PACELC","imp":"core","quiz":[["Why is &quot;CA&quot; (consistent + available, no partition tolerance) not a meaningful choice for a multi-node database?",["It is too expensive","Partitions happen whether you design for them or not; the only question is how you behave when they do","CA systems are illegal","Partition tolerance is optional on cloud providers"],1,"You cannot opt out of network failures. A single-node database is &quot;CA&quot; only because it isn’t distributed.","M"],["Which system should choose CP?",["A news feed","A like counter","A distributed lock service used for leader election","A product recommendations cache"],2,"Two leaders (split brain) is a correctness disaster. Lock/election services must refuse rather than give a wrong answer.","M"],["N=5 replicas. You want writes to survive 2 replica failures and reads to always see the latest write. Which (W, R)?",["W=1, R=5","W=3, R=3","W=5, R=1","W=2, R=2"],1,"W=3 tolerates 2 failures for writes; R=3 with W=3 gives 3+3 &gt; 5 overlap.","M"]]},{"id":"/kafka","no":"W7","title":"Kafka & message queues","imp":"core","quiz":[["A topic has 8 partitions. You run 12 consumers in one consumer group. How many actively consume?",["12","8","4","1"],1,"Each partition goes to exactly one consumer in the group, so 4 sit idle. Add partitions to scale further.","M"],["All events for one bank account must be processed in order. What should the partition key be?",["A random UUID","The event timestamp","account_id","The consumer ID"],2,"Same key → same partition → strict order for that account, while different accounts spread across partitions.","M"],["Consumers process a message, then crash before committing the offset. What happens?",["The message is lost","The message is redelivered, so consumers must be idempotent","Kafka deletes the partition","The producer resends automatically"],1,"That is at-least-once delivery. Handle duplicates with idempotency (dedupe by message ID, upserts).","M"]]},{"id":"/eventual-consistency","no":"W7","title":"Eventual consistency","imp":"core","quiz":[["A user updates their bio and immediately sees the old one. Best targeted fix?",["Make all reads go to the primary","Read-your-writes: route that user’s reads to the primary (or an up-to-date replica) briefly after their write","Increase cache TTL","Switch to last-write-wins"],1,"Routing everything to the primary throws away read scaling. Only the writer needs fresh data, right after writing.","M"],["Two offline phones add different items to the same shopping cart. With last-write-wins on sync, what happens?",["Both items are kept","One phone’s additions are silently lost","The sync fails","Duplicates are created"],1,"LWW keeps one version and discards the other. A set CRDT or union-merge would keep both.","M"]]},{"id":"/resilience","no":"W7","title":"Retries, idempotency & circuit breakers","imp":"core","quiz":[["A service has 200 threads. A dependency normally answers in 20 ms but starts hanging for 10 s. With no timeout, roughly what throughput can the service sustain?",["Unchanged (10,000 req/s)","~20 req/s","~200 req/s","0"],1,"Little's law: 200 threads / 10 s ≈ 20 req/s. A timeout of 200 ms would keep it around 1,000 req/s.","M"],["Which retry policy is best for a call to a struggling service?",["Retry immediately up to 5 times","Exponential backoff with jitter, a small retry budget, only for retryable errors","Retry forever until it works","Never retry anything"],1,"Backoff and jitter spread retries out; budgets cap amplification; and only transient errors are worth retrying.","M"],["A payment request times out at the client. What makes a retry safe?",["Waiting 10 seconds first","Sending the same idempotency key so the server returns the original result if it already processed it","Using PUT instead of POST","Retrying from a different region"],1,"The server dedupes on the key and returns the stored response, so there is no double charge.","M"]]},{"id":"/microservices","no":"W9","title":"Microservices","imp":"core","quiz":[["What is the strongest reason to split a service out of a monolith?",["Microservices are always faster","A separate team needs to deploy and scale that capability independently","To use more servers","To avoid writing tests"],1,"Independent deployment/ownership and scaling are the main benefits, and they matter most when teams are stepping on each other.","M"],["Order service and Inventory service both write to the same &quot;stock&quot; table. What is this?",["Database per service","A distributed monolith smell: shared mutable data couples them","Event sourcing","CQRS"],1,"Shared write access means schema changes and invariants span both services. One should own the table; the other uses its API or events.","M"]]},{"id":"/event-driven","no":"W9","title":"Event-driven architecture","imp":"core","quiz":[["Why not just write to the database, then publish to Kafka, in the request handler?",["Kafka is too slow","A crash between the two leaves them inconsistent (dual-write problem); an outbox makes publish part of the DB transaction","Kafka cannot store orders","It is fine; this is the recommended approach"],1,"Two independent writes can’t be atomic. The outbox (or CDC) derives the event from the committed transaction.","M"],["Three teams each need every OrderPlaced event. With Kafka, how?",["Three consumers in one consumer group","Three consumer groups subscribed to the topic","Three topics written by the producer","One consumer that calls the three teams"],1,"Each consumer group receives every message (pub/sub); within a group, partitions are split among consumers.","M"]]},{"id":"/fault-tolerance","no":"W9","title":"Fault tolerance","imp":"core","quiz":[["A request synchronously depends on 5 services, each 99.9% available (independent). Upper bound on availability?",["99.9%","~99.5%","99.99%","95%"],1,"0.999⁵ ≈ 0.995. Series dependencies multiply, which is why critical paths should have few hard dependencies.","M"],["Two app servers each run at 75% CPU. One dies. What happens?",["Nothing, they are redundant","The survivor gets ~150% load and fails too: redundancy without N+1 capacity","The load balancer adds a server","Latency halves"],1,"Redundancy only helps if the remaining capacity can absorb the load. Plan for N+1.","M"]]},{"id":"/observability","no":"W9","title":"Logging, metrics & tracing","imp":"core","quiz":[["Which is the best primary alert for an API?",["CPU above 80% on any host","SLO burn rate: error budget for availability/latency is being consumed too fast","Any ERROR log line","Disk at 50%"],1,"Alert on user-facing symptoms tied to your objective. Causes like CPU are for dashboards and diagnosis.","M"],["Why is a <code>user_id</code> label on a request-count metric a bad idea?",["It is personal data, which metrics cannot store","Cardinality explosion: one time series per user overwhelms the metrics backend","Prometheus forbids string labels","It makes counters decrease"],1,"Each label combination is a separate series. Per-user detail belongs in logs and traces.","M"]]},{"id":"/disaster-recovery","no":"W9","title":"Disaster recovery","imp":"core","quiz":[["A developer accidentally runs DELETE FROM orders. Which protects you?",["Synchronous replication to 3 replicas","Point-in-time recovery from backups / WAL archive","Multi-AZ failover","A bigger instance"],1,"Replication copies the delete everywhere instantly. You need history: PITR or snapshots.","M"],["RPO = 0 across regions requires…",["Async replication with a short lag","Writes acknowledged only after the remote region (or a cross-region quorum) has them","Hourly snapshots","A CDN"],1,"Anything acknowledged before reaching another region can be lost with the region. That costs write latency.","M"]]},{"id":"/url-shortener","no":"W11","title":"Design a URL shortener","imp":"core","quiz":[["Why might a URL shortener return 302 instead of 301?",["302 is faster","301s are cached by browsers, so later clicks never reach your servers and you lose analytics","301 is deprecated","302 uses less bandwidth"],1,"Permanent redirects get cached aggressively. If you need click counts, use 302 or short cache lifetimes.","M"],["Best way to generate unique short codes across 50 app servers?",["Each server picks random 3-char codes","Pre-allocated ID ranges (or Snowflake IDs) encoded in base62","Use the long URL’s length","A single global auto-increment row locked on every request"],1,"Ranges/Snowflake give uniqueness without per-request coordination; a single locked counter becomes a bottleneck.","M"]]},{"id":"/whatsapp","no":"W11","title":"Design WhatsApp (chat)","imp":"core","quiz":[["How does the system know which server holds a recipient’s connection?",["Broadcast the message to every gateway","A session registry mapping user_id → gateway, updated on connect/disconnect","DNS","The recipient polls every server"],1,"A fast lookup (usually an in-memory KV store) routes each message to exactly the right gateway.","M"],["What guarantees messages in one chat appear in order?",["Client timestamps","Partitioning by conversation_id and assigning a per-conversation sequence number","A global lock","Sorting by message length"],1,"A single partition per conversation gives a total order there; client clocks are unreliable.","M"]]},{"id":"/instagram","no":"W11","title":"Design Instagram (feed & media)","imp":"core","quiz":[["Why not fan out on write for an account with 300M followers?",["Followers would see the post too early","One post becomes 300M timeline writes: huge write amplification and lag for everyone","Celebrities post less","Redis cannot store that many lists"],1,"Push works when follower counts are modest. For mega-accounts, pull their posts at read time and merge (hybrid).","M"],["How should a client upload a 50 MB video?",["POST the bytes to the API server, which forwards them to storage","Get a pre-signed URL and upload directly to object storage","Send it base64 inside JSON","Email it"],1,"Direct-to-storage uploads keep app servers free of bulk bytes and scale with the storage service.","M"]]},{"id":"/youtube","no":"W11","title":"Design YouTube (video streaming)","imp":"core","quiz":[["Why split videos into small segments with multiple renditions?",["To reduce storage","So the player can adapt quality per segment to network conditions, and segments cache well on CDNs","Because browsers can’t play long files","To make uploads faster"],1,"Adaptive bitrate streaming switches quality per segment; immutable segments are ideal CDN objects.","M"],["How should view counts be updated?",["UPDATE videos SET views = views + 1 on each view","Publish view events to a stream and aggregate asynchronously in batches","Count CDN logs once a year","Store each view as a row and COUNT(*) on every page load"],1,"A hot row updated millions of times per minute is a lock bottleneck. Aggregate events and write periodically.","M"]]},{"id":"/uber","no":"W11","title":"Design Uber (ride matching)","imp":"core","quiz":[["Why keep live driver locations in memory rather than a durable SQL table?",["SQL cannot store coordinates","Updates are huge in volume, ephemeral and only the latest matters; memory handles 1M+ writes/s cheaply","Memory is more durable","Regulations require it"],1,"The live index is a cache of rapidly changing state. Durable history can be written asynchronously in batches.","M"],["How do you prevent two dispatchers from assigning the same driver?",["Hope it is rare","Atomic compare-and-set on driver state (available → offered) in a strongly consistent store","Assign by client timestamp","Let the driver pick both"],1,"A conditional update ensures only one dispatcher wins the transition.","M"]]},{"id":"/payments","no":"W11","title":"Design a payment system","imp":"core","quiz":[["A PSP call times out. What is the right next step?",["Mark the payment failed and ask the user to pay again","Retry with the same idempotency key, or query the PSP for the payment status","Retry with a new request","Refund the customer"],1,"The outcome is unknown. The same key makes the retry safe; status queries and reconciliation resolve the truth.","M"],["Why is the ledger append-only?",["Databases are faster at inserts","Every cent must be traceable: corrections are new balancing entries, never edits that erase history","Regulations forbid indexes","To save storage"],1,"Immutability plus double-entry (debits = credits) makes errors detectable and the history auditable.","M"]]},{"id":"/notifications","no":"W11","title":"Design a notification system","imp":"core","quiz":[["Why separate queues for OTP codes and marketing campaigns?",["They use different databases","So a huge campaign backlog never delays time-critical messages","Providers require it","To save money"],1,"Priority isolation keeps transactional latency low even when bulk traffic floods the system.","M"],["The email provider allows 3,000 sends/s and a broadcast needs 10,000/s. What should the system do?",["Send 10,000/s and ignore 429s","Queue and drain at ≤ 3,000/s with a rate limiter; accept minutes of lag for bulk email","Drop 70% of emails","Switch everything to SMS"],1,"You can’t exceed a provider’s quota. Smoothing through the queue avoids throttling and data loss.","M"]]}]},"algo":[["two-sum","Two Sum","Arrays & Hashing"],["valid-anagram","Valid Anagram","Arrays & Hashing"],["contains-duplicate","Contains Duplicate","Arrays & Hashing"],["majority-element","Majority Element","Arrays & Hashing"],["group-anagrams","Group Anagrams","Arrays & Hashing"],["top-k-frequent-elements","Top K Frequent Elements","Arrays & Hashing"],["product-of-array-except-self","Product of Array Except Self","Arrays & Hashing"],["longest-consecutive-sequence","Longest Consecutive Sequence","Arrays & Hashing"],["valid-palindrome","Valid Palindrome","Two Pointers"],["move-zeroes","Move Zeroes","Two Pointers"],["two-sum-ii-input-array-is-sorted","Two Sum II - Input Array Is Sorted","Two Pointers"],["sort-colors","Sort Colors","Two Pointers"],["3sum","3Sum","Two Pointers"],["container-with-most-water","Container With Most Water","Two Pointers"],["trapping-rain-water","Trapping Rain Water","Two Pointers"],["best-time-to-buy-and-sell-stock","Best Time to Buy and Sell Stock","Sliding Window"],["longest-substring-without-repeating-characters","Longest Substring Without Repeating Characters","Sliding Window"],["max-consecutive-ones-iii","Max Consecutive Ones III","Sliding Window"],["fruit-into-baskets","Fruit Into Baskets","Sliding Window"],["longest-repeating-character-replacement","Longest Repeating Character Replacement","Sliding Window"],["permutation-in-string","Permutation in String","Sliding Window"],["minimum-window-substring","Minimum Window Substring","Sliding Window"],["binary-search","Binary Search","Binary Search"],["search-insert-position","Search Insert Position","Binary Search"],["find-minimum-in-rotated-sorted-array","Find Minimum in Rotated Sorted Array","Binary Search"],["search-a-2d-matrix","Search a 2D Matrix","Binary Search"],["search-in-rotated-sorted-array","Search in Rotated Sorted Array","Binary Search"],["koko-eating-bananas","Koko Eating Bananas","Binary Search"],["capacity-to-ship-packages-within-d-days","Capacity To Ship Packages Within D Days","Binary Search"],["valid-parentheses","Valid Parentheses","Stack"],["min-stack","Min Stack","Stack"],["next-greater-element-i","Next Greater Element I","Stack"],["evaluate-reverse-polish-notation","Evaluate Reverse Polish Notation","Stack"],["daily-temperatures","Daily Temperatures","Stack"],["asteroid-collision","Asteroid Collision","Stack"],["largest-rectangle-in-histogram","Largest Rectangle in Histogram","Stack"],["reverse-linked-list","Reverse Linked List","Linked List"],["merge-two-sorted-lists","Merge Two Sorted Lists","Linked List"],["linked-list-cycle","Linked List Cycle","Linked List"],["middle-of-the-linked-list","Middle of the Linked List","Linked List"],["remove-nth-node-from-end-of-list","Remove Nth Node From End of List","Linked List"],["reorder-list","Reorder List","Linked List"],["lru-cache","LRU Cache","Linked List"],["merge-k-sorted-lists","Merge k Sorted Lists","Linked List"],["maximum-depth-of-binary-tree","Maximum Depth of Binary Tree","Trees: Traversal"],["invert-binary-tree","Invert Binary Tree","Trees: Traversal"],["same-tree","Same Tree","Trees: Traversal"],["balanced-binary-tree","Balanced Binary Tree","Trees: Traversal"],["diameter-of-binary-tree","Diameter of Binary Tree","Trees: Traversal"],["binary-tree-level-order-traversal","Binary Tree Level Order Traversal","Trees: Traversal"],["binary-tree-right-side-view","Binary Tree Right Side View","Trees: Traversal"],["binary-tree-zigzag-level-order-traversal","Binary Tree Zigzag Level Order Traversal","Trees: Traversal"],["validate-binary-search-tree","Validate Binary Search Tree","Trees: BST & Advanced"],["kth-smallest-element-in-a-bst","Kth Smallest Element in a BST","Trees: BST & Advanced"],["lowest-common-ancestor-of-a-binary-search-tree","Lowest Common Ancestor of a Binary Search Tree","Trees: BST & Advanced"],["lowest-common-ancestor-of-a-binary-tree","Lowest Common Ancestor of a Binary Tree","Trees: BST & Advanced"],["construct-binary-tree-from-preorder-and-inorder-traversal","Construct Binary Tree from Preorder and Inorder Traversal","Trees: BST & Advanced"],["binary-tree-maximum-path-sum","Binary Tree Maximum Path Sum","Trees: BST & Advanced"],["serialize-and-deserialize-binary-tree","Serialize and Deserialize Binary Tree","Trees: BST & Advanced"],["kth-largest-element-in-an-array","Kth Largest Element in an Array","Heap / Priority Queue"],["last-stone-weight","Last Stone Weight","Heap / Priority Queue"],["k-closest-points-to-origin","K Closest Points to Origin","Heap / Priority Queue"],["task-scheduler","Task Scheduler","Heap / Priority Queue"],["top-k-frequent-words","Top K Frequent Words","Heap / Priority Queue"],["reorganize-string","Reorganize String","Heap / Priority Queue"],["find-median-from-data-stream","Find Median from Data Stream","Heap / Priority Queue"],["flood-fill","Flood Fill","Graphs: BFS / DFS"],["number-of-islands","Number of Islands","Graphs: BFS / DFS"],["max-area-of-island","Max Area of Island","Graphs: BFS / DFS"],["clone-graph","Clone Graph","Graphs: BFS / DFS"],["rotting-oranges","Rotting Oranges","Graphs: BFS / DFS"],["01-matrix","01 Matrix","Graphs: BFS / DFS"],["surrounded-regions","Surrounded Regions","Graphs: BFS / DFS"],["pacific-atlantic-water-flow","Pacific Atlantic Water Flow","Graphs: BFS / DFS"],["course-schedule","Course Schedule","Graphs: Topological Sort & Union-Find"],["number-of-provinces","Number of Provinces","Graphs: Topological Sort & Union-Find"],["find-eventual-safe-states","Find Eventual Safe States","Graphs: Topological Sort & Union-Find"],["course-schedule-ii","Course Schedule II","Graphs: Topological Sort & Union-Find"],["redundant-connection","Redundant Connection","Graphs: Topological Sort & Union-Find"],["accounts-merge","Accounts Merge","Graphs: Topological Sort & Union-Find"],["word-ladder","Word Ladder","Graphs: Topological Sort & Union-Find"],["subsets","Subsets","Backtracking"],["permutations","Permutations","Backtracking"],["combination-sum","Combination Sum","Backtracking"],["subsets-ii","Subsets II","Backtracking"],["combination-sum-ii","Combination Sum II","Backtracking"],["word-search","Word Search","Backtracking"],["palindrome-partitioning","Palindrome Partitioning","Backtracking"],["n-queens","N-Queens","Backtracking"],["climbing-stairs","Climbing Stairs","1D Dynamic Programming"],["min-cost-climbing-stairs","Min Cost Climbing Stairs","1D Dynamic Programming"],["house-robber","House Robber","1D Dynamic Programming"],["house-robber-ii","House Robber II","1D Dynamic Programming"],["coin-change","Coin Change","1D Dynamic Programming"],["longest-increasing-subsequence","Longest Increasing Subsequence","1D Dynamic Programming"],["word-break","Word Break","1D Dynamic Programming"],["decode-ways","Decode Ways","1D Dynamic Programming"],["unique-paths","Unique Paths","2D Dynamic Programming"],["minimum-path-sum","Minimum Path Sum","2D Dynamic Programming"],["longest-common-subsequence","Longest Common Subsequence","2D Dynamic Programming"],["partition-equal-subset-sum","Partition Equal Subset Sum","2D Dynamic Programming"],["coin-change-ii","Coin Change II","2D Dynamic Programming"],["target-sum","Target Sum","2D Dynamic Programming"],["edit-distance","Edit Distance","2D Dynamic Programming"],["best-time-to-buy-and-sell-stock-with-cooldown","Best Time to Buy and Sell Stock with Cooldown","2D Dynamic Programming"],["maximum-subarray","Maximum Subarray","Greedy & Intervals"],["jump-game","Jump Game","Greedy & Intervals"],["merge-intervals","Merge Intervals","Greedy & Intervals"],["insert-interval","Insert Interval","Greedy & Intervals"],["jump-game-ii","Jump Game II","Greedy & Intervals"],["gas-station","Gas Station","Greedy & Intervals"],["non-overlapping-intervals","Non-overlapping Intervals","Greedy & Intervals"],["minimum-number-of-arrows-to-burst-balloons","Minimum Number of Arrows to Burst Balloons","Greedy & Intervals"],["implement-trie-prefix-tree","Implement Trie (Prefix Tree)","Trie & Strings"],["longest-common-prefix","Longest Common Prefix","Trie & Strings"],["palindromic-substrings","Palindromic Substrings","Trie & Strings"],["design-add-and-search-words-data-structure","Design Add and Search Words Data Structure","Trie & Strings"],["search-suggestions-system","Search Suggestions System","Trie & Strings"],["longest-palindromic-substring","Longest Palindromic Substring","Trie & Strings"],["word-search-ii","Word Search II","Trie & Strings"],["network-delay-time","Network Delay Time","Advanced Graphs (Dijkstra / MST)"],["shortest-path-in-binary-matrix","Shortest Path in Binary Matrix","Advanced Graphs (Dijkstra / MST)"],["min-cost-to-connect-all-points","Min Cost to Connect All Points","Advanced Graphs (Dijkstra / MST)"],["cheapest-flights-within-k-stops","Cheapest Flights Within K Stops","Advanced Graphs (Dijkstra / MST)"],["path-with-minimum-effort","Path With Minimum Effort","Advanced Graphs (Dijkstra / MST)"],["swim-in-rising-water","Swim in Rising Water","Advanced Graphs (Dijkstra / MST)"],["maximum-units-on-a-truck","Maximum Units on a Truck","OA Simulation: 2 problems in 90 min each round"],["count-number-of-teams","Count Number of Teams","OA Simulation: 2 problems in 90 min each round"],["number-of-ways-to-select-buildings","Number of Ways to Select Buildings","OA Simulation: 2 problems in 90 min each round"],["sum-of-total-strength-of-wizards","Sum of Total Strength of Wizards","OA Simulation: 2 problems in 90 min each round"],["subarray-sum-equals-k","Subarray Sum Equals K","Amazon-tagged: Arrays & Strings"],["find-all-anagrams-in-a-string","Find All Anagrams in a String","Amazon-tagged: Arrays & Strings"],["string-compression","String Compression","Amazon-tagged: Arrays & Strings"],["next-permutation","Next Permutation","Amazon-tagged: Arrays & Strings"],["spiral-matrix","Spiral Matrix","Amazon-tagged: Arrays & Strings"],["rotate-image","Rotate Image","Amazon-tagged: Arrays & Strings"],["set-matrix-zeroes","Set Matrix Zeroes","Amazon-tagged: Arrays & Strings"],["copy-list-with-random-pointer","Copy List with Random Pointer","Amazon-tagged: Mixed"],["decode-string","Decode String","Amazon-tagged: Mixed"],["find-the-duplicate-number","Find the Duplicate Number","Amazon-tagged: Mixed"],["valid-sudoku","Valid Sudoku","Amazon-tagged: Mixed"],["basic-calculator-ii","Basic Calculator II","Amazon-tagged: Mixed"],["sliding-window-maximum","Sliding Window Maximum","Amazon-tagged: Mixed"],["first-missing-positive","First Missing Positive","Amazon-tagged: Mixed"],["insert-delete-getrandom-o-1","Insert Delete GetRandom O(1)","Amazon-tagged: Design-style coding"],["time-based-key-value-store","Time Based Key-Value Store","Amazon-tagged: Design-style coding"],["design-underground-system","Design Underground System","Amazon-tagged: Design-style coding"],["snapshot-array","Snapshot Array","Amazon-tagged: Design-style coding"],["design-twitter","Design Twitter","Amazon-tagged: Design-style coding"],["maximum-frequency-stack","Maximum Frequency Stack","Amazon-tagged: Design-style coding"],["all-nodes-distance-k-in-binary-tree","All Nodes Distance K in Binary Tree","Amazon-tagged: Trees & Matrix (mock day)"],["path-sum-ii","Path Sum II","Amazon-tagged: Trees & Matrix (mock day)"],["flatten-binary-tree-to-linked-list","Flatten Binary Tree to Linked List","Amazon-tagged: Trees & Matrix (mock day)"],["maximal-square","Maximal Square","Amazon-tagged: Trees & Matrix (mock day)"],["vertical-order-traversal-of-a-binary-tree","Vertical Order Traversal of a Binary Tree","Amazon-tagged: Trees & Matrix (mock day)"],["longest-increasing-path-in-a-matrix","Longest Increasing Path in a Matrix","Amazon-tagged: Trees & Matrix (mock day)"],["game-of-life","Game of Life","Weak areas: redo your mistakes notebook + new"],["3sum-closest","3Sum Closest","Weak areas: redo your mistakes notebook + new"],["integer-to-english-words","Integer to English Words","Weak areas: redo your mistakes notebook + new"]],"lab":[["rate-limiter","Rate Limiter"],["comments-replies","Comments & Replies"],["url-shortener","URL Shortener Service"],["reservation-service","Reservation Service Incident"],["file-deduplication","File Deduplication"],["feature-flag","Feature Flags & A/B"],["image-transform-pipeline","Image Transform Pipeline"],["loan-management","Loan Lifecycle & Balances"],["return-fraud-risk","Return Risk Assessment"],["review-moderation","Comment Moderation"],["issue-creation-api","Retry-Safe Issue Service"],["movie-recommendations","Movie Recommendations"],["keyword-user-blocklists","Keyword & User Blocking"],["movie-watchlists","Persistent Private Watchlists"],["password-reset","Password Reset"],["ttl-lru-cache","TTL + LRU Cache"],["job-queue","Retrying Job Queue"],["leaderboard","Leaderboard Service"]]}