CS foundations interview bank

Questions interviewers actually ask, each answered at the length you would say it aloud, with the topic to reread if you were not sure.

92 questions Junior Senior
All levels Junior Mid Senior
Reveal one by one Show all answers
Report an error

Networking protocols

2 questions
01 What problem does HTTP/2 multiplexing solve, and which head-of-line blocking remains? Mid common reveal ▾ hide ▴

HTTP/2 labels frames with stream identifiers, so requests and responses can be interleaved on one connection. A ready response no longer waits for an earlier slow response merely because HTTP/1.1 requires response order. However, the frames still travel through one ordered TCP byte stream. If a TCP segment is lost, later bytes for every HTTP/2 stream wait for retransmission. Multiplexing therefore removes HTTP-level response ordering, not transport-level head-of-line blocking. I verify the negotiated protocol and measure through the real proxy path before attributing a latency change to multiplexing.

read more HTTP/2
Was this clear?
09 How does a WebSocket opening handshake work, and what does subprotocol negotiation establish? Mid common reveal ▾ hide ▴

On the classic HTTP/1.1 path, the client requests an upgrade and sends a random Sec-WebSocket-Key plus version 13. An accepting server returns 101 and computes Sec-WebSocket-Accept from that key and the protocol GUID. The accept value proves protocol awareness, not user identity. The client may also offer ordered Sec-WebSocket-Protocol values; the server selects at most one offered value, and both endpoints then use that application protocol. I separately verify TLS, Origin policy, authentication, and the selected protocol before marking the session ready.

read more WebSocket
Was this clear?

Capacity and backpressure

3 questions
02 How do HTTP/2 flow control and application backpressure differ? Mid common reveal ▾ hide ▴

HTTP/2 DATA consumes both a stream window and a connection window. WINDOW_UPDATE grants more byte credit after the receiver makes capacity available. These windows do not limit HEADERS, handler count, parsed objects, database work, or an application queue. A runtime may expose the combined pressure through a writable stream returning false and a later drain event. Correct services respect that signal and also bound admission, body size, decoding, downstream calls, and buffered responses. I test a peer that stops reading because happy-path payloads rarely expose missing backpressure.

read more HTTP/2
Was this clear?
07 What does end-to-end backpressure require in a network service? Senior common reveal ▾ hide ▴

Socket backpressure begins when kernel send buffers fill: blocking writes wait, and nonblocking writes complete partially or would block. The service breaks that feedback if it keeps placing responses into an unbounded user-space queue. I put capacity limits on accepted connections, in-flight handlers, parsed messages, downstream calls, and outbound bytes. When a consumer slows, the producer pauses rather than spawning more work. The overload policy may reject, shed permitted data, or close a slow peer, but it must be explicit. I monitor queue depth, buffered bytes, and tail latency to tune those limits.

Was this clear?
11 How do you apply backpressure to the classic WebSocket API? Senior common reveal ▾ hide ▴

The classic API queues data passed to send and exposes bufferedAmount as a snapshot; it has no standard drained event or automatic producer slowdown. I admit a send only while OPEN and while the encoded payload stays under a per-connection byte budget. The producer then pauses, rejects, coalesces replaceable state, or closes a persistently slow peer according to message semantics. Limits also cover inbound message size, concurrent handlers, and downstream calls. I test a peer that stops reading and monitor queued bytes and memory, because ordinary small messages rarely expose a missing bound.

read more WebSocket
Was this clear?

Failure handling

5 questions
03 How should a client react to an HTTP/2 GOAWAY frame? Senior occasional reveal ▾ hide ▴

GOAWAY means the connection will accept no new streams and carries the highest peer-initiated stream that might have been processed. The client opens or selects another session for new work and gives accepted streams a bounded drain period. Higher-numbered local streams can be candidates for retry, but the protocol signal is not the whole decision. The method must be safe under replay or protected by idempotency, the request body must be reproducible, and intermediary side effects must be considered. I never replay every active request blindly, especially writes.

read more HTTP/2
Was this clear?
06 How do timeout, orderly EOF, and connection reset differ for a socket reader? Mid common reveal ▾ hide ▴

A timeout says that an operation made no required progress before its budget expired; it does not prove the peer is dead. Orderly EOF, represented by an empty read after buffered bytes are consumed, says the peer closed its sending direction. A reset reports abnormal connection termination and normally arrives as an error. None of these outcomes proves whether the peer committed an application transaction. I preserve them as separate error states, attach the connection phase and byte counts, close through one owner, and retry only when application idempotency makes replay safe.

Was this clear?
10 Why is reconnecting a WebSocket not enough to recover message delivery? Mid common reveal ▾ hide ▴

A break tells the client that the transport ended, but not whether the server processed the last command. The server may have committed a side effect while its acknowledgement was lost. I reconnect with capped exponential backoff and jitter, then restore authentication and subscriptions before sending new work. Side-effecting commands carry stable idempotency keys so a retry returns the original result rather than repeating it. Server pushes use a confirmed resume cursor; if retained history no longer covers that cursor, the protocol requires a fresh snapshot instead of silently losing events.

read more WebSocket
Was this clear?
51 How do exit status, pipelines, and pipefail affect shell error handling? Mid common reveal ▾ hide ▴

Zero conventionally means success; each command documents its nonzero outcomes. The special parameter $? is volatile, so I capture it immediately or put the command directly in an if condition. A Bash pipeline normally reports its last stage, which can hide an earlier failure. With pipefail, it reports the rightmost nonzero stage, but early consumer exit can make a producer receive SIGPIPE intentionally. I choose the policy per pipeline, preserve diagnostic output, and force every stage to fail in tests. I do not treat set -e as exception handling because its behavior depends on grammar context.

read more Shell basics
Was this clear?
78 How do you detect an upstream failure in a Bash pipeline without losing stage identity? Mid common reveal ▾ hide ▴

By default, Bash reports the last command’s status, so a successful consumer can hide a failed producer. I enable pipefail when any failed stage should fail the operation, then copy PIPESTATUS immediately after the pipeline if diagnosis or status-specific recovery needs every value. Even an echo or assignment can replace that array. I classify expected nonzero statuses explicitly instead of attaching || true to the whole pipeline. Before publishing an artifact, I verify the chosen status policy and reject partial output, even when the file is nonempty or the final parser succeeded.

Was this clear?

Protocol security

2 questions
04 What state does HPACK maintain, and what security limits still matter? Senior occasional reveal ▾ hide ▴

HPACK uses static and dynamic tables so repeated field names and values can be represented by references. Encoder and decoder context is ordered and scoped to one connection; a context failure can therefore become a connection error. Compression does not encrypt fields. Sensitive values should use a never-indexed representation, while TLS, log redaction, and access control remain necessary. Receivers must limit decoded field count and size rather than trusting compressed bytes on the wire. I also bound per-field size and decoding work so a compact field block cannot trigger unbounded memory or CPU use.

read more HTTP/2
Was this clear?
12 Which security checks belong at a browser WebSocket boundary? Senior occasional reveal ▾ hide ▴

