Skip to content
Preptima

Top 15 Invariants Interview Questions

Browse 15 real-world technical and behavioral interview questions about Invariants. Review scenarios, edge cases, and architectural best practices.

A flash sale decrements stock from many threads. Do you go optimistic or pessimistic, and how do you prove nothing oversold?

For one stock counter, optimistic locking with a compare-and-set loop fits: read, refuse at zero, and publish the decrement only if nobody changed the value meanwhile. A lock suits a larger critical section. Prove it by arguing each sale consumes one unit, plus a stress test seen to fail on the broken code.

mediumcoding

You may use an AI coding assistant in the machine-coding round. What do you still write yourself, and what do you ask it for?

Write the domain model, the interfaces and the code enforcing each invariant yourself, because the grader scores them and a mid-round change tests them. Hand the assistant bounded boilerplate such as records, an in-memory repository, a driver and test scaffolding, and review every line it returns.

mediumcoding

A bundle can contain products or other bundles, and the pricing code should not care which it is holding. How would you model that?

A composite gives leaves and containers one interface so callers recurse without branching. The two decisions that matter are whether child management appears on that shared interface, and which operations genuinely aggregate - because price, availability and delivery date do not combine the same way. It also connects tree structures to the point an interviewer is testing.

mediumdesign

Implement a FIFO queue using only two stacks, then tell me what a dequeue costs.

Push arrivals onto an inbound stack and serve departures from an outbound one, transferring everything across only when the outbound stack is empty. Transferring on every dequeue instead reverses the order and breaks FIFO, and the empty-only rule is also what makes the amortised cost constant.

mediumcoding

Given package weights in a fixed order, find the smallest ship capacity that delivers them all within D days

When you cannot construct the answer but can cheaply test a candidate, and that test is monotone, binary search the answer's numeric range instead of the input. The feasibility check here is greedy day-packing, giving O(n log S) time, and the whole implementation hinges on one loop invariant. It also connects monotonicity to the point an interviewer is testing.

mediumcoding

How do you turn what the business tells you into a domain model that holds up once the exceptions arrive?

Model the state changes and invariants rather than the nouns the business names, and go looking for reversal, amendment, partial completion and manual override before committing to a shape. Domain-driven design earns its keep where rules are contested; on CRUD and reporting it is ceremony.

harddesign

Where does encapsulation or polymorphism change a design, and how do you decide between composition and inheritance?

Encapsulation earns its place when a class owns an invariant that callers would otherwise each have to enforce, and polymorphism when a conditional grows with every new requirement. Composition versus inheritance is decided on evidence: how many axes vary, and whether every inherited operation is honest.

mediumconcept

Merge a list of overlapping intervals, and justify the key you sorted by

Sorting by start time is what reduces the merge to a single scan carrying one scalar, the end of the open block; sorting by end breaks it, and sorting by end is instead correct for maximum non-overlapping selection. Both run in O(n log n), and equal timestamps decide the answer.

easycoding

An order moves through a set of states with rules about which transitions are allowed. How would you design that so it does not become a nest of if statements?

Write the legal transitions down as a table first, then give the entity one entry point that consults it and no state setter at all. The design question is where the transition rules live and how side effects stay outside the decision that changed the state.

mediumdesign

Numbers arrive one at a time and after each one I want the running median. How would you keep it?

Split the values across a max-heap of the lower half and a min-heap of the upper half, so the median is read off one or both tops. Balancing by size alone is what breaks it: a new value has to enter through the heap it belongs to by value and be transferred across, never pushed into whichever heap is currently smaller.

mediumcoding

You are given a sorted array that has been rotated by an unknown amount. Find a target value in logarithmic time.

Search a rotated sorted array in O(log n) by finding which half is sorted at each midpoint, then keeping the half where the target can legally fall. With duplicates, equal endpoints can hide the pivot, so the worst case becomes linear.

mediumcoding

Build a shared-expense tracker. Three people split a bill of ten pounds evenly - write the classes, and tell me where the missing penny goes.

A Splitwise-style machine coding answer turns on one invariant: the shares of an expense must sum to the expense total exactly, in every currency, forever. That forces money into integer minor units and forces a stated rule for allocating the remainder.

mediumcoding

Given the heights of a row of bars, work out how much rainwater is trapped between them. Do it in constant extra space.

Water above a bar is the smaller of the tallest bar to its left and the tallest to its right, minus its own height. Walking inwards from both ends and always advancing the shorter side works because that side's running maximum is the binding constraint there, whatever heights remain unseen in the middle.

mediumcoding

An operation in this code takes two locks and it deadlocks every few weeks. How would you design the locking so that cannot happen?

A deadlock is a cycle in the wait-for graph, so the design goal is a graph that cannot contain one: stop holding two locks where you can, impose one total order on acquisition everywhere you cannot, and never call unknown code while holding a lock.

harddesign

Given a binary tree, decide whether it is a valid binary search tree.

Every node must fall inside an open interval inherited from its ancestors, not merely compare correctly against its own two children. Recurse carrying a low and high bound, tightening one of them at each descent, or walk in-order and require the sequence to be strictly increasing.

mediumcoding