CS Fundamentals Cheat Sheet
The 20 operating system, database and networking concepts that come up again and again in interviews, each boiled down to a crisp definition and the facts worth saying out loud.
Core CS questions are the quiet filter in many interview loops: they show up in phone screens, as follow-ups to coding rounds and inside system design discussions. They are rarely hard, but a vague answer costs more than you think, especially when you have been away from textbooks for a while.
Work through one group per sitting. For each item, try to explain it aloud in under a minute before reading the bullets, then tick it off once you can answer the usual follow-up without notes.
Operating Systems
How the OS shares CPU, memory and locks between running programs.
1Process vs ThreadOS
A process is a running program with its own address space and resources. A thread is a unit of execution inside a process; threads of one process share its heap, code and open files but each has its own stack and registers.
- Processes are isolated: a crash in one does not corrupt another; communication needs IPC (pipes, sockets, shared memory).
- Threads are cheaper to create and switch, and communicate through shared memory, which is why they need synchronization.
- A process has at least one thread; the PCB stores process state, a TCB stores per-thread state.
- Interview angle: Chrome uses processes per tab for isolation; a web server uses a thread pool for cheap concurrency.
2Context switchingOS
Saving the state (registers, program counter, stack pointer) of the running task and loading the state of the next one so the CPU can be shared. It is pure overhead: no useful work happens during the switch.
- Triggered by timer interrupts (time slice ends), blocking I/O, system calls or a higher-priority task becoming ready.
- Thread switches within a process are cheaper than process switches: no address-space change, so the TLB need not be flushed.
- Too many switches (tiny time slices, too many threads) means the CPU spends its time switching instead of working.
3CPU schedulingOS
The scheduler picks which ready process runs next. Goals trade off against each other: throughput, CPU utilisation, low waiting and turnaround time, fast response time and fairness.
- Preemptive: the OS can take the CPU away mid-run (Round Robin, SRTF, preemptive priority). Non-preemptive: a task runs until it blocks or finishes (FCFS, SJF).
- SJF gives minimum average waiting time but needs burst estimates and can starve long jobs.
- Priority scheduling can starve low-priority tasks; the fix is aging (slowly raise priority of waiting tasks).
- Round Robin quantum: too small means context-switch overhead, too large degrades to FCFS.
Algorithm Preemptive? Key idea Weakness FCFS No run in arrival order convoy effect SJF No shortest burst first starvation, needs estimate SRTF Yes shortest remaining first starvation Round Robin Yes fixed time quantum quantum tuning Priority Either highest priority first starvation -> aging Multilevel Q Yes queues per class complex tuning
4DeadlockOS
A set of tasks each waiting for a resource held by another task in the set, so none can ever proceed. It needs all four Coffman conditions at once; break any one and deadlock is impossible.
- Coffman: mutual exclusion, hold and wait, no preemption, circular wait.
- Prevention: break a condition, e.g. always acquire locks in a fixed global order (kills circular wait) or request all resources up front.
- Avoidance: Banker's algorithm grants a request only if the system stays in a safe state (some order exists in which everyone can finish).
- Detection and recovery: build a wait-for graph, find a cycle, then kill or roll back a victim. Ignoring it (ostrich) is what most desktop OSes do.
5Mutex vs SemaphoreOS
A mutex is a lock with ownership: only the thread that locked it may unlock it, and it lets exactly one thread into a critical section. A semaphore is a counter with wait (P) and signal (V) that allows up to N concurrent holders and has no owner.
- Binary semaphore (0/1) looks like a mutex but any thread can signal it, so it suits signalling between threads.
- Counting semaphore limits access to a pool, e.g. at most 10 DB connections.
- Classic uses: mutex for protecting shared data, semaphores for producer-consumer (empty/full counts).
- Java:
ReentrantLock/synchronizedfor mutex,java.util.concurrent.Semaphorefor counting.
6Race conditionOS
A bug where the result depends on the timing of threads accessing shared data, at least one of them writing. The code that touches the shared data is the critical section and must run under mutual exclusion.
count++is read-modify-write (load, add, store), so two threads can both read 5 and both write 6: a lost update.- A correct critical-section solution needs mutual exclusion, progress and bounded waiting.
- Fixes: locks (
synchronized), atomic CAS operations (AtomicInteger) or avoiding shared mutable state altogether. volatilegives visibility, not atomicity: it does not fixcount++.
class Counter { private int unsafe = 0; private int safe = 0; private final java.util.concurrent.atomic.AtomicInteger atomic = new java.util.concurrent.atomic.AtomicInteger(); void unsafeInc() { unsafe++; } // race: updates can be lost synchronized void safeInc() { safe++; } // one thread at a time void atomicInc() { atomic.incrementAndGet(); } // lock-free CAS }
7Virtual memory & pagingOS
Each process sees a large private virtual address space; the OS and MMU map it in fixed-size pages onto physical frames, keeping only the needed pages in RAM and the rest on disk. This gives isolation and lets programs exceed physical memory.
- Page table maps virtual page number to frame; the TLB is a small hardware cache of recent translations so most lookups skip the table.
- Page fault: the page is not in RAM, so the OS loads it from disk (evicting a victim via LRU, FIFO or Clock) and retries the instruction.
- Thrashing: working sets do not fit in RAM, so the system spends most of its time paging. Fix by reducing multiprogramming or adding memory.
- Paging removes external fragmentation but has some internal fragmentation in the last page.
DBMS
Transactions, schema design and how databases stay fast and correct.
8ACIDDBMS
The four guarantees of a database transaction, so a group of changes behaves like one safe unit even with crashes and concurrent users.
- Atomicity: all or nothing; implemented with undo logs and rollback.
- Consistency: a transaction moves the DB from one valid state to another (constraints, foreign keys hold).
- Isolation: concurrent transactions do not see each other's partial work; strength is set by the isolation level.
- Durability: once committed, data survives crashes; implemented with write-ahead logging (WAL) flushed to disk.
9NormalizationDBMS
Splitting tables so each fact is stored once, which removes insert, update and delete anomalies caused by redundancy. Each normal form adds one rule on top of the previous.
- Denormalize deliberately for read-heavy workloads (fewer joins) and accept the cost of keeping copies in sync.
- Know how to spot a partial dependency (2NF) and a transitive dependency (3NF) on a small example table.
1NF atomic values, no repeating groups or lists in a cell 2NF 1NF + no partial dependency (non-key column depends on the WHOLE composite key) 3NF 2NF + no transitive dependency (non-key column must not depend on another non-key) BCNF for every dependency X -> Y, X must be a super key (stricter 3NF)
10IndexingDBMS
An index is an extra data structure, usually a B+ tree, that lets the database find rows without scanning the whole table. It speeds up reads at the cost of storage and slower writes.
- B+ tree: balanced, high fan-out so only 3-4 levels deep; all data pointers live in leaves, which are linked for fast range scans.
- Clustered index decides the physical row order (one per table, usually the primary key). Non-clustered index is a separate structure pointing back to rows (many allowed).
- Composite index (a, b) follows the leftmost-prefix rule: it helps
WHERE a = ?but notWHERE b = ?alone. - Index columns used in WHERE, JOIN and ORDER BY with high selectivity; avoid over-indexing write-heavy tables.
11Isolation levelsDBMS
Isolation levels trade correctness for concurrency by deciding which read anomalies a transaction may see. Stronger levels block or abort more and run slower.
- Dirty read: reading another transaction's uncommitted data.
- Non-repeatable read: the same row read twice returns different values because someone committed an update.
- Phantom read: the same range query returns new or missing rows because someone inserted or deleted.
- Defaults: Postgres and SQL Server use Read Committed, MySQL InnoDB uses Repeatable Read.
Deep dive: Payment system →Level Dirty Non-repeatable Phantom Read Uncommitted yes yes yes Read Committed no yes yes Repeatable Read no no yes* Serializable no no no (* InnoDB largely prevents phantoms with gap locks)
12SQL vs NoSQLDBMS
SQL databases store structured data in tables with a fixed schema, joins and strong ACID transactions. NoSQL databases (key-value, document, wide-column, graph) relax schema and often consistency to scale horizontally.
- Pick SQL for relational data, complex queries and transactions (payments, orders, inventory).
- Pick NoSQL for huge scale, flexible or evolving schemas and simple access patterns (sessions, feeds, logs, caches).
- SQL usually scales up (vertically) first; NoSQL is built to shard out, often favouring availability (BASE, eventual consistency).
- Examples: PostgreSQL, MySQL vs Redis, MongoDB, Cassandra, DynamoDB, Neo4j.
Computer Networks
How bytes get from a browser to a server and back.
13OSI & TCP/IP modelsCN
OSI is a 7-layer reference model for how network communication is split into responsibilities; TCP/IP is the 4-layer model the internet actually uses. Each layer talks to the same layer on the other side and wraps the data of the layer above.
- Mnemonic top-down: All People Seem To Need Data Processing.
- Data units: segment (L4), packet (L3), frame (L2), bits (L1).
- Devices: switch works at L2 (MAC), router at L3 (IP), load balancers at L4 or L7.
# OSI layer TCP/IP layer Examples 7 Application Application HTTP, DNS, SMTP, FTP 6 Presentation Application TLS, encoding, compression 5 Session Application sessions, RPC 4 Transport Transport TCP, UDP (ports) 3 Network Internet IP, ICMP, routing 2 Data Link Link Ethernet, MAC, ARP 1 Physical Link cables, Wi-Fi radio
14TCP vs UDPCN
TCP is a connection-oriented, reliable, ordered byte stream with flow and congestion control. UDP is connectionless, sends independent datagrams with no delivery or order guarantee, and has far less overhead.
- TCP setup is a 3-way handshake (SYN, SYN-ACK, ACK); teardown uses FIN/ACK. Reliability comes from sequence numbers, ACKs and retransmission.
- UDP header is 8 bytes vs at least 20 for TCP; no handshake means lower latency.
- TCP: web, email, file transfer, databases. UDP: DNS queries, video calls, gaming, live streaming.
- HTTP/3 runs on QUIC, which builds reliability on top of UDP.
15DNSCN
The internet's phone book: it translates a domain name like
example.cominto an IP address. Resolution is hierarchical and cached heavily at every step.- Order: browser cache, OS cache, recursive resolver (ISP or 8.8.8.8), then root server, TLD server (.com) and the authoritative name server.
- Records: A (IPv4), AAAA (IPv6), CNAME (alias), MX (mail), NS (name server), TXT.
- TTL controls how long answers are cached; low TTL helps failover, high TTL reduces load.
- Usually runs over UDP port 53, falling back to TCP for large responses.
16HTTP vs HTTPSCN
HTTPS is HTTP sent over TLS, which adds encryption, integrity and server authentication via certificates. Plain HTTP (port 80) is readable and editable by anyone on the path; HTTPS uses port 443.
- Asymmetric crypto (certificate key pair) is used only to agree on a key; bulk data uses fast symmetric encryption (e.g. AES).
- The certificate is signed by a trusted CA, which is how the browser knows it is talking to the real server.
- TLS 1.3 needs one round trip for the handshake (zero with resumption) vs two in TLS 1.2.
TLS handshake (simplified, TLS 1.3) 1. ClientHello: supported ciphers + client key share 2. ServerHello: chosen cipher + server key share + certificate 3. Client verifies certificate chain against trusted CAs 4. Both derive the same session key (ECDHE) 5. Finished messages; data now flows encrypted with the symmetric key
17HTTP status codesCN
Three-digit codes in every HTTP response telling the client what happened. The first digit gives the class, so learn the classes first and a handful of common codes in each.
- 401 means not authenticated (who are you?); 403 means authenticated but not allowed.
- 301 is cached by browsers and passes SEO value; 302 is temporary and not cached by default.
- 4xx means the client should fix the request; 5xx means retrying later may help.
1xx Informational 100 Continue, 101 Switching Protocols 2xx Success 200 OK, 201 Created, 204 No Content 3xx Redirection 301 Moved Permanently, 302 Found, 304 Not Modified 4xx Client error 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 429 Too Many Requests 5xx Server error 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout18REST APIsCN
REST is an architectural style for APIs over HTTP: everything is a resource identified by a URL, manipulated with standard HTTP methods, and each request is stateless and self-contained.
- Methods: GET read, POST create, PUT replace, PATCH partial update, DELETE remove.
- Idempotent: GET, PUT, DELETE (repeat gives same result). POST is not, so use idempotency keys for retries.
- Use nouns in paths (
/users/42/orders), proper status codes, pagination and versioning (/v1/). - Statelessness makes horizontal scaling easy since any server can handle any request.
GET /api/v1/users/42 -> 200 + user JSON POST /api/v1/users -> 201 + Location header PATCH /api/v1/users/42 -> 200 updated fields DELETE /api/v1/users/42 -> 204 No Content
19Cookies vs Sessions vs JWTCN
Three ways to remember who a user is across stateless HTTP requests. A cookie is just browser storage sent automatically; a session keeps state on the server keyed by an ID in a cookie; a JWT is a signed token that carries the claims itself.
- Sessions: easy to revoke, but the server (or shared store like Redis) must hold state for every user.
- JWT: header.payload.signature; stateless and scales well, but hard to revoke before expiry, so keep it short-lived with a refresh token.
- JWT payload is only base64-encoded, not encrypted: never put secrets in it.
- Secure cookies with
HttpOnly(no JS access, limits XSS),Secure(HTTPS only) andSameSite(limits CSRF).
20What happens when you type a URLCN
The classic end-to-end question that ties networking together. Walk through the steps in order and go deeper on whichever one the interviewer probes.
- Mention caches at each step: browser, OS and resolver DNS caches, CDN edge, HTTP cache (304 Not Modified).
- Mention keep-alive and HTTP/2 multiplexing so later resources reuse the same connection.
- Large sites add a load balancer and CDN between the browser and the app server.
Deep dive: URL shortener (redirects) →1. Parse URL (scheme, host, port, path); check HSTS and browser cache 2. DNS: resolve host to IP (caches -> resolver -> root -> TLD -> authoritative) 3. TCP 3-way handshake with the server IP on port 443 4. TLS handshake: verify certificate, agree on session key 5. Send HTTP GET request (headers, cookies) 6. Load balancer / CDN -> web server -> app -> DB/cache 7. Response: status code + headers + HTML (may be a 301/302 redirect) 8. Browser parses HTML, builds DOM/CSSOM, fetches CSS/JS/images 9. Layout, paint, run JS; page is interactive
Quick tips
- Answer in layers: one-line definition first, then a concrete example, then trade-offs. Stop and let the interviewer pick where to dig.
- Draw it: a quick table or diagram (isolation anomalies, OSI layers, URL flow) is often clearer than a paragraph.
- Tie concepts to real systems you have built, e.g. which isolation level your service used or why you chose JWT over sessions.
- Revise the classic comparisons right before an interview: process vs thread, mutex vs semaphore, TCP vs UDP, SQL vs NoSQL.
- If you do not know a detail, say how you would reason about it; that earns more than a confident wrong answer.
Topic list based on the free Everything You Need to Get Placed checklist by Mohammad Fraz. Explanations and examples are original.