I use wss and validate the browser Origin against an explicit allowlist before upgrade. Origin protects against a hostile page borrowing ambient credentials; it is not authentication and non-browser clients can forge it. Identity comes from a secure session, short-lived connection ticket, or bounded authentication exchange. Every message is size-limited, parsed against a schema, rate-limited, and authorized for its resource rather than trusting connection-time access forever. I keep long-lived tokens out of URLs and logs, expire unauthenticated connections quickly, and define close codes without exposing sensitive policy details.

read more WebSocket
Was this clear?

Transport semantics

1 question
05 Why does TCP need application message framing, and how would you test a length-prefixed decoder? Mid common reveal ▾ hide ▴

TCP delivers an ordered byte stream, not the write boundaries chosen by the sender. One receive can contain part of a header, part of a payload, several messages, or any combination that preserves byte order. A length-prefixed decoder therefore buffers incrementally, reads a fixed-width length in the agreed byte order, rejects values above a configured maximum, and emits only complete frames. I test every split within the header and payload, several frames in one chunk, zero-length frames, early EOF, oversized lengths, and a total operation deadline.

Was this clear?

Connection establishment

1 question
08 Why should a client treat DNS results as connection candidates rather than one address? Senior occasional reveal ▾ hide ▴

A host name can resolve to several IPv6 and IPv4 addresses whose reachability and latency differ. Trying only the first result turns one broken route into an application outage, while connecting to everything simultaneously wastes work. A mature client uses resolver ordering plus a bounded strategy such as staggered candidate attempts, cancels losers, and applies one overall deadline. I keep each candidate failure for diagnostics and record the selected address family. Resolution success, transport connection, TLS handshake, and application handshake remain separate phases because success at one does not guarantee the next.

Was this clear?

Operating-system model

1 question
13 How do the Linux kernel, a distribution, and a shell differ? Junior common reveal ▾ hide ▴

Linux is the kernel: it schedules execution, manages memory and devices, implements filesystems and networking, and exposes system calls. A distribution combines a selected kernel with user-space libraries, package management, service management, defaults, and an update policy. A shell is one user-space command interpreter that starts programs and configures file descriptors for redirection and pipelines. These layers can vary independently. A Bash command copied from Ubuntu may fail on a minimal Fedora container even though both use Linux, because the available tools, paths, and service policy differ.

read more Linux
Was this clear?

Files and permissions

1 question
14 Why can a user sometimes delete a file they cannot read, or fail to delete one they own? Mid common reveal ▾ hide ▴

Reading file contents is authorized against the file, while unlinking a name modifies its parent directory. Removing a directory entry therefore normally requires write and search permission on the parent, not read permission on the file. A sticky directory such as a shared temporary directory adds an ownership rule, and mounts or mandatory access control can add more restrictions. I inspect every path component with the process effective credentials and check ACLs and policy denials. File ownership alone does not settle whether the containing directory may be changed.

read more Linux
Was this clear?

Files and storage

1 question
15 Why can df report a full filesystem when du cannot find the corresponding files? Mid common reveal ▾ hide ▴

du walks reachable directory entries and sums the blocks attributed to them. df reports allocation for the filesystem as a whole. If a process keeps a file open after its last directory entry is removed, that inode and its data remain allocated until the final open file description closes, but du can no longer reach it by name. I first confirm both commands refer to the same mount, then inspect open deleted files and identify the owning service. The safe remedy is usually to make that service close or reopen the file, not to manipulate its descriptor blindly.

read more Linux
Was this clear?

Process lifecycle

1 question
16 How do you design a reliable Linux service shutdown? Senior common reveal ▾ hide ▴

I define one owner for shutdown and a catchable stop signal, usually SIGTERM. The service stops admitting work, cancels or drains operations according to their semantics, forwards termination to children, closes descriptors, and exits before an overall deadline. The supervisor waits and records the real exit status. If the deadline expires, it captures useful diagnostics and escalates to SIGKILL. I test shutdown during startup, active requests, dependency failure, and repeated signals. A vanished PID proves only termination; it does not prove that transactions committed or leases were released.

read more Linux
Was this clear?

Git data model

2 questions
17 How do Git blobs, trees, commits, and references fit together? Mid common reveal ▾ hide ▴

A blob stores file bytes without a path or file name. A tree gives those blobs and subtrees names and modes, so one root tree describes a project snapshot. A commit points to that root tree, lists parent commits, and records author, committer, and message metadata. A branch is a movable reference to a commit; HEAD normally refers symbolically to the checked-out branch. This separation lets identical content be reused and makes branches cheap names over one shared graph. I inspect the model with cat-file, ls-tree, and for-each-ref rather than editing files under .git directly.

Was this clear?
18 What is Git’s index, and how does it differ from HEAD and the working tree? Mid common reveal ▾ hide ▴

HEAD resolves to the current committed snapshot, the index describes the proposed next snapshot, and the working tree contains editable files. Git add reads a path’s current content into a blob and places that blob in the index; later edits remain only in the working tree until added again. That is why git diff shows unstaged changes while git diff —cached shows staged changes relative to HEAD. During conflicts, the index can hold base, ours, and theirs entries at stages 1, 2, and 3. Resolving and adding the file replaces them with one stage 0 entry.

Was this clear?

History transformations

1 question
19 What is the structural difference between merging and rebasing? Mid common reveal ▾ hide ▴

A true merge creates a commit with multiple parents after combining each tip’s changes relative to a merge base. Existing commits keep their identities, and the graph records where lines converged. Rebase instead reapplies commits unique to one branch onto a new base. Because parent IDs are part of commit content, the replacements normally get new IDs even when the final files match. I merge shared history unless a documented policy permits rewriting it, and I use rebase to organize private commits before publication. Force-with-lease is a conditional ref update, not team authorization to rewrite a branch.

Was this clear?

Failure recovery

1 question
20 How would you recover a commit after an accidental reset, and what are reflog’s limits? Senior common reveal ▾ hide ▴

I stop mutating the repository, inspect git reflog with dates, and identify the pre-reset commit from the operation, time, tree, and parent chain. I create a rescue branch at the verified full object ID before deciding whether to reset, cherry-pick, or merge anything. A reflog is local: another clone may not contain the same entries, and expiration plus garbage collection can eventually remove unreachable objects. It does not recover uncommitted working-tree bytes that Git never stored. For important history I rely on protected remote references or independent backups, not an assumed ninety-day recovery window.

Was this clear?

Text and locale

1 question
21 How do internationalization, localization, and a locale differ? Junior common reveal ▾ hide ▴

Internationalization is the software design that separates messages, formatting rules, and writing direction from business logic. Localization supplies and validates those inputs for a particular market: translation is part of it, alongside terminology and layout review. A locale is a runtime convention used to select such behavior, usually represented by a BCP 47 tag that may include language, script, and region. It is not a user’s location and does not determine currency or time zone. I model those values separately and define a deterministic policy that resolves requested locales to catalogs the product actually deploys.

Was this clear?

Data and presentation

1 question
22 Why should locale, currency, and time zone be separate formatting inputs? Mid common reveal ▾ hide ▴

