TRT
Sign in

topic / language

Programming languages

C++ first: the language-specific practice and interview prep, grouped so new languages slot in beside it.

Hands-on C++ practice problems and interview questions, from first programs to memory, templates, and concurrency. Each language lives in its own folder under this topic, so adding Java or Python later means adding one folder, not restructuring the site.

  • 0 articles
  • 0 videos
  • 0 traces
  • 0 flows
  • 215 interviews
  • 215 total

Articles

// empty

No articles published in this topic yet

The queue is running. Subscribe to the dispatch to be told the moment this topic ships.

Join the dispatch

Request flows

// empty

No request flows in this topic yet

Interactive request journeys will appear here as this topic is built out.

Browse request flows

Videos

// empty

No videos yet

Video coverage for this topic is planned. Watch the library page for updates.

Browse videos

Traces

// empty

No traces in this topic yet

Traces are the step-by-step walkthroughs. They land as the topic matures.

Browse traces

Interviews

GO

easy · t1Walk through the internal structure of a Go channel (`hchan`), explain the exact table of channel state behaviors (nil vs open vs closed for send, receive.Detail `hchan` (`buf`, `sendx`, `recvx`, `sendq`, `recvq`, `lock`), `sendDirect` stack-to-stack copy, the nil/open/closed matrix, and buffered (`cap=1`) vs `select`+`ctx.Done()` fixes.easy · t1How does Go's compiler decide whether a variable is allocated on the stack or the heap (Escape Analysis), why is returning a value `User` often faster than.Explain downward pointer sharing (stack-safe) vs upward pointer returning (heap-escape), inspect `-gcflags=-m`, and trace `Unwrap()` trees in `errors.Is`/`As`.easy · t1Explain how Go's Concurrent Tri-Color Mark-and-Sweep GC works—why doesn't Go use a compacting/generational GC like the JVM, how does the Hybrid Write Barrier.Explain value types + escape analysis + size-class `mspan` allocators (why compaction isn't needed), trace White/Grey/Black + Hybrid Write Barrier, and detail the `GOMEMLIMIT` (~90% of container memory) production formula.easy · t1Explain the Go GMP scheduler in detail—what are G, M, and P, what is the `runnext` slot, how does work-stealing work, how does the Netpoller differ from.Walk through `G`, `M`, `P`, the 1-slot LIFO `runnext` optimization, `schedtick % 61` global fairness, 50% work-stealing, `epoll` Netpoller vs `handoffp`, and Kubernetes CFS quota throttling.easy · t1Explain how interfaces are represented in the Go runtime (`iface` vs `eface` and the `itab` table), why returning a `nil` concrete pointer as `error` breaks.Trace the 16-byte `(tab, data)` struct, explain `itab` hash-table lookup on interface conversion, and contrast `[]T`'s contiguous memory layout against `[]any`'s array of 16-byte `eface` structs.easy · t1Explain how Go maps work internally (`hmap`, `bmap` `[8]tophash`/`[8]K`/`[8]V`, incremental evacuation, and Go 1.24 SwissTables)—why is map iteration order.Walk through bucket layout, incremental `growWork`, why `delete` doesn't shrink buckets, why `fatal error` bypasses `recover()`, and `sync.Map` vs sharded `RWMutex`.easy · t1How does `sync.Pool` avoid lock contention across 64 CPU cores, why did Go 1.13 add a 'victim cache' to `sync.Pool`, and how do you combine `sync.Pool` and.Explain per-`P` `poolLocal` private slots + lock-free `poolChain` ring buffers, the 2-GC-cycle `victim` cache that smooths allocation spikes after GC, and `singleflight` context detachment.easy · t1How does `select` work inside the Go runtime (`pollorder` and `lockorder`), how does `context.Context` propagate cancellation across goroutines in $O(1)$, and.Explain `selectgo`'s random poll permutation and address-sorted locking, `close(done)` broadcast semantics, and `errgroup.WithContext` scoping.easy · t1Explain Go's 24-byte slice header—when does `append` mutate an existing slice's backing array, how can slicing cause a 100 MB memory leak in Go, and how do.Trace `(ptr, len, cap)`, `growslice` growth thresholds, backing-array retention leaks on small sub-slices, and three-index slicing `s[i:j:k]`.easy · t1How are strings represented in memory in Go, why does `s[i]` return a `byte` while `for _, r := range s` yields a `rune`, when does `string(byteSlice)` avoid.Explain the 16-byte `(ptr, len)` string header, UTF-8 byte vs rune indexing, compiler zero-copy optimizations for `m[string(b)]`, and `strings.Builder` + `Grow()`.

