Loading...
Loading...
Core CS and SQL interview guide
Processes, threads, scheduling, memory management and deadlocks. Every answer is short enough to say aloud, and every question links to the lesson that teaches it.
60 questionsLast updated
FIFO evicts the page that was loaded into memory earliest, using a queue. It is simple but ignores usage, so it may evict a page that is used constantly.
Follow-up: Why can FIFO be a poor choice? It ignores usage: a page loaded early may be used all the time, yet FIFO evicts it first. It can also show Belady's anomaly.
Common mistake: Saying FIFO evicts the page used least. It evicts the page loaded earliest, whatever its use.
Lesson: Virtual memory and page replacement algorithmsFor some reference strings, FIFO produces more page faults when given more frames. The string 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 gives 9 faults with 3 frames and 10 with 4.
Follow-up: Give the string and the numbers. For 1 2 3 4 1 2 5 1 2 3 4 5, FIFO makes 9 faults with 3 frames and 10 faults with 4 frames.
Common mistake: Saying more frames always means fewer faults. That holds for LRU and Optimal but not for FIFO.
Lesson: Virtual memory and page replacement algorithmsLRU evicts the page that has not been used for the longest time, using recent past as a predictor of the near future. It performs close to Optimal on programs with good locality.
Follow-up: What is the difference between LRU and Optimal? LRU looks at the past; Optimal needs the future, so it cannot be built and serves as a yardstick. LRU is the practical approximation.
Common mistake: Saying LRU evicts the least frequently used page. It evicts the least recently used one; frequency is LFU.
Lesson: Virtual memory and page replacement algorithmsEAT = (1 − p) × memory access time + p × page-fault service time. With 200 ns memory, 8 ms faults and p = 0.001, EAT is about 8.2 µs, about 40 times slower than memory.
Follow-up: Compute it for 200 ns memory, 8 ms faults and p = 0.0001. 0.9999 x 200 + 0.0001 x 8,000,000 = 199.98 + 800, about 1000 ns: five times slower than memory alone.
Common mistake: Forgetting to convert units. Milliseconds must become nanoseconds: 8 ms = 8,000,000 ns.
Lesson: Virtual memory and page replacement algorithmsTrap to the OS, check that the address is legal, find a free frame or choose a victim (writing it to disk if dirty), read the page from disk, update the page table and restart the faulting instruction.
Follow-up: What if there is no free frame? Choose a victim with the replacement algorithm. If it is dirty, write it to disk first, then load the new page into that frame.
Common mistake: Skipping the legality check. The OS first checks the address belongs to the process; if not, it ends the process with a segmentation fault.
Lesson: Virtual memory and page replacement algorithmsPrograms are not limited by physical RAM, more processes fit in memory at once, processes are isolated in their own address spaces, and memory can be shared, for example common libraries mapped into many processes.
Lesson: Virtual memory and page replacement algorithmsNot usually. It is a normal event in demand paging. Only an access to an address that is not part of the process at all is an error, which leads to a segmentation fault or access violation.
Lesson: Virtual memory and page replacement algorithmsIt is set when a page is written. When a dirty page is replaced, it must be written back to disk; a clean page can simply be dropped, which halves the cost of that fault.
Lesson: Virtual memory and page replacement algorithmsA fault costs milliseconds while a memory access costs nanoseconds, so one fault equals tens of thousands of accesses. For under 10% slowdown with those numbers, fewer than 1 in about 400,000 accesses may fault.
Lesson: Virtual memory and page replacement algorithmsThe sequence of page numbers a process accesses, with consecutive repeats removed. Page-replacement algorithms are compared by counting faults on the same reference string.
Lesson: Virtual memory and page replacement algorithmsIt evicts the page that will not be used for the longest time in the future. It gives the minimum possible number of faults but needs future knowledge, so it is used only as a benchmark.
Lesson: Virtual memory and page replacement algorithmsWith a counter or timestamp per page updated on every access, or a stack (linked list) where each accessed page moves to the top. Both need hardware help on every memory access, so exact LRU is rare.
Lesson: Virtual memory and page replacement algorithmsLFU evicts the least frequently used page; MFU evicts the most frequently used page, on the idea that a page used a lot has probably finished its work. Neither is common, because counts do not age well.
Lesson: Virtual memory and page replacement algorithmsFIFO makes 15 faults, LRU 12 and Optimal 9. This classic string is the one most textbooks and tests use.
Lesson: Virtual memory and page replacement algorithmsToo many processes for the available frames. Seeing low CPU utilisation, a simple scheduler admits more processes, which takes frames from everyone and increases faults further.
Lesson: Virtual memory and page replacement algorithmsThe working set is the set of distinct pages a process used in its last Δ references. If the sum of working-set sizes exceeds available frames, the OS suspends a process to prevent thrashing.
Lesson: Virtual memory and page replacement algorithmsToo small and it misses part of the current locality; too large and it covers several localities and overestimates. Systems approximate it using reference bits sampled at timer interrupts.
Lesson: Virtual memory and page replacement algorithmsGlobal replacement can pick a victim from any process, which uses memory flexibly but lets one process hurt others. Local replacement picks only from the faulting process's own frames, which isolates processes but may waste memory.
Lesson: Virtual memory and page replacement algorithmsAfter fork, parent and child share the same pages marked read-only. Only when one of them writes is that page copied, so fork followed by exec copies almost nothing.
Common mistake: Saying fork copies all the memory at once. With copy-on-write only the pages that are written are copied.
Lesson: Virtual memory and page replacement algorithmsIn Unix-like file systems, an inode is a record describing one file: size, owner, permissions, timestamps, link count and pointers to its data blocks. It does not contain the file name.
Follow-up: Can you run out of inodes while the disk still has free space? Yes. Millions of tiny files can use up all the inodes. df -i shows inode use, and creating a file then fails with "No space left on device".
Common mistake: Saying the inode stores the file name. The name lives in the directory entry that points to the inode number.
Lesson: File systems and basic Linux conceptsA hard link is another directory entry pointing to the same inode, so the data survives until all hard links are removed. A soft (symbolic) link is a separate small file storing a path; it can cross file systems and point to directories, but breaks if the target is deleted.
Follow-up: What happens to each if the original file is deleted? The hard link still reaches the data and the link count drops by one. The soft link breaks, because its path points to nothing.
Common mistake: Swapping them. A soft link breaks when the target is removed; a hard link keeps the data alive.
Lesson: File systems and basic Linux conceptsEach file has read, write and execute permissions for the owner, the group and others. ls -l shows them as rwxr-xr-x; in octal, r = 4, w = 2, x = 1, so that string is 755.
Follow-up: Why does a script need the x bit? Without execute permission the shell refuses to run the file directly. chmod +x script.sh sets it.
Common mistake: Running chmod 777 to fix a permission error. It lets every user change the file; give only what is needed, usually 755 or 644.
Lesson: File systems and basic Linux conceptschmod 755 mean?Owner gets read, write and execute (7); group and others get read and execute (5). It is typical for scripts and directories.
Follow-up: What is the difference between 644 and 600? 644 lets others read the file; 600 lets only the owner read and write, which suits private keys.
Common mistake: Reading 755 as 7 + 5 + 5. Each digit is one group: owner 7 (rwx), group 5 (r-x), others 5 (r-x).
Lesson: File systems and basic Linux conceptskill and kill -9?kill PID sends SIGTERM, which the program can catch to shut down cleanly, for example a Spring Boot app closing connections. kill -9 sends SIGKILL, which ends the process immediately with no cleanup, so it is a last resort.
Follow-up: What happens to a process that ignores SIGTERM? It keeps running until you send SIGKILL (kill -9) or it exits. SIGKILL is handled by the kernel and cannot be ignored.
Common mistake: Using kill -9 first every time. The app gets no chance to close files or finish writes, so try SIGTERM first.
Lesson: File systems and basic Linux conceptsThe part of the OS that organises data on storage into files and directories, keeps their metadata and tracks which blocks are free or used. Examples are ext4 and XFS on Linux, NTFS on Windows and APFS on macOS.
Lesson: File systems and basic Linux conceptsFCFS is fair but can move the head a lot. SSTF always serves the nearest request, which reduces movement but can starve far requests. SCAN sweeps back and forth like a lift, giving good throughput and no starvation.
Follow-up: Which of the three can starve a request? SSTF, because new requests near the head can keep winning while a far request waits. SCAN sweeps the whole disk, so every request is reached.
Common mistake: Naming algorithms without a number. Add the total head movement for a small queue to show you can compute it.
Lesson: File systems and basic Linux conceptsA file is a named collection of related data on storage. Its attributes include name, type, size, location of its blocks, owner, permissions and timestamps for creation, modification and access.
Lesson: File systems and basic Linux conceptsHard links to directories could create loops in the tree, so they are not allowed for normal users. Inode numbers are only unique within one file system, so a hard link cannot refer to an inode on another one.
Lesson: File systems and basic Linux conceptsAny free block can be used, so there is no external fragmentation and files grow easily. But random access is slow, pointers use space, and one damaged pointer loses the rest of the file. FAT stores the chain in a table to speed it up.
Lesson: File systems and basic Linux conceptsAn index block lists all the file's block numbers, giving fast random access. Inodes use a few direct pointers for small files and single, double and triple indirect blocks for large ones.
Lesson: File systems and basic Linux conceptsPointers per block = block size ÷ pointer size. Max blocks = direct + p + p² + p³ for single, double and triple indirect; multiply by block size. With 4 KB blocks, 4-byte pointers and 12 direct pointers, it is about 4 TB.
Follow-up: Give the numbers for 1 KB blocks and 4-byte pointers. A block holds 256 pointers. With 12 direct, 1 single, 1 double and 1 triple indirect: 12 + 256 + 65,536 + 16,777,216 blocks of 1 KB, about 16 GB.
Lesson: File systems and basic Linux conceptsThe file system writes its intended metadata changes to a log, the journal, before applying them. After a crash, it replays or discards the journal instead of scanning the whole disk, so recovery is fast and consistent. ext4 and NTFS are journaling file systems.
Follow-up: What does a journal protect against? A crash in the middle of an update. After a restart the system replays or discards the log, so the file system stays consistent.
Lesson: File systems and basic Linux conceptsIt orders pending disk requests to reduce head movement, because on a hard disk seek time is the biggest part of access time. Better ordering means higher throughput and lower average wait.
Lesson: File systems and basic Linux conceptsSCAN serves requests in both directions. C-SCAN serves only while moving in one direction, then jumps back to the start without serving, which gives more uniform waiting times across cylinders.
Lesson: File systems and basic Linux conceptsLOOK is SCAN that turns around at the last pending request in each direction instead of going all the way to the disk edge. C-LOOK is the one-direction version.
Lesson: File systems and basic Linux conceptsThe kernel is the core of the OS that manages hardware, processes and memory. The shell, such as bash, is a user program that reads commands and asks the kernel to run them.
Lesson: File systems and basic Linux conceptsIt lets you enter the directory and access files inside it by name. Read permission on a directory lets you list its names; you need execute to cd into it.
chmod and chown?chmod changes the permission bits of a file; chown changes its owner and group. To let the app user write a folder, chown appuser:appuser dir is safer than chmod 777.
tail -f app.log | grep ERROR. tail -f keeps printing new lines as they are written, and grep keeps only matching ones.
df -h for free space on each file system, du -sh * for the size of each item in a folder, and free -h for RAM and swap. top shows live CPU and memory per process.
> and >> in the shell?> redirects output to a file and overwrites it; >> appends to the end. 2>&1 sends error output to the same place as normal output.
A pipe, written |, connects the output of one command to the input of the next, so small tools combine: ps aux | grep java | wc -l counts Java processes. Inside the kernel it is an inter-process communication channel.
Exit code 137 is 128 + 9, which means the process got SIGKILL. The usual sender is the kernel's out-of-memory killer, because the container reached its memory limit. I would check the container memory limit, keep the JVM heap well below it, and look for a leak.
Follow-up: Why is -Xmx equal to the container limit a bad idea? The JVM also uses memory outside the heap: thread stacks, metaspace and native buffers. The total must stay below the limit, so I leave a margin.
Common mistake: Blaming Docker or a random crash. Exit 137 points to SIGKILL, and the usual sender is the out-of-memory killer.
Lesson: Practice: OS rapid-fire and numericalsA web server needs quick responses for many short requests, so a preemptive scheme such as Round Robin or a multilevel feedback queue fits. A nightly batch with known run times fits SJF, because it minimises the average waiting time and nobody is waiting for an interactive response.
Follow-up: Why is plain FCFS a poor choice for the web server? One slow request would hold the CPU and everything behind it would wait: the convoy effect.
Common mistake: Choosing SJF for a server. It needs burst times in advance and can starve long requests.
Lesson: Practice: OS rapid-fire and numericalsThe thread makes a system call to read from the network socket and, if the data is not there yet, moves to the waiting state. The scheduler runs another ready thread meanwhile. When the data arrives, an interrupt is handled, the thread goes back to ready, and later it runs again.
Follow-up: Does the waiting thread use CPU time? No. A blocked thread uses no CPU; it just sits in a wait queue until the I/O completes.
Common mistake: Saying the thread spins on the CPU while it waits. A blocked thread uses no CPU.
Lesson: Practice: OS rapid-fire and numericalsNot necessarily. BLOCKED means a thread waits to enter a synchronized block, which is normal under contention. It is a deadlock only when the waits form a cycle, and jstack then prints "Found one Java-level deadlock" with the locks and threads involved.
Follow-up: Which tool prints the thread dump? jstack <pid> or jcmd <pid> Thread.print, or kill -3 on Linux for the dump in the application output.
Common mistake: Calling every BLOCKED thread a deadlock. BLOCKED is normal while waiting for a lock; a deadlock needs a cycle of waits.
Lesson: Practice: OS rapid-fire and numericalsIt looks like a deadlock: one thread locked account A and wants B, the other locked B and wants A. I would take a thread dump to confirm, then fix it by always locking the account with the lower id first. That breaks circular wait, and I would add a test that runs opposite transfers in parallel.
Follow-up: What is another fix if ordering is not possible? Use tryLock with a timeout: if the second lock is not free, release the first and retry after a random delay.
Common mistake: Wrapping the whole method in one global synchronized or just restarting the service. That hides the bug and hurts throughput.
Lesson: Practice: OS rapid-fire and numericalsOpening a connection is expensive: it needs a network handshake, authentication and a server-side thread or process. A pool opens connections once and reuses them, so requests start faster and the database sees a steady, limited number of sessions instead of thousands.
Lesson: Practice: OS rapid-fire and numericalsA file descriptor is a small number the kernel gives a process for each open file, socket or pipe. Each process has a limit on them. A server that never closes sockets or streams hits the limit and new connections fail.
Follow-up: How do you fix it? Raise the limit with ulimit -n or LimitNOFILE in the systemd service, but first look for a leak: streams or sockets that are never closed.
Common mistake: Raising the limit without looking for a leak. If the code never closes streams, a bigger limit only delays the failure.
Lesson: Practice: OS rapid-fire and numericalsnohup or & only survives the logout. For a real server I would make a systemd service with Restart=always and enable it, or run the app in Docker with a restart policy. Then the system starts it at boot and restarts it after a crash.
Follow-up: What would you do in a Docker setup? Use a restart policy such as restart: unless-stopped in Compose, so the Docker daemon starts the container again after a crash or reboot.
Common mistake: Using nohup alone. It survives logout but not a crash or a reboot.
Lesson: Practice: OS rapid-fire and numericalsI run df -h to see which file system is full, then du -sh * in that folder and repeat in the biggest sub-folder. Logs and old build files are common culprits. If df shows full but du does not, a deleted file may still be held open by a process, which lsof can show.
Lesson: Practice: OS rapid-fire and numericalsSwap is disk space the OS uses to hold pages that do not fit in RAM. A little swap protects against sudden spikes, but a JVM heap that is swapped out makes garbage collection extremely slow. I size the heap to fit in RAM so the server does not rely on swap.
Lesson: Practice: OS rapid-fire and numericalsA container is an ordinary group of processes on the host's kernel. Namespaces give it its own view of processes, network and files, and cgroups limit its CPU and memory. So a container starts fast and is lighter than a virtual machine.
Follow-up: Does a container have its own kernel? No, it shares the host kernel. A virtual machine has its own kernel, which is why it is heavier.
Common mistake: Describing a container as a small virtual machine. It is an isolated set of processes on the shared kernel.
Lesson: Practice: OS rapid-fire and numericalsI state the assumption in the answer and then solve consistently. For example, on equal bursts I pick the earlier arrival, and in Round Robin a new arrival at the end of a quantum joins the queue before the preempted process. A clear assumption earns marks even if the book uses another convention.
Common mistake: Silently choosing a rule. A different convention gives a different chart, so say which one you used.
Lesson: Practice: OS rapid-fire and numericalsOptimal is always at least as good, because it knows the future. LRU is usually better than FIFO, but on an unusual string FIFO can win, so I never assume an order between those two. Only Optimal gives the guaranteed minimum.
Lesson: Practice: OS rapid-fire and numericalsAfter a switch the new thread finds the cache and TLB filled with the old thread's data, so it starts slowly. That is why a pool for CPU-bound work is about the number of cores: more threads add switching without adding speed. I/O-bound pools can be larger because their threads mostly wait.
Lesson: Practice: OS rapid-fire and numericalsA daemon is a background process with no terminal that provides a service. A cron job is a task started by the cron scheduler at set times. A systemd service is how a modern Linux system starts, stops and restarts daemons and checks their health.
Lesson: Practice: OS rapid-fire and numericalsA report job runs at low priority, and checkout traffic keeps the CPU busy, so the report never finishes. The fix is aging, which raises its priority while it waits, or a guaranteed share of CPU for the batch queue.
Lesson: Practice: OS rapid-fire and numericalsA TLB miss means the translation is not in the small TLB cache, so the page table in memory is read; the page is still in RAM and the cost is a few memory reads. A page fault means the page is not in RAM, so the OS must load it from disk, which costs milliseconds.
Follow-up: Can a TLB miss happen without a page fault? Yes, and it is far more common. Most TLB misses find the page in RAM; only a missing page causes a fault.
Common mistake: Using the two terms for the same event. A TLB miss costs nanoseconds; a page fault costs milliseconds.
Lesson: Practice: OS rapid-fire and numericalsEach process has its own address space, so a variable in one is invisible to the other. They use inter-process communication: pipes, sockets, message queues or shared memory. ShopLite's services talk over HTTP, which runs on sockets.
Lesson: Practice: OS rapid-fire and numericalsEach lesson has quizzes, practice and more interview questions on the same topic.
Open the first lesson