They represent different facts. Locale controls presentation conventions such as separators and symbol placement; currency belongs to an order or quote; time zone comes from the user or event context. A Chinese-language user may pay euros while viewing an event in Paris time, so deriving one input from another loses valid states. I keep raw amounts paired with currency codes and preserve explicit time semantics, then format only at the display boundary. Server and client receive the same resolved inputs, and caches include every dimension that actually changes rendered output.

Was this clear?

Message contracts

1 question
23 How would you design and validate a message catalog with plurals? Mid common reveal ▾ hide ▴

I use stable semantic keys and complete messages with named, typed placeholders, never translated fragments joined in source-language order. A plural-aware message selects a locale-defined category through the message runtime and always has an other branch; exact-number branches such as =0 are distinct from the zero category. At build time I compare catalog key sets, placeholder names and types, plural variables, and permitted rich-text slots. In development a miss fails visibly. Production may follow a short deterministic fallback chain, but it records the requested locale, selected catalog, and missing key for diagnosis.

Was this clear?

Bidirectional interfaces

1 question
24 What does correct RTL support require beyond setting dir="rtl"? Senior occasional reveal ▾ hide ▴

The root lang and dir attributes must follow the same resolved locale, while layout uses CSS logical properties instead of left and right assumptions. Dynamic fragments such as names, URLs, and order IDs may have the opposite direction from surrounding text, so I isolate them with bdi or an equivalent mechanism. Icon mirroring is semantic: a back arrow may flip, while a play symbol or brand should not. I test keyboard and reading order, copying, selection, focus, and assistive technology with real RTL content because a mirrored screenshot cannot expose every bidirectional boundary defect.

Was this clear?

Algorithm correctness

1 question
25 How do you prove that a recursive function terminates? Mid common reveal ▾ hide ▴

I first define the admitted input domain and every base case. Then I choose a well-founded measure, often a nonnegative integer such as remaining length or interval width. I show that the measure is valid on entry and strictly decreases on every recursive edge, not only the common branch. Because that measure cannot descend forever, execution must reach a boundary. For graphs, structural size alone is insufficient because edges may form cycles, so I mark identities before descent and use the finite set of reachable, unvisited nodes as the measure.

read more Recursion
Was this clear?

Complexity analysis

3 questions
26 Why are recursive running time and call depth different quantities? Mid common reveal ▾ hide ▴

Running time depends on total calls and the work done in each call, while stack space depends on the maximum number of unfinished calls at once. A balanced tree traversal visits every node, so it takes O(n) time but only O(log n) call depth. A chain-shaped tree keeps O(n) time and raises depth to O(n). Naive Fibonacci has linear depth yet exponential total calls because its branches recompute overlapping states. I draw a call tree for work and follow one longest root-to-leaf path for depth, then include non-stack storage separately.

read more Recursion
Was this clear?
30 How do you derive a complexity bound from unfamiliar code? Junior common reveal ▾ hide ▴

I first define every independent input dimension and choose a meaningful operation to count. Then I trace sequential phases, loops, recursion, allocations, and calls whose own cost depends on input. Sequential costs add, nested full traversals usually multiply, and repeated constant-factor shrinking suggests logarithmic work, but I verify how indices move instead of judging indentation. I derive time and peak auxiliary space separately, simplify dominant terms, and label the relevant case and assumptions. Finally, I test operation counts or doubling ratios on boundary, representative, and adversarial shapes to challenge the model.

Was this clear?
31 How do worst-case, expected, and amortized complexity differ? Mid common reveal ▾ hide ▴

Worst-case complexity bounds the most expensive valid input of a given size and is useful for deadlines or hostile input. Expected complexity averages under an explicit probability or data-structure assumption, such as randomized hashing; without that assumption the claim is incomplete. Amortized complexity instead bounds the total cost across any relevant operation sequence and spreads it over the operations, with no probability distribution required. A dynamic array append can therefore be worst-case O(n) during resize but amortized O(1) across many appends. I report whichever cases affect the product limit rather than presenting one label without context.

Was this clear?

Traversal design

1 question
27 How do you replace a recursive depth-first traversal with an explicit stack without changing behavior? Mid occasional reveal ▾ hide ▴

I identify what each recursive frame stores: the node, local accumulator, next child, and any work performed after the child returns. Pre-order traversal can process a node immediately and push its children from right to left so a LIFO stack preserves left-to-right visitation. Post-order traversal needs an explicit phase or next-child index to represent the return point. I also preserve duplicate handling, error timing, and partial-result rules. The explicit stack gets an application limit, and I compare both versions on small branching trees, chains, cycles, and failures before switching large inputs.

read more Recursion
Was this clear?

Failure diagnosis

5 questions
28 A recursive function passes tests but reaches RecursionError in production. How do you diagnose and fix it? Senior common reveal ▾ hide ▴

I capture the input shape and a bounded frame trace, then determine whether depth comes from a valid chain, a cycle, or a branch that fails to make progress. I state a termination measure and check it on every edge. Raising the recursion limit is not my default fix because it changes the guard without reducing frames or proving termination. I add cycle detection and business limits where required, then replace linear-depth recursion with an explicit stack for large or external input. Regression tests cover the exact boundary, a deeper chain, a self-cycle, and traversal order.

read more Recursion
Was this clear?
47 How do minor faults, major faults, invalid access, and OOM differ? Mid common reveal ▾ hide ▴

A minor fault needs kernel work but not storage I/O for the missing page, while a major fault requires I/O under the operating system’s accounting definition. Both may be recoverable and restart the instruction. Invalid access means the address has no permitted mapping; Linux commonly reports SIGSEGV or SIGBUS with fault metadata. OOM is a resource-policy outcome after reclaim cannot satisfy a request under system or cgroup constraints, and the kernel may kill a selected process. I preserve the exact counter, signal, exception, cgroup event, and map around the fault instead of calling every case “out of memory.”

Was this clear?
59 How do you diagnose a TLS connection failure without weakening verification? Mid common reveal ▾ hide ▴

I first separate DNS resolution, transport connect, TLS negotiation, certificate path building, hostname verification, and application protocol. I record the requested authority, selected address, SNI, ALPN result, safe error code, and phase timing. For certificate errors I inspect the served leaf and intermediates, configured trust anchors, reference hostname, SAN entries, validity times, and endpoint clock from a clean client environment. I test the deployed proxy path rather than only the origin. I do not set rejectUnauthorized to false, because that hides the evidence and can send credentials to an impersonator.

Was this clear?
71 How do NXDOMAIN, NODATA, SERVFAIL, and a timeout differ operationally? Mid common reveal ▾ hide ▴

NXDOMAIN is an authoritative statement that the queried name does not exist. NODATA is a successful response saying that the existing name has no records of the requested type, so another type may still succeed. SERVFAIL says the resolver could not produce a usable answer, for example because every authority failed or DNSSEC validation was bogus. A timeout says no response arrived within the caller’s wait. I negatively cache only authoritative absence for its derived lifetime, preserve transient failures as distinct states, and retry them only across suitable servers under one bounded deadline. None of these outcomes proves an application port is closed.