Python

easy · t1Walk through what happens under the hood when an `asyncio` coroutine executes `await client.get(url)`—how do Coroutines, Futures, Tasks, and `epoll` interact.Trace `Task.__step()` calling `coro.send(None)`, yielding a `Future` up the `await` chain, `loop.add_reader(fd)` on `epoll`, `Task.__wakeup`, and `asyncio.to_thread` / `ProcessPoolExecutor`.easy · t1How does the `asyncio` event loop actually work under the hood (coroutines, `Future`, `Task._step()`, `epoll`/`kqueue`), when do you still need `asyncio.Lock`.Trace `Task._step()` driving `coro.send(None)`, explain read-modify-write races across `await` points, and use `loop.set_debug(True)` / lag monitors.easy · t1Do Python type hints (`def f(x: int) -> int:`) make CPython run faster? Explain how CPython's bytecode evaluation loop and PEP 659 Adaptive Specialization.Clarify that static annotations do not speed up CPython directly, but runtime type stability triggers PEP 659 inline caches (`BINARY_OP_ADD_INT`, `LOAD_ATTR_SLOT`, `CALL_PY_EXACT_ARGS`).easy · t1Walk through how you diagnose and optimize a slow Python service in production—from profiling (`py-spy` / `tracemalloc`), to algorithmic/data-structure fixes.Synthesize sampling vs deterministic profiling, Python-level optimizations (`dict`/`deque`/`__slots__`/`memoryview`), and zero-copy `Py_buffer` + `allow_threads` FFI boundary design.easy · t1Explain how closures work at the bytecode/memory level in CPython (`PyCellObject`, `LOAD_DEREF`, `nonlocal`), why lambdas in a loop all see the final loop.Trace `co_freevars`, `co_cellvars`, `__closure__`, `UnboundLocalError`, and 3-layer parameterized decorators `def retry(max_attempts):`.easy · t1How does the Descriptor Protocol power methods (`self`), `@property`, and `@functools.cached_property` in Python—and why is `@cached_property` a Non-Data.Walk through the 3-step `object.__getattribute__` algorithm, explain how functions bind `self` via `__get__`, and trace why `@cached_property` omits `__set__` so `obj.__dict__` shadows it on subsequent reads.easy · t1Why does `threading.local()` cause cross-request data leaks in `asyncio` applications, how does `contextvars.ContextVar` work under the hood (HAMT + `Token`).Explain single-thread multiplexing in `asyncio`, `Python/hamt.c` persistent tries, `var.set()`/`var.reset(token)`, and `contextvars.copy_context().run(...)`.easy · t1Why does `threading.local()` break in `asyncio`, how does `contextvars` use a persistent HAMT to achieve O(1) context copying across `create_task()`, and what.Contrast OS-thread-bound storage with `Task._step()` context swapping, explain HAMT structural sharing, and show `token = var.set()` / `var.reset(token)`.easy · t1Compare `@dataclass(slots=True, frozen=True)`, `NamedTuple`, `TypedDict`, and Pydantic `BaseModel`—how do their memory layouts, instantiation speeds, and.Contrast C-slot structs (`dataclass(slots=True)`), tuple subclasses (`NamedTuple`), static-only dicts (`TypedDict`), and Rust-backed boundary validators (Pydantic v2 / `msgspec`).easy · t1What does the CPython GIL actually protect, when is it released, why isn't `x += 1` thread-safe under the GIL, and how does PEP 703 (Python 3.13t/3.14t).Detail `ob_refcnt` and `pymalloc` protection, `eval_breaker` 5-ms switching, `Py_BEGIN_ALLOW_THREADS`, and PEP 703's trio: Immortal Objects, Biased Reference Counting, and `mimalloc`.easy · t1What is the exact difference between an Iterable and an Iterator in Python, how does a generator preserve local variables across `yield` without using the C.Contrast `__iter__` (Iterable) with `__iter__ + __next__` (Iterator), explain heap-allocated `PyFrameObject` suspension, and trace `yield` + `finally` cleanup in context managers / dependencies.medium · t1How are `list` and `dict` implemented inside CPython, why is `dict` ordered since Python 3.7, and how do Key-Sharing Dicts (PEP 412) and `__slots__` save.Walk through `PyListObject`'s `ob_item` pointer array, `PyDictObject`'s split `indices` + `entries` tables, and instance `__dict__` vs `__slots__`.easy · t1How do you parallelize CPU-bound work across 8 cores in Python without getting killed by `pickle` IPC overhead or `fork()` multithreaded deadlocks?Compare `fork`, `spawn`, and `forkserver`, explain `ProcessPoolExecutor(initializer=...)` vs `SharedMemory` + `numpy.ndarray(buffer=shm.buf)`, and detail `/dev/shm` cleanup via `SharedMemoryManager`.easy · t1Explain why mutable default arguments and `[[0]*N]*M` fail in Python, why `if not bucket:` is a subtle bug compared to `if bucket is None:`, and how.Trace `fn.__defaults__`, distinguish falsy empty lists `[]` from `None`, and explain `deepcopy`'s `memo` cycle-detection dictionary.easy · t1What is inside a CPython PyObject in memory, how does `b = a` work under the hood, and why does `1000 is 1000` behave differently in a script vs the REPL?Explain the 16-byte PyObject header (ob_refcnt, ob_type), small-integer interning [-5, 256], compiler constant folding per code object, and PEP 683 immortal objects.