Was this clear?
72 How would you diagnose two machines receiving different DNS answers for the same hostname? Senior occasional reveal ▾ hide ▴

I first make the questions truly comparable: absolute name, record type, class, lookup API, recursive resolver, network or tenant view, and query time. I record response code, answer, authority, TTL, and DNSSEC status, then query the intended recursive resolvers directly. Different remaining TTLs may show ordinary cache age; different data may come from split-horizon policy, geography, staged rollout, stale serving, or inconsistent authoritative replicas. I query the parent delegation and every authoritative server for NS, SOA, aliases, A, and AAAA. Finally, I separate resolution from connection reuse, because an existing pool can keep using an older address.

Was this clear?

Asymptotic notation

1 question
29 How do Big O, Big Omega, and Big Theta differ, and why does a tight bound matter? Junior common reveal ▾ hide ▴

Big O is an asymptotic upper bound, Big Omega is a lower bound, and Big Theta means matching upper and lower bounds up to constant factors beyond a threshold. A linear function is technically O(n²), so Big O alone may be true but uninformative. I prefer Theta when I can establish tight growth and state whether the claim is worst-case, expected, or amortized. I also define the input variable and cost model. The notation compares growth; it does not give milliseconds or erase constants that matter at supported input sizes.

Was this clear?

Engineering trade-offs

1 question
32 How would you choose between a constant-space quadratic duplicate check and a linear-space expected-linear check? Mid common reveal ▾ hide ▴

I start with the maximum and typical item counts, memory budget, latency target, and whether keys can be adversarial. Pairwise comparison is worst-case Θ(n²) time and Θ(1) auxiliary space; a hash set is expected Θ(n) time and Θ(n) space under its hashing contract. For tiny hard-bounded inputs, the simpler scan may win on constants and allocation. For growing inputs, the set usually provides safer scaling. I benchmark near the expected crossover with representative keys, test the no-duplicate worst path, bound accepted cardinality, and record the assumptions so later traffic changes trigger reevaluation.

Was this clear?

Algorithm selection

1 question
33 When would you scan unsorted data instead of sorting it or building an index? Junior common reveal ▾ hide ▴

I start from the full operation mix. A scan is often right for one query, a small collection, frequently changing data, or a predicate that does not follow an existing order. It has a weak precondition and can stop after the first match. Sorting adds an upfront O(n log n) comparison cost but can support many ordered or range queries afterward. A hash index suits repeated exact-key lookup but consumes memory and needs updates. I compare builds, queries, mutations, and freshness requirements together, then measure representative data after the simplest correct design works.

Was this clear?

Ordering contracts

1 question
34 What must a comparator guarantee, and what extra guarantee does a stable sort provide? Mid common reveal ▾ hide ▴

A comparator returns a negative, zero, or positive result for before, equivalent in order, or after. Its answers must be consistent: self-comparison is equal, reversing arguments reverses the sign, and ordering is transitive. A stable sort preserves the input-relative order of distinct records that compare equal. Stability does not create a business tie-breaker or make unordered input deterministic. If pagination or reproducible output needs one total order, I add consistent secondary keys and usually a unique identifier. I also define null, missing, locale, and normalization behavior before sorting.

Was this clear?

Search invariants

1 question
35 How does a lower-bound binary search work, and how do you argue that it is correct? Mid common reveal ▾ hide ▴

I use a half-open interval [low, high). Every index below low is known to hold a key less than the target, while every index at or above high is known to hold a key at least the target. If the middle key is too small, low becomes middle plus one; otherwise high becomes middle because middle may be the answer. Both branches shrink the interval. When low equals high, the invariants meet at the first key not less than the target, or at the valid insertion position after the array. Sorting and searching must use the same key order.

Was this clear?

Range queries

1 question
36 How would you return every record whose sorted key lies in a requested range? Mid occasional reveal ▾ hide ▴

I define endpoint semantics first. For a half-open range [minimum, maximum), I run lower bound twice: once for the first key at least minimum and once for the first key at least maximum, then slice between those positions. For an inclusive maximum, the second search is upper bound, the first key greater than maximum. This handles duplicate boundary keys without scanning unrelated values. I test empty input, equal endpoints, bounds before and after the data, and duplicate runs at both ends. The sorted snapshot must remain valid under the same comparison policy during the query.

Was this clear?

HTTP contracts

1 question
37 What is the difference between a safe HTTP method and an idempotent one? Junior common reveal ▾ hide ▴

A safe method asks for read-only semantics: the client is not requesting a resource-state change, although logging or metrics can still occur. An idempotent method can change state, but repeating the same request has the same intended effect as sending it once. Every safe method is idempotent, but DELETE and PUT are idempotent without being safe. Idempotency does not require identical responses; an initial PUT can return 201 and a repeat 204. I use these properties to design retries, tests, and intermediary behavior, then add any narrower application guarantees explicitly.

Was this clear?

Retries and failure

1 question
38 How should a client react when a write times out before any response arrives? Mid common reveal ▾ hide ▴

I preserve the result as unknown because a timeout reports missing progress, not transaction rollback. The request might not have arrived, might still be running, or might have committed while its response was lost. I replay automatically only when the method and application contract make that safe, the body is reproducible, and the retry remains inside a capped attempt and deadline budget. For a non-idempotent operation, I use a stable server-enforced idempotency key or query an operation identifier. Backoff and jitter protect capacity, but they do not solve duplicate effects.

Was this clear?

Caching and validators

1 question
39 Explain a conditional GET that receives 304 Not Modified. Junior common reveal ▾ hide ▴

A cache first stores a successful GET representation and its validator, commonly an ETag. Once reuse requires validation, it sends If-None-Match with that tag. If the selected current representation still matches, the server returns 304 without representation content. The cache retains its stored content, updates metadata permitted by the validation response, and serves the combined result. If the tag does not match, the server normally returns 200 with the new representation. This is why 304 is not an empty 200, and why a client with no stored response cannot use it as content.

Was this clear?

Protocol boundaries

1 question
40 Why is an HTTP message boundary different from a connection boundary? Mid occasional reveal ▾ hide ▴

A connection is a transport session, while requests and responses are protocol messages carried by it. HTTP/1.1 can send several exchanges sequentially on one persistent connection, so content length, transfer coding, method, and status rules frame each message without waiting for EOF. HTTP/2 carries multiple concurrent streams on one connection and gives stream failures a narrower scope than connection failures. Closing or replacing a connection therefore says nothing conclusive about an application commit. I keep connection, stream, request-attempt, and idempotency identifiers distinct in logs and retry decisions.

Was this clear?

Data-structure choice

1 question
41 How do you choose between an array and a linked list? Junior common reveal ▾ hide ▴

I start from the operations and their inputs. Arrays give constant-time access by index, compact traversal, and amortized constant-time append in a dynamic implementation, but middle insertion shifts a suffix. A linked list reaches a numeric position linearly, yet can insert or remove with a fixed number of link updates when the required node or predecessor is already known. I also include memory: every node has links and usually a separate allocation, while an array may hold unused capacity. I default to the standard dynamic array, then benchmark another representation only when the workload justifies it.

Was this clear?

Complexity contracts

2 questions
42 Why is “linked-list insertion is O(1)” an incomplete claim? Mid common reveal ▾ hide ▴

The constant-time part is pointer rewiring after the correct location is known. If an API receives an index or a value, a plain linked list normally walks from an endpoint to find the predecessor, which costs O(n). In a singly linked list, deleting a target node may still require its predecessor. I state the precondition explicitly: insert after this known node, or remove this known doubly linked node. If a map supplies node handles, I include its memory and consistency costs. Complexity should describe the caller’s whole operation, not only the last assignments.

Was this clear?
62 Why is hash-map lookup expected O(1) rather than guaranteed O(1)? Mid common reveal ▾ hide ▴

Expected constant time assumes a suitable hash distribution, controlled load, and reasonably cheap equality. If many keys share a bucket or probe cluster, lookup examines more candidates and can approach O(n). Hashing a variable-length key also costs time proportional to the input examined unless a hash is cached. Hostile clients may exploit a predictable weak hash to create this concentration. I state the assumptions, bound untrusted key sizes and collection capacity, use the runtime’s hardened map, and measure representative plus adversarial key distributions when tail latency matters.

read more Hash maps
Was this clear?

Growth and latency

2 questions
43 How can dynamic-array append be amortized O(1) when a resize is O(n)? Mid common reveal ▾ hide ▴

A dynamic array keeps spare capacity, so most appends write one unused slot. When capacity is exhausted, it allocates a larger backing area and moves the existing elements, making that particular append O(n). With geometric growth, such as doubling, the moves across a long sequence form a geometric series whose total is proportional to the number of successful appends. That gives constant amortized cost, not constant worst-case latency. If one slow append violates a deadline, I reserve known capacity or choose a bounded or chunked structure and measure its memory tradeoff.

Was this clear?
63 What happens during hash-table resizing, and why is insertion still amortized O(1)? Mid common reveal ▾ hide ▴

When load crosses an implementation threshold, the table allocates larger storage and relocates live entries. It cannot simply copy buckets by index because index reduction depends on capacity; the same full hash may select another bucket after growth. That resize costs O(n) and may create a latency and memory peak. With geometric growth, however, resizes are infrequent, and the total relocation work across a long insertion sequence remains proportional to the number of entries inserted. The sequence has amortized O(1) insertion even though the particular insertion triggering growth is linear.

read more Hash maps
Was this clear?

Memory behavior

1 question
44 How do cache locality and memory overhead affect the array-versus-list choice? Senior occasional reveal ▾ hide ▴

Sequential array slots are commonly near one another, so cache-line fetches and prefetching can serve several upcoming accesses. Separately allocated list nodes carry one or two links and the next address is known only after reading the current node, which can make traversal allocation- and cache-heavy despite the same O(n) label. I avoid universal ratios because element shape, allocator, runtime, and hardware change the result. I write a byte model with slot size, capacity slack, link fields, headers, and alignment, then confirm it with a heap profile and representative traversal benchmark.

Was this clear?

Address translation

1 question
45 What does virtual memory add between a program address and physical RAM? Mid common reveal ▾ hide ▴

A program issues virtual addresses inside its process address space. The processor checks a cached translation or walks page tables, which map a virtual page to a physical frame and carry access permissions. If no usable present entry exists, a page fault transfers control to the kernel. The kernel may supply an anonymous page, find a cached file page, restore swapped data, perform copy-on-write, or reject the access. This layer provides relocation, protection, sparse reservation, and controlled sharing. It does not promise that every mapped byte is resident or that address-space capacity equals available RAM.

Was this clear?

Memory diagnosis

1 question
46 How would you decide whether rising RSS is an application memory leak? Mid common reveal ▾ hide ▴

I first keep the scope consistent: one process generation, cgroup, namespace, and workload interval. Then I compare virtual mappings, RSS, proportional set size, private dirty pages, allocator or heap profiles, cache ownership, and cgroup charge on one timeline. Rising RSS can come from live objects, allocator arenas retained for reuse, file cache, first-touch pages, or copy-on-write, so one snapshot is not proof. I reduce load or force a controlled lifecycle boundary and observe what ownership disappears and what the kernel can reclaim under pressure. The fix follows the retaining owner, not the largest headline number.

Was this clear?

Process memory

1 question
48 Why can memory usage rise sharply after fork even with copy-on-write? Senior occasional reveal ▾ hide ▴

Copy-on-write avoids eagerly copying private pages at fork. Parent and child can initially map the same physical backing with permissions that fault on a later write. When either process modifies a page, the kernel must preserve private contents, so sharing falls and aggregate physical charge can grow. A large resident heap becomes expensive if both sides dirty many pages, and runtime housekeeping may write pages the application expected to stay shared. I measure proportional and private memory before and after the fork workload, include cgroup accounting, and use a supported spawn-and-exec path when the child does not need the inherited runtime state.

Was this clear?

Shell parsing

1 question
49 How do you reason from shell source text to the arguments an external program receives? Junior common reveal ▾ hide ▴

I separate parsing from execution. First I identify operators, quote context, and shell words. Then I trace parameter, arithmetic, and command substitutions, followed where eligible by word splitting and pathname expansion, and finally quote removal. The result is an argument vector, not the original command-line string. I write each final argument on its own line and include empty arguments. For uncertain code, I replace the target temporarily with a function that prints its count and quoted arguments, then test spaces, wildcard characters, newlines, and leading hyphens in a controlled directory.

read more Shell basics
Was this clear?

Argument boundaries

1 question
50 Why is quoted "$@" the normal way for a Bash function to forward arguments? Junior common reveal ▾ hide ▴

Inside double quotes, ”$@” expands every positional parameter as a separate word. It therefore preserves the caller’s argument count, spaces inside one argument, and empty arguments. Unquoted $@ exposes values to word splitting and pathname expansion, while ”$*” joins all parameters into one word using the first character of IFS. I verify a forwarding wrapper with at least an empty argument, a value containing spaces, a literal asterisk, and a leading-hyphen value. The wrapped command may still need an option terminator because quoting does not stop option parsing.

read more Shell basics
Was this clear?

Safe automation

1 question
52 How do you review a generated shell command that deletes files? Mid common reveal ▾ hide ▴

I begin with authority and recovery, not only quoting. I identify who controls every input, require the narrowest accepted identifier or path, and reject empty, root, relative, or out-of-scope targets as the contract demands. Then I derive the exact operand array, confirm option termination, and examine glob, symlink, mount, and race behavior. I run the selection logic without mutation against spaces, wildcards, and leading-hyphen names in a temporary tree. Before unattended use, I require a bounded deletion scope, useful diagnostics, preserved failure status, an idempotent cleanup path, and a tested restore or rollback method.

read more Shell basics
Was this clear?

Operating-system concurrency

1 question
53 How do you choose between a process and a thread for concurrent work? Mid common reveal ▾ hide ▴