Rust

medium · t1Explain how `async fn` compiles into a state machine in Rust, why self-referential futures require `Pin<&mut Self>`, how stack pinning (`std::pin::pin!`).Trace the compiler-generated `enum` across `.await` yield points, `Pin` / `Unpin`, `Waker` readiness notifications, and `tokio::select!` drop cancellation.easy · t1Explain how Rust's borrow checker (`&T` XOR `&mut T`), Lifetime annotations (`fn longest<'a>(x: &'a str, y: &'a str) -> &'a str`), and disjoint field.Explain lifetime variance/intersection (`'a` is the smaller of the two input lifetimes), struct field borrow splitting, and why `split_at_mut` encapsulates an internal `unsafe` bounds-checked pointer split.medium · t1What are the exact rules for writing sound `unsafe` Rust (aliasing, alignment, `MaybeUninit`, `catch_unwind` across FFI), how does `cargo miri` detect.Detail the 5 `unsafe` operations, Stacked/Tree Borrows in `Miri`, `MaybeUninit`T``, `extern "C-unwind"` panic safety, and C11/Rust memory orderings.easy · t1How are Rust enums laid out in memory (tagged unions + niche optimization), why does a large `Err` variant hurt `Ok` performance in `Result<T, E>`, and how.Explain union sizing (`max(variants) + tag`), `NonZero*` / `NonNull` niches, `Box<LargeError>` to shrink `Result`, and why `?` avoids DWARF stack unwinding.easy · t1Explain how Rust's Ownership, Move semantics, and `Drop` eliminate both garbage-collection pauses and C/C++ use-after-free/double-free bugs—and how Rust's.Trace the 24-byte `Vec`/`String` stack header, mutually exclusive `Copy` vs `Drop`, conditional move drop flags on the stack, and `mem::take` / `mem::replace`.easy · t1Explain how `Send`, `Sync`, and `UnsafeCell`T`` work together in Rust—why is `RefCell`T`` `Send` but `!Sync`, why is `Rc`T`` both `!Send` and `!Sync`, and how.Prove why `RefCell` is `Send + !Sync`, why `Rc` is `!Send + !Sync`, why `Mutex`T`` owns `T` inside the lock, and when `std::sync::Mutex` is faster than `tokio::sync::Mutex`.easy · t1Contrast static dispatch (`impl Trait` / `<T: Trait>`) and dynamic dispatch (`&dyn Trait` / `Box<dyn Trait>`) in Rust—how is a Rust vtable laid out, what are.Explain monomorphization + LLVM inlining, the 16-byte `(data_ptr, vtable_ptr)` fat pointer, `where Self: Sized` escape hatches on object-safe traits, and the inner non-generic function idiom.

Typescript

medium · t1Explain how to implement Zero-Cost Branded Types in TypeScript, how distributive conditional types and `infer` work (e.g., implementing `Awaited<T>` or.Write the `Brand<T, B>` phantom symbol intersection, implement recursive `MyAwaited<T>` with `infer U`, and contrast method bivariance with function-property contravariance.easy · t1Explain V8 Hidden Classes (Shapes/Maps) and Inline Caches (Monomorphic, Polymorphic, Megamorphic). Why doesn't a TypeScript `interface` automatically.Walk through in-object property offsets, Map transition trees, the 4-shape polymorphic threshold, `delete` dictionary degradation, and why TypeScript type erasure leaves runtime property order in control.easy · t1Explain the exact execution order of the Call Stack, `process.nextTick`, the V8 Promise Microtask Queue, `setTimeout(fn, 0)`, and `setImmediate(fn)` in.Diagram the 6 `libuv` phases, explain why `nextTick` and Promise microtasks run between every phase callback, show how `perf_hooks.monitorEventLoopDelay()` measures P99 lag, and fix microtask starvation with time-budgeted `setImmediate` yields.medium · t1Implement a bounded concurrency runner `mapWithConcurrency(items, limit, signal, worker)` in TypeScript that maintains at most `limit` in-flight tasks without.Write the pull-based `nextIndex++` coroutine lane pattern, compose `AbortSignal.any([parentSignal, poolController.signal])`, and explain why `nextIndex++` has no race condition on a single JS thread.medium · t1How does stream backpressure work under the hood in Node.js (`highWaterMark`, `write() -> false`, `'drain'`, `pipeline`), and how can `Buffer.subarray()` both.Walk through the producer/consumer `highWaterMark` state machine, why `.pipe()` leaks file descriptors on client disconnect, `DataView` `byteOffset` bugs on Node's 8 KB slab allocator, and slab retention in LRU caches.easy · t1How do Discriminated Unions and `assertNever(x: never)` eliminate illegal runtime states in TypeScript, and why should every external boundary (`JSON.parse`.Explain set-theoretic narrowing, making illegal states unrepresentable, why `any` infects the call graph by disabling type checking, and how schema validators (Zod/Valibot) narrow `unknown` into typed discriminated unions.medium · t1Explain how V8's Orinoco Garbage Collector (NewSpace Semi-Space Scavenger vs OldSpace Mark-Sweep-Compact, Write Barriers, and Remembered Sets) and Array.Contrast $O(\text{live})$ NewSpace copying with OldSpace concurrent marking, explain Old-to-New Write Barriers, trace premature promotion when request latency exceeds 2 scavenge intervals, and explain why `TypedArray` Structure-of-Arrays bypasses GC scanning.hard · t1Design a zero-copy multi-core worker pool in TypeScript/Node.js using `worker_threads`. Compare Structured Clone (`postMessage(obj)`), Transferables.Explain V8 Isolate memory separation, why `postMessage(obj)` bottlenecks the main thread, ping-pong double buffering with Transferables, and how `Atomics.store`/`load` prevent ARM64 memory reordering in a `SharedArrayBuffer` ring.

C

medium · t1When would you use an arena allocator instead of malloc?Explain arena allocation trade-offs: fast allocation, no per-object free, bulk deallocation, and fragmentation.easy · t1Arrays versus pointers: are they the same?Explain that arrays and pointers are distinct types, though arrays often decay into pointers.medium · t1What does AddressSanitizer detect that valgrind does not, and vice versa?Compare ASan's compile-time instrumentation (fast, detects use-after-free/overflow) versus valgrind's runtime emulation (slow, no recompile).medium · t1What makes a function async-signal-safe?Explain that async-signal-safe functions can be called from a signal handler, and list examples like write but not printf/malloc.medium · t1What is the difference between sequential consistency and acquire-release?Explain memory_order_seq_cst total ordering versus memory_order_acquire/release for synchronization without full ordering.easy · t1Why does sequential array access outperform random access?Explain spatial locality, cache line prefetching, and how sequential access fills cache lines efficiently.medium · t1What are deferred versus asynchronous cancellation?Explain deferred cancellation (cancellation points only) versus asynchronous (immediate, unsafe) and why deferred is preferred.hard · t1Design a memory-safe collections library in C.Discuss API design, ownership semantics, error handling without exceptions, and testing strategies for a C collections library.easy · t1What happens between typing gcc hello.c -o hello and seeing your program run?Explain the four stages of the C compilation pipeline — preprocessing, compilation, assembly, and linking — and what artifact each produces.easy · t1How do you tell a compiler error apart from a linker error in C, and what causes each?Distinguish syntax and type errors caught per translation unit by cc1 from unresolved or duplicate symbol errors caught across object files by ld.easy · t1Why must condition variable waits be in a predicate loop?Explain spurious wakeups and that waking does not guarantee the condition holds, so re-check in a while loop.hard · t1What must be saved and restored during a manual context switch?Explain saving callee-saved registers, stack pointer, instruction pointer, and restoring them to resume execution.medium · t1How does cooperative I/O integrate with epoll?Explain yielding a coroutine on epoll_wait, registering interest, and resuming when the descriptor is ready.hard · t1Design a full user-space coroutine runtime in C.Discuss stack management, context switching, M:N scheduling, cooperative I/O integration, and synchronization primitives.medium · t1How is a coroutine different from a thread?Explain cooperative (not preemptive) scheduling, single stack vs shared, and explicit yield/resume versus kernel scheduling.

CPP

hard · t1Why does adding a field break old apps that link your library?Explain mangled names, class layout shifts, and append-only rules that keep shipped libraries compatible.medium · t1What is the difference between an abstract class with shared state and a pure interface?Contrast pure virtuals, shared helpers, narrow interfaces, and how derived types become concrete by defining every contract function.medium · t1Why does a relaxed flag expose incomplete data while acquire-release does not?Explain release-acquire publication, the happens-before edge, and three-permit semaphore bounds for concurrent workers.hard · t1When does a custom pool allocator and lock-free queue beat std::queue with std::mutex in production, and when should you stick with the STL?Evaluate contention profiles, latency tail behavior, maintenance complexity, and C++17 std::pmr alternatives across realistic thread counts.easy · t1Who calls main and where does its return value go?Explain startup code, chained insertions, namespaces, and the exit status of a minimal C++ program.easy · t1How do vector and array differ in size knowledge and copying?Compare raw arrays with array and vector on size tracking, copy rules, and checked access.easy · t1How does array indexing compute an element address?Explain contiguous layout, zero based offsets, and why out of range access has no check.medium · t1When should you choose map over unordered_map for lookup?Compare ordered tree cost and iteration order against hashed average cost, rehash, and hash quality effects.medium · t1When does an atomic counter beat a mutex-guarded counter?Compare fetch_add indivisibility with lock cost, flag signaling with exchange, and sharding for hot contended counters.hard · t1Why do naive C++ microbenchmarks often produce misleading or irreproducible numbers, and how do you make a benchmark trustworthy?Identify compiler dead-code elimination, cold page faults, CPU frequency scaling, and wrong clock choices, and explain how to fix each one.easy · t1Why do raw struct bytes fail as a portable file format?Explain binary writes, fixed width types, defined byte order, and random access by record size.easy · t1When does the right side of and or or never run?Explain precedence, De Morgan rewrites, and why short-circuit order makes operand placement part of program logic.medium · t1When would you use each of the four named casts, and why is const_cast dangerous on truly const objects?Covers static, dynamic, const, and reinterpret cast use cases, the polymorphic requirement for dynamic_cast, and the undefined behavior of writing through const_cast on immutable storage.medium · t1How does a class template stamp a distinct class per argument list?Describe Pair instantiation, layout per argument list, const-correct members, and header placement for member definitions.easy · t1Why does a class with private data protect its invariant better than a struct?Explain access control, invariants, and destructor timing for a first class type.

Explore adjacent