I start with the required boundary. A process normally gives a separate virtual address space, identity, resource table, and independently observable exit, so it is useful for fault containment, privilege separation, or independent deployment. Threads share a process and can communicate through shared memory with lower transfer cost, but they also share corruption and resource pressure. I then account for runtime rules, serialization or locking cost, startup rate, maximum concurrency, and shutdown. I choose from measured workload and ownership needs rather than assuming threads are always faster.

Was this clear?

Synchronization

1 question
54 Why is making a counter atomic not enough to make a shared operation thread-safe? Mid common reveal ▾ hide ▴

An atomic counter protects only the specified counter operation. A business transition may also check capacity, reserve an item, update a balance, and append a ledger entry. Other threads can interleave between those individually atomic steps and observe or create an invalid combination. I write the invariant first, identify every state field and access path that participates, then protect the whole transition with one ownership rule. That may be a mutex, an atomic compare-and-exchange protocol, or a single-owner queue. Tests exercise adverse interleavings, but the synchronization argument establishes correctness.

Was this clear?

Lifecycle and shutdown

1 question
55 What lifecycle contract should a bounded worker pool define? Mid common reveal ▾ hide ▴

The pool needs a hard worker limit, bounded admission, and an explicit overflow policy. Its owner defines creation failure, result delivery, worker crash, timeout, cancellation, and whether queued work may be abandoned. Graceful shutdown first stops admission, requests cancellation, lets safe in-flight work finish, closes channels, and joins workers within a deadline before escalating. Joining observes termination; it does not itself request it. I also specify result ordering and partial-failure semantics, then test shutdown while workers are blocked, starting, finishing, and reporting an error.

Was this clear?

Concurrency diagnosis

1 question
56 How do you investigate an intermittent process or thread concurrency failure? Senior occasional reveal ▾ hide ▴

I begin with the violated invariant and build a timeline using monotonic timestamps, process and thread identities, message IDs, lock waits, cancellation requests, and exits. I enumerate every path that touches the state and mark the happens-before edge that should order each conflicting access. Then I force delayed messages, creation failure, worker crashes, and cancellation at boundary points. Race detectors, thread sanitizers, and scheduler traces can expose evidence, but only for exercised paths. Once I reproduce one failing schedule, I minimize it and keep it as a deterministic regression test.

Was this clear?

Connection security

1 question
57 Why are certificate-chain validation and hostname verification separate TLS checks? Mid common reveal ▾ hide ▴

Chain validation asks whether signatures and certificate constraints lead from the presented leaf to a trust anchor the client already accepts. Hostname verification asks whether that leaf covers the reference service identity, normally the hostname from the original URL or configuration. A perfectly trusted certificate for payments.example must still fail for login.example, and a certificate naming login.example must fail if it chains only to an unknown root. I preserve the original name through DNS and routing, pass it as SNI and the verification input, and require both checks before sending credentials.

Was this clear?

Protocol mechanics

1 question
58 How does a TLS 1.3 handshake combine key agreement with server authentication? Mid common reveal ▾ hide ▴

Client and server exchange ephemeral Diffie-Hellman public shares and independently derive the same shared input. Key agreement alone is not authentication because an attacker could negotiate a different secret with each endpoint. The server therefore sends a certificate chain and a CertificateVerify signature over the handshake transcript, proving possession of the certified private key and binding the negotiation to it. Finished values then authenticate the transcript with derived secrets. The key schedule derives separate handshake and directional application traffic keys; the certificate signing key is not used to encrypt bulk application bytes.

Was this clear?

Session lifecycle

1 question
60 What security decisions accompany TLS session resumption and 0-RTT early data? Senior occasional reveal ▾ hide ▴

A session ticket is a resumption credential, so I bound its lifetime, rotate its protection keys, and isolate those keys between security domains. For TLS 1.3 I prefer resumption with a fresh ephemeral exchange when forward-secrecy requirements call for it. I treat 0-RTT separately: early data can be replayed before the new handshake completes. It stays disabled unless the complete application operation is safe when repeated. A nominal read may still consume a token, write an audit event, or trigger costly work, so an HTTP method label alone is not enough evidence.

Was this clear?

Hash-table mechanics

1 question
61 How does a hash map remain correct when two keys collide? Mid common reveal ▾ hide ▴

The hash and bucket index only narrow the candidate set; they do not establish key identity. A chaining table retains both entries in the selected bucket, while an open-addressed table follows a shared probe rule to another slot. Lookup repeats the same path and compares each candidate with the requested key. Equal keys must produce equal hashes, but unequal keys may collide. Insertion updates the existing value only after equality succeeds. I test this contract with deliberately colliding unequal keys, including updates, misses, and deletion in both insertion orders.

read more Hash maps
Was this clear?

Key design

1 question
64 How would you design a safe composite key for a hash map? Senior occasional reveal ▾ hide ▴

I begin with business equality: which fields define the same entity, including type, case, Unicode normalization, and missing-value rules. The hash or canonical representation must use those exact rules and remain stable while stored. Delimiter joining is unsafe when fields may contain the delimiter, so I prefer a value-key type or a specified length-prefixed encoding. I apply one canonicalizer on every insert, lookup, and delete path. For public input I also bound field length and collection size, then test reconstructed equal keys, delimiter-shaped values, normalized variants, mutations, and deliberate collisions.

read more Hash maps
Was this clear?

Graph modeling

1 question
65 How do you decide whether data should be treated as a tree or a graph? Mid common reveal ▾ hide ▴

I begin with invariants, not field names. A rooted tree has one root, every other node has exactly one parent, every node is reachable from the root, and no cycle exists. General graph data may have shared destinations, several parents, cycles, or disconnected vertices. I ask what an edge means, whether it is directed, and which stable key defines vertex identity. If an external API merely exposes children, I still validate unique parentage and acyclicity. When those guarantees are absent, I use graph traversal with visited state rather than trusting a tree-shaped serialization.

Was this clear?

Traversal strategy

1 question
66 How do DFS and BFS differ, and when would you choose each? Mid common reveal ▾ hide ▴

DFS uses a stack, explicit or through recursion, and follows one branch before returning to alternatives. It fits recursive evaluation, backtracking, component discovery, and algorithms that need completion order. BFS uses a queue and expands vertices by edge-count layers. That layer invariant makes first discovery a shortest path when every edge has equal cost. Both need stable visited state on a general graph and both take O(V + E) time with an adjacency list. I also compare memory shape: BFS may retain a wide layer, while recursive DFS risks the runtime stack on a deep chain.

Was this clear?

Cycle detection

1 question
67 Why is a visited set insufficient for directed cycle detection? Senior common reveal ▾ hide ▴

Visited state answers whether a vertex was encountered before, but it does not say whether that earlier traversal is still active. Directed DFS therefore separates unseen, active, and completed vertices. An edge to an active vertex is a back edge and proves a cycle; an edge to a completed vertex may simply join previously explored work. I keep parent links for active vertices so an error can report the concrete cycle. In an undirected graph, the edge back to the immediate parent is expected, so the detection condition must account for direction rather than reusing the directed test unchanged.

Was this clear?

Representation and complexity

1 question
68 How does graph representation change traversal cost and correctness? Mid occasional reveal ▾ hide ▴

With an adjacency list, DFS or BFS processes each reachable vertex once and inspects each stored outgoing edge once, giving O(V + E) work under the usual set assumptions. An adjacency matrix scans V possible neighbors per processed vertex, so full traversal performs O(V squared) cell checks even on a sparse graph. Representation also carries correctness contracts: missing map keys may mean leaves or invalid references, undirected edges normally need entries in both directions, and neighbor order selects among valid traversal or shortest-path results. I define those rules and stable vertex identity before discussing complexity.

Was this clear?

Resolution path

1 question
69 Trace a cache-miss DNS lookup from an application to an authoritative answer. Mid common reveal ▾ hide ▴

The application usually asks a stub resolver, which forwards the name and type to a recursive resolver. On a cache miss, the recursive resolver starts from known root-server addresses. A root reply refers it to the relevant top-level-domain servers, and the TLD reply refers it to authoritative servers for the child zone. The resolver queries one of those servers, follows any CNAME chain under a hop limit, caches the resulting record sets for their remaining TTLs, and returns candidates to the application. Referrals, timeouts, and negative answers are responses, not transport connections to the application service.

Was this clear?

Caching and change

1 question
70 Why does a DNS TTL not define the exact time when every client changes address? Mid common reveal ▾ hide ▴

TTL limits how long a particular cache may normally reuse a record after receiving it. Caches receive answers at different times, so their expiry instants differ. Applications can add caches with separate policies, and established sockets or connection pools do not consult DNS again merely because a record expired. For a migration, I lower TTL before the change, wait through the previous TTL, keep old and new endpoints healthy during an overlap, and observe traffic before retiring the old endpoint. I also inspect aliases and both A and AAAA data, because each dependent record set has its own lifetime.

Was this clear?

Text representation

1 question
73 How do bytes, UTF-16 code units, code points, and grapheme clusters differ? Junior common reveal ▾ hide ▴

Bytes belong to an encoded representation such as UTF-8. UTF-16 code units are 16-bit storage units, and JavaScript length and slicing use them; a supplementary code point needs a surrogate pair. A code point is a numbered Unicode position, although surrogate code points are not scalar values. An extended grapheme cluster is a sequence that segmentation rules treat as one user-perceived character, such as a base letter plus accents or a joined emoji family. I choose the unit from the operation: bytes for protocol capacity, code points for Unicode inspection, and graphemes for cursor movement or visible limits.

read more Unicode text
Was this clear?

Encoding boundaries

1 question
74 How would you safely decode UTF-8 arriving in network chunks? Mid common reveal ▾ hide ▴

I get the encoding from the protocol rather than guessing from the bytes. I reuse one decoder in streaming mode because a multibyte sequence can start in one chunk and finish in the next; decoding chunks independently can replace or reject valid text. At end-of-stream I finalize the decoder so an incomplete pending sequence is detected. For identifiers, signed data, or imports, I normally choose fatal decoding and keep the original bytes for diagnosis when policy permits. Wire-size limits are enforced on bytes before decoding, while user-visible limits are checked separately with grapheme segmentation after successful decoding.

read more Unicode text
Was this clear?

Normalization and equality

1 question
75 When should text be normalized, and how do NFC and NFKC change the policy? Mid common reveal ▾ hide ▴

I normalize only at a boundary whose equality contract requires it, and I preserve the original text for display and audit. NFC makes canonically equivalent sequences converge, such as a precomposed accented letter and its decomposed form. NFKC additionally applies compatibility mappings, so circled digits or width variants can converge with plain characters. That broader relation may help a specified search key but can erase meaningful distinctions in stored content or identifiers. I use the same named form on every write and lookup path, version derived keys when the policy changes, migrate old data, and handle collisions explicitly.

read more Unicode text
Was this clear?

Comparison contracts

1 question
76 Why should locale-aware collation not decide account identity? Senior occasional reveal ▾ hide ▴

A collator defines ordering and equivalence for one locale and option set. At base sensitivity it may ignore accents or case, so a zero comparison does not prove identical code points, bytes, or accounts. Locale data can also change when the runtime upgrades. I reserve collation for display sorting and product-defined search, construct it with an explicit locale and options, and add a stable identifier as the final sorting tie-breaker. Identity, uniqueness, permissions, and protocol tokens use a separate specification-defined comparison key. I test normalization, case, script, and collision cases against that identity contract rather than borrowing display behavior.

read more Unicode text
Was this clear?

Stream contracts

1 question
77 Why should a command keep standard output separate from standard error? Mid common reveal ▾ hide ▴

Standard output is the command’s result channel, so another program can parse it as data. Standard error carries diagnostics, warnings, and progress independently. If a script uses 2>&1 before a parser, one warning can become a fake record, invalidate JSON, or change a checksum. I keep the channels separate through the data path, redirect diagnostics to a dedicated log when needed, and preserve the exit status as a third signal. My test producer emits one valid record, one warning, and a nonzero status so the consumer contract is exercised rather than assumed.

Was this clear?

Descriptor routing

1 question
79 Why do `>file 2>&1` and `2>&1 >file` have different effects? Mid common reveal ▾ hide ▴

The shell applies redirections from left to right. In >file 2>&1, it first points standard output at the file, then duplicates that current destination onto standard error, so both descriptors reach the file. In 2>&1 >file, standard error first receives standard output’s old destination; only then does standard output move to the file. Standard error keeps the old terminal or pipe. I reason about each operator as a descriptor-table update and test with distinct markers on descriptors 1 and 2. Token reordering is therefore a semantic change, not formatting.

Was this clear?

Pipe lifecycle

1 question
80 What controls EOF and SIGPIPE in a pipe, and why can a pipeline hang? Senior occasional reveal ▾ hide ▴

A reader sees EOF only after every descriptor referring to the write end is closed, not merely when the apparent producer exits or the buffer becomes empty. An inherited duplicate write descriptor can therefore keep the reader waiting forever. Conversely, once every read end is closed, another write normally delivers SIGPIPE or fails with EPIPE if that signal is ignored. Pipe capacity also creates backpressure: a producer blocks when the finite buffer fills. I check descriptor ownership, close unused ends, bound the operation with a deadline, and decide whether an early-closing consumer is expected.

Was this clear?

Temporal modeling

1 question
81 How does an instant differ from a civil date-time? Mid common reveal ▾ hide ▴

An instant identifies one point on the timeline and can be ordered against other instants. A civil date-time is a set of calendar and clock fields such as 2026-11-01 01:30; it does not identify an instant until a calendar, zone or offset, and transition policy supply the missing context. Some civil values have no candidate instant during a clock gap, while others have two during an overlap. I keep event timestamps, calendar-only dates, and unresolved schedules as different domain types, then convert at a boundary that owns the policy.

Was this clear?

Time-zone rules

2 questions
82 Why is a UTC offset not a time zone? Mid common reveal ▾ hide ▴

An offset such as -04:00 states one numeric relationship to UTC and, with complete local fields, identifies an instant. A named IANA zone such as America/New_York supplies date-dependent regional rules, including historical changes and future rules in the installed database. A recurring 09:00 meeting therefore needs the zone, not merely the offset in effect when it was created. For resolved wire timestamps I still include an explicit offset, while scheduling data retains local fields, the zone identifier, and the policy for gaps and overlaps.

Was this clear?
83 How would you resolve local input during a time-zone gap or overlap? Senior occasional reveal ▾ hide ▴

I validate the calendar fields, load the named zone, and search for instants that project back to exactly those fields. Zero candidates means a gap, one means an ordinary unique time, and two means an overlap. Then I apply a product policy rather than a library default: reject or shift a gap, and choose earlier, choose later, or ask for an overlap. In Python I preserve the selected fold or resolved instant. Tests use real transitions and assert both local round trips and UTC results, because attaching ZoneInfo alone does not reject nonexistent fields.

Was this clear?

Arithmetic and clocks

1 question
84 How do calendar arithmetic, elapsed duration, and clock choice interact? Mid common reveal ▾ hide ▴

Calendar arithmetic preserves fields under calendar and zone rules: tomorrow at noon can be only 23 elapsed hours away across a forward clock change. Elapsed arithmetic preserves a timeline amount, so exactly 24 hours later may display as 13:00. I make that choice explicit in operation names and test both local fields and timestamp differences at transitions and month ends. For in-process deadlines I use a monotonic clock because wall time can be corrected. I record a separate UTC instant for logs, since monotonic readings are process-relative and cannot serve as universal timestamps.

Was this clear?

Numeric representation

1 question
85 Why can 0.1 + 0.2 differ from 0.3, and when is exact floating-point equality still appropriate? Mid common reveal ▾ hide ▴

Binary64 has finite precision, and fractions such as one tenth have repeating base-two expansions. Parsing each decimal chooses a nearby representable value, and addition rounds again, so the stored sum can differ from the value selected for the literal 0.3. That does not make every equality check wrong. Exact equality is appropriate when the contract promises identical representations, such as safe integers, an exact sentinel, or a value compared after a lossless round trip. For independently computed measurements, I derive absolute and relative tolerances from units and the algorithm’s error budget, then handle NaN and infinities separately.

Was this clear?

Numeric comparison

1 question
86 How would you design and review a floating-point near-equality check? Mid common reveal ▾ hide ▴

I first ask what error the domain permits and what error the algorithm introduces. An absolute tolerance gives a meaningful floor near zero, while a relative tolerance scales with the larger operand magnitude; a common rule accepts a difference below the greater bound. I do not copy Number.EPSILON because it only describes binary64 spacing near one. I define policies for NaN, infinities, and signed zero before subtracting. Tests cover zero, both signs, ordinary and maximum magnitudes, and values just inside and outside each bound. I also avoid using tolerant equality as a hash-key or sorting equivalence because it is not transitive.

Was this clear?

Range and failure handling

1 question
87 How should a service handle floating-point overflow, underflow, and nonfinite values? Mid occasional reveal ▾ hide ▴

Floating-point overflow usually produces an infinity rather than throwing, invalid arithmetic can produce NaN, and gradual underflow first reduces relative precision before a tiny result becomes zero. I therefore validate finite inputs and results at the domain boundary with a non-coercing predicate such as Number.isFinite. The contract must say whether overflow rejects the operation, saturates to a limit, or switches representation; silently accepting infinity is not a policy. I test the largest expected operands, overflow-producing combinations, the normal-to-subnormal boundary, signed zero, and serialization. Standard JSON has no NaN or infinity literal, so transport behavior must be deliberate rather than discovered after failure.

Was this clear?

Numerical stability

1 question
88 Why can summation order change a floating-point result, and how do you choose a stable approach? Senior occasional reveal ▾ hide ▴

Every addition rounds at the spacing of its intermediate magnitude, so floating-point addition is not generally associative. A small addend can disappear beside a large partial sum, and subtracting close approximate values can expose catastrophic cancellation. Chunking or parallelizing a reduction changes its rounding tree, which can change the last bits. I inspect input magnitudes and the required error bound, then consider pairwise summation, compensated summation, a reformulated expression, or a higher-precision representation. Tests mix very large and small values and compare with a higher-precision oracle. If bitwise reproducibility matters, I also fix the operation order, runtime behavior, and library implementation.

Was this clear?

Text validation

1 question
89 How do you use a regular expression for validation without confusing shape with meaning? Junior common reveal ▾ hide ▴

I first write the lexical contract: character repertoire, separators, length bounds, and whether the whole input must match. In JavaScript I verify the overall match consumes the entire string instead of assuming a successful substring or $ always means absolute end. I keep g and y out of an independent Boolean validator because they carry lastIndex. After the shape passes, ordinary code or a domain parser checks meaning, such as calendar validity or whether an identifier exists. Tests include valid input, leading and trailing junk, a final newline, boundary lengths, and shape-valid values that are semantically invalid.

Was this clear?

Performance and safety

1 question
90 What causes catastrophic regex backtracking, and how would you control the risk? Mid common reveal ▾ hide ▴

Backtracking is normal when an engine revisits a quantifier or alternative after later input fails. Risk grows when nested quantifiers or overlapping alternatives create many ways to consume the same prefix, especially on a long near miss that fails at the end. I remove ambiguous nesting, factor shared prefixes, replace broad wildcards with delimiter-aware classes where appropriate, and enforce input and repetition bounds before matching. I then measure adversarial near misses across increasing safe sizes in a worker or child process that the test harness can terminate. For exposed complex patterns, I consider a parser or an engine with a suitable worst-case guarantee.

Was this clear?

Pattern construction

1 question
91 How should dynamic text be included in a JavaScript regular expression? Mid occasional reveal ▾ hide ▴

I decide whether the dynamic value is trusted regex source or literal data; most user names, extensions, and search strings are data. Fixed patterns stay as regex literals. On Node 24, literal fragments pass through RegExp.escape() before they are embedded in new RegExp(), while trusted source is kept in a visibly separate path. I account for the two parsers: JavaScript string escaping happens before regex parsing in the constructor form. Tests use dots, brackets, parentheses, hyphens, backslashes, newlines, and Unicode. Escaping prevents syntax injection, but input bounds and a review of the surrounding fixed pattern are still required for performance safety.

Was this clear?

Runtime semantics

1 question
92 Which JavaScript regex state and Unicode details do you check during code review? Mid common reveal ▾ hide ▴

I inspect the flags first. With g or y, test() and exec() mutate lastIndex, so a shared validator or a test-then-exec sequence can skip matches; matchAll() is usually clearer for complete iteration. I verify whether u is required and name the intended unit: UTF-16 code unit, code point, grapheme, byte, ASCII digit, or Unicode decimal number. In ECMAScript, \d remains ASCII-only under u, while property escapes such as \p{Decimal_Number} express broader sets. Match indices are code-unit offsets, and regex matching neither segments graphemes nor normalizes text, so those policies need separate APIs and tests.

Was this clear?