Show 25 50 100
PDF

Index

  1. ER Diagram
  2. Normalization (1NF, 2NF, 3NF, BCNF)
  3. SQL Command Types
  4. SQL Joins
  5. Aggregate Functions, GROUP BY and HAVING
  6. Transactions and ACID
  7. Indexing
  8. Views, Stored Procedures and Triggers
  9. SQL vs NoSQL
  10. OSI Model
  11. TCP/IP Model
  12. TCP vs UDP
  13. Common Ports and Protocols
  14. IP Address and Subnetting
  15. DNS
  16. HTTP and HTTPS
  17. Network Devices
  18. Network Topologies and Types
  19. ARP, DHCP and ICMP
  20. Network Security Basics
  21. What is an Operating System
  22. Process vs Thread
  23. Process States
  24. CPU Scheduling Algorithms
  25. Process Synchronization
  26. Deadlock
  27. Memory Management and Paging
  28. Virtual Memory and Page Replacement
  29. System Calls and User/Kernel Mode
  30. File System and Disk Scheduling
  31. Software Engineering and SDLC
  32. Waterfall Model
  33. Agile and Scrum
  34. Other SDLC Models
  35. Requirements Engineering
  36. Software Testing
  37. UML Diagrams
  38. Coupling and Cohesion
  39. Design Patterns
  40. Software Metrics and Estimation
  41. Git and Version Control
  42. Length of an Array
  43. Length (count digits) of a number
  44. Power (x^n)
  45. Largest & Smallest Digit of a Number
  46. Bit Manipulation (common)
  47. Palindrome String
  48. Largest & Smallest Element of an Array
  49. Reverse an Array
  50. Missing Number (1 to N)
101 Index

An Entity-Relationship diagram models the database before building tables: entities (things), attributes (properties) and relationships.

A student can take many courses and a course has many students (M:N)

A student can take many courses and a course has many students (M:N)

  • Cardinality: one-to-one (1:1), one-to-many (1:N), many-to-many (M:N).
  • Weak entity — cannot be identified by its own attributes (double rectangle), e.g. Dependent of an Employee.
  • Derived attribute (dashed ellipse), e.g. Age from DOB; multi-valued (double ellipse), e.g. Phone numbers.
102 Index

Normalization splits tables to remove redundancy and anomalies (insert, update, delete). It is based on functional dependency: A → B means A decides B.

Each normal form builds on the previous one

Each normal form builds on the previous one

FormRuleExample fix
1NFEvery cell holds one atomic value; no repeating groupsPhone = "017.., 018.." → one row per phone
2NF1NF and no non-key column depends on only part of a composite key(Roll, CourseID) → CourseName depends only on CourseID → move to Course table
3NF2NF and no non-key column depends on another non-key columnRoll → DeptID → DeptName → move DeptName to Department table
BCNFFor every A → B, A must be a super keyStricter version of 3NF

Q & A

  1. What is denormalization?
    Adding some redundancy back on purpose (for example, storing a total) to make reads faster, at the cost of harder updates.
103 Index
TypeFull nameCommands
DDLData Definition LanguageCREATE, ALTER, DROP, TRUNCATE, RENAME
DMLData Manipulation LanguageINSERT, UPDATE, DELETE
DQLData Query LanguageSELECT
DCLData Control LanguageGRANT, REVOKE
TCLTransaction Control LanguageCOMMIT, ROLLBACK, SAVEPOINT
SQL 11 lines
INSERT INTO students (roll, name, dept_id) VALUES (1, 'Rahim', 10);
UPDATE students SET name = 'Karim' WHERE roll = 1;
DELETE FROM students WHERE roll = 1;

ALTER TABLE students ADD COLUMN cgpa DECIMAL(3,2);

SELECT name, cgpa
FROM students
WHERE cgpa >= 3.5 AND name LIKE 'R%'
ORDER BY cgpa DESC
LIMIT 5;

DELETE vs TRUNCATE vs DROP

DELETETRUNCATEDROP
DML, removes chosen rows (WHERE)DDL, removes all rowsDDL, removes the whole table
Can be rolled backUsually cannot be rolled backCannot be rolled back
Slower, row by rowFast, resets auto incrementStructure is gone too
104 Index

A JOIN combines rows from two tables using a related column.

Shaded area = rows returned

Shaded area = rows returned

SQL 20 lines
-- INNER JOIN: only students that have a department
SELECT s.name, d.name AS dept
FROM students s
INNER JOIN departments d ON s.dept_id = d.id;

-- LEFT JOIN: every student, dept is NULL when missing
SELECT s.name, d.name AS dept
FROM students s
LEFT JOIN departments d ON s.dept_id = d.id;

-- Students without a department
SELECT s.name
FROM students s
LEFT JOIN departments d ON s.dept_id = d.id
WHERE d.id IS NULL;

-- SELF JOIN: employee with their manager
SELECT e.name, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;

CROSS JOIN returns every combination (rows A × rows B). MySQL has no FULL OUTER JOIN: use LEFT JOIN UNION RIGHT JOIN.

105 Index

Aggregate functions: COUNT, SUM, AVG, MIN, MAX. GROUP BY makes one row per group. WHERE filters rows before grouping; HAVING filters groups after.

SQL 6 lines
SELECT dept_id, COUNT(*) AS total, AVG(cgpa) AS avg_cgpa
FROM students
WHERE cgpa IS NOT NULL
GROUP BY dept_id
HAVING COUNT(*) > 10
ORDER BY avg_cgpa DESC;
Most asked SQL queries SQL 16 lines
-- 2nd highest salary
SELECT MAX(salary) FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

-- Nth highest (N = 3)
SELECT DISTINCT salary FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 2;

-- Duplicate emails
SELECT email, COUNT(*) FROM users
GROUP BY email HAVING COUNT(*) > 1;

-- Highest paid employee in each department
SELECT * FROM employees e
WHERE salary = (SELECT MAX(salary) FROM employees WHERE dept_id = e.dept_id);

Order of execution: FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT.

106 Index

A transaction is a group of operations that must succeed or fail together, e.g. a money transfer.

PropertyMeaning
AtomicityAll or nothing: if one step fails, everything is rolled back
ConsistencyThe database moves from one valid state to another (rules and constraints hold)
IsolationConcurrent transactions do not see each other's half-done work
DurabilityOnce committed, data survives crashes (written to disk / log)
SQL 4 lines
START TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT;          -- or ROLLBACK; if anything went wrong

Isolation levels

Isolation levelDirty readNon-repeatable readPhantom read
Read UncommittedPossiblePossiblePossible
Read CommittedNoPossiblePossible
Repeatable Read (MySQL default)NoNoPossible
SerializableNoNoNo
107 Index

An index is a separate data structure (usually a B+ tree) that lets the database find rows without scanning the whole table, like the index at the back of a book. It speeds up SELECT/WHERE/JOIN/ORDER BY but slows down INSERT/UPDATE/DELETE and uses extra space.

  • Clustered index — the table rows are physically stored in index order; only one per table (the primary key in InnoDB).
  • Non-clustered index — separate structure pointing to rows; many per table.
  • Composite index on (a, b) helps queries on a, or a and b, but not on b alone (leftmost prefix rule).
SQL 3 lines
CREATE INDEX idx_students_name ON students(name);
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at);
EXPLAIN SELECT * FROM students WHERE name = 'Rahim';   -- check if the index is used
108 Index
SQL 17 lines
-- View: a saved query that behaves like a table
CREATE VIEW top_students AS
SELECT name, cgpa FROM students WHERE cgpa >= 3.75;

-- Stored procedure: saved, reusable SQL with parameters
DELIMITER //
CREATE PROCEDURE get_dept_students(IN d INT)
BEGIN
    SELECT * FROM students WHERE dept_id = d;
END //
DELIMITER ;
CALL get_dept_students(10);

-- Trigger: runs automatically on INSERT / UPDATE / DELETE
CREATE TRIGGER before_student_insert
BEFORE INSERT ON students
FOR EACH ROW SET NEW.name = UPPER(NEW.name);
109 Index
SQL (relational)NoSQL
Tables with a fixed schemaFlexible schema: document, key-value, column, graph
Scales vertically (bigger server)Scales horizontally (more servers, sharding)
Strong ACID transactionsOften BASE / eventual consistency
Complex joins and queriesFast simple reads/writes at huge scale
MySQL, PostgreSQL, OracleMongoDB, Redis, Cassandra, Neo4j

CAP theorem: a distributed system can guarantee only two of Consistency, Availability and Partition tolerance at the same time.

110 Index

The OSI (Open Systems Interconnection) model splits network communication into 7 layers. Each layer serves the layer above it. Mnemonic (top → bottom): All People Seem To Need Data Processing.

OSI layers, example protocols, PDU names and the matching TCP/IP layers

OSI layers, example protocols, PDU names and the matching TCP/IP layers

LayerJobDevice
ApplicationNetwork services to the user (web, mail)Gateway
PresentationTranslation, encryption, compression—
SessionOpen, manage and close sessions—
TransportEnd-to-end delivery, ports, segmentation, flow and error controlFirewall
NetworkLogical addressing (IP) and routingRouter
Data LinkPhysical addressing (MAC), framing, error detectionSwitch, Bridge
PhysicalTransmit raw bits over the mediumHub, Repeater, Cable

Q & A

  1. What is encapsulation?
    Each layer adds its own header while data goes down (data → segment → packet → frame → bits). The receiver removes them going up (decapsulation).
111 Index
TCP/IP layerOSI layersProtocols
ApplicationApplication + Presentation + SessionHTTP, HTTPS, FTP, SMTP, DNS, SSH
TransportTransportTCP, UDP
InternetNetworkIP, ICMP, ARP
Network Access (Link)Data Link + PhysicalEthernet, Wi-Fi

OSI is a theoretical reference model; TCP/IP is the practical model the internet uses.

112 Index
TCPUDP
Connection-oriented (handshake first)Connectionless
Reliable: acknowledgement, retransmissionUnreliable: no guarantee of delivery
Data arrives in orderNo ordering
Flow and congestion controlNone
Slower, 20-byte headerFaster, 8-byte header
Web (HTTP), email, file transfer, SSHVideo streaming, gaming, VoIP, DNS

SYN → SYN-ACK → ACK

SYN → SYN-ACK → ACK

113 Index
ProtocolPortUse
HTTP80Web pages
HTTPS443Secure web (TLS)
FTP20, 21File transfer
SSH22Secure remote login
Telnet23Remote login (plain text)
SMTP25 / 587Send email
POP3110Download email
IMAP143Read email on server
DNS53Domain name → IP
DHCP67, 68Automatic IP address
MySQL3306Database
RDP3389Remote desktop
114 Index

An IPv4 address is 32 bits written as four octets (192.168.1.10). IPv6 is 128 bits written in hex (2001:db8::1).

ClassFirst octetDefault maskPrivate range
A1 – 126255.0.0.0 (/8)10.0.0.0 – 10.255.255.255
B128 – 191255.255.0.0 (/16)172.16.0.0 – 172.31.255.255
C192 – 223255.255.255.0 (/24)192.168.0.0 – 192.168.255.255
D224 – 239—Multicast
E240 – 255—Experimental

127.0.0.1 is the loopback (localhost) address.

Subnetting

Subnetting example: 192.168.1.0/26

  • Mask /26 = 255.255.255.192 → host bits = 32 − 26 = 6
  • Addresses per subnet = 26 = 64, usable hosts = 64 − 2 = 62 (network and broadcast are reserved)
  • Number of subnets from a /24 = 22 = 4 → .0, .64, .128, .192
  • First subnet: network 192.168.1.0, hosts .1 – .62, broadcast 192.168.1.63

Q & A

  1. What is CIDR?
    Classless Inter-Domain Routing: writes the mask as /prefix length (for example /26), so networks are not limited to classes A, B and C.
  2. What is NAT?
    Network Address Translation lets many devices with private IPs share one public IP through the router.
115 Index

DNS (Domain Name System) converts a domain name into an IP address, like the phone book of the internet. It mainly uses UDP port 53.

Recursive resolver asks root → TLD → authoritative server

Recursive resolver asks root → TLD → authoritative server

RecordMeaning
ADomain → IPv4 address
AAAADomain → IPv6 address
CNAMEAlias of another domain
MXMail server
NSName server of the domain
TXTText (SPF, verification)
116 Index

HTTP is a stateless request/response protocol for the web. HTTPS = HTTP over TLS: data is encrypted, the server is verified by a certificate, and it uses port 443.

MethodUse
GETRead data
POSTCreate / submit data
PUTReplace a resource
PATCHUpdate part of a resource
DELETERemove a resource

HTTP status codes

CodeMeaning
1xxInformational
200 OKSuccess
201 CreatedResource created
301 / 302Moved permanently / temporarily (redirect)
304Not modified (use cache)
400Bad request
401Unauthorised (login needed)
403Forbidden
404Not found
500Internal server error
502 / 503Bad gateway / service unavailable

Q & A

  1. What happens when you type a URL and press Enter?
    DNS lookup gives the IP → TCP handshake (and TLS handshake for HTTPS) → browser sends an HTTP request → server sends the response → browser parses HTML, loads CSS/JS/images and renders the page.
  2. Why is HTTP stateless and how do sites remember you?
    Each request is independent. Sites use cookies, sessions or tokens (JWT) to keep state.
117 Index
DeviceLayerWorks withWhat it does
HubPhysical (1)BitsSends data to every port (one collision domain)
RepeaterPhysical (1)BitsRegenerates the signal to extend distance
SwitchData Link (2)MAC addressSends the frame only to the correct port
BridgeData Link (2)MAC addressConnects two LAN segments
RouterNetwork (3)IP addressConnects different networks, chooses the best path
GatewayAll layersProtocolsConnects networks using different protocols
ModemPhysicalSignalsConverts digital ↔ analog
118 Index

Bus, star, ring, mesh and tree

Bus, star, ring, mesh and tree

TopologyAdvantageDisadvantage
BusCheap, easyBackbone cable fails → whole network fails
StarEasy to manage, one cable failure affects one deviceCentral switch is a single point of failure
RingOrderly data flowOne break can stop the ring
MeshVery reliable (many paths)Expensive, many cables

Network types by size: PAN (Bluetooth) < LAN (office) < MAN (city) < WAN (country / internet).

119 Index
  • ARP (Address Resolution Protocol) — finds the MAC address for a known IP address inside the LAN (broadcast "who has 192.168.1.5?").
  • DHCP — gives a device an IP address, mask, gateway and DNS automatically. Steps: DORA — Discover, Offer, Request, Acknowledge.
  • ICMP — error and diagnostic messages; used by ping and traceroute.
Useful commands Bash / Shell 5 lines
ping google.com          # is the host reachable? (ICMP echo)
tracert google.com       # path of routers (Windows; traceroute on Linux)
ipconfig /all            # IP, MAC, gateway, DNS (Windows; ip a on Linux)
nslookup example.com     # DNS lookup
arp -a                   # ARP cache
120 Index
  • Firewall — allows or blocks traffic by rules (IP, port, protocol).
  • Symmetric encryption (AES) — one shared key, fast. Asymmetric (RSA) — public/private key pair, used to exchange keys and for digital signatures.
  • Hashing (SHA-256) — one-way fingerprint for integrity and password storage.
  • VPN — encrypted tunnel over a public network.
  • Common attacks: DoS/DDoS, man-in-the-middle, phishing, SQL injection, XSS.
121 Index

An operating system is system software that manages computer hardware and provides services to programs. Examples: Windows, Linux, macOS, Android.

The OS is the layer between programs and hardware

The OS is the layer between programs and hardware

Main functions: process management, memory management, file system management, device (I/O) management, security and protection, user interface.

TypeIdeaExample
BatchJobs grouped and run without interactionEarly mainframes
MultiprogrammingSeveral programs in memory, CPU switches when one waits for I/O—
Time-sharing (multitasking)CPU time is sliced between users/programsUnix, Windows
Real-timeMust respond within a strict deadlineAir-bag controller, RTOS
DistributedMany computers act like one systemCluster systems

Q & A

  1. What is the kernel?
    The core part of the OS that runs in privileged mode and directly controls CPU, memory and devices.
  2. Monolithic vs microkernel?
    Monolithic: all services (drivers, file system) run inside the kernel, fast (Linux). Microkernel: only minimal services in the kernel, the rest in user space, more stable and secure but slower (Minix, QNX).
122 Index

A process is a program in execution, with its own memory space. A thread is the smallest unit of execution inside a process; threads of the same process share its memory.

ProcessThread
HeavyweightLightweight
Own memory (code, data, heap, stack)Shares code, data and heap; has its own stack and registers
Context switch is slowContext switch is fast
Communicate via IPC (pipes, sockets, shared memory)Communicate directly through shared memory
One crashing does not affect othersOne crashing thread can crash the whole process

PCB (Process Control Block) stores everything about a process: PID, state, program counter, registers, memory info, open files, priority.

Context switch: saving the state of the running process in its PCB and loading the next one.

123 Index

New → Ready → Running → Waiting → Terminated

New → Ready → Running → Waiting → Terminated

  • New — being created.
  • Ready — waiting for the CPU.
  • Running — instructions are executing.
  • Waiting / Blocked — waiting for I/O or an event.
  • Terminated — finished.

Zombie process: finished but its parent has not read its exit status. Orphan process: its parent ended first (adopted by init).

124 Index

Terms: Burst time (CPU time needed), Arrival time, Completion time, Turnaround time = Completion − Arrival, Waiting time = Turnaround − Burst, Response time = first run − arrival.

AlgorithmTypeIdeaProblem
FCFSNon-preemptiveFirst come, first servedConvoy effect (short jobs wait behind a long one)
SJFNon-preemptiveShortest burst first; minimum average waiting timeStarvation of long jobs; burst time must be known
SRTFPreemptive SJFShortest remaining time firstStarvation
PriorityEitherHighest priority firstStarvation → fixed by aging
Round RobinPreemptiveEach process gets a time quantum in turnToo small quantum = many context switches
Multilevel QueueEitherSeparate queues (system, interactive, batch)Rigid

Round Robin example with its waiting and turnaround times

Round Robin example with its waiting and turnaround times

FCFS average waiting time C++ 7 lines
// FCFS waiting time: each process waits for all bursts before it
int burst[] = {24, 3, 3}, n = 3, wait = 0, total = 0;
for (int i = 0; i < n; i++) {
    total += wait;
    wait += burst[i];
}
cout << "Average waiting = " << (double)total / n;   // (0 + 24 + 27) / 3 = 17
125 Index

When processes/threads share data, a race condition happens if the result depends on the order they run. The code that touches shared data is the critical section.

A correct solution needs: Mutual exclusion (one at a time), Progress and Bounded waiting.

MutexSemaphore
Lock with owner: only the thread that locked can unlockInteger counter changed by wait() / signal()
Binary: locked / unlockedBinary (0/1) or counting (0..n)
Protect one critical sectionAlso limits access to n identical resources
Semaphore operations C 13 lines
// wait (P) and signal (V) — both are atomic
wait(S) {
    while (S <= 0) ;   // busy wait
    S--;
}
signal(S) {
    S++;
}

// usage
wait(mutex);
/* critical section */
signal(mutex);

Classic problems: Producer–Consumer (bounded buffer), Readers–Writers, Dining Philosophers.

126 Index

A deadlock is a state where a set of processes wait forever, each holding a resource the other needs.

Resource allocation graph with a cycle

Resource allocation graph with a cycle

Four necessary conditions (Coffman) — all must hold:

  • Mutual exclusion — a resource is used by one process at a time.
  • Hold and wait — a process holds one resource and waits for another.
  • No preemption — a resource cannot be taken away forcibly.
  • Circular wait — P1 waits for P2, P2 waits for P1 (a cycle).

Handling: Prevention (break one condition), Avoidance (Banker's algorithm, only grant requests that keep the system in a safe state), Detection and recovery (kill a process / preempt resources), or Ignore it (Ostrich approach, used by most desktop OSes).

Q & A

  1. Deadlock vs starvation?
    Deadlock: processes wait for each other forever and none progresses. Starvation: one process waits a very long time because others keep getting priority; the system still progresses.
127 Index
  • Contiguous allocation — each process gets one block; strategies First fit, Best fit, Worst fit; causes external fragmentation.
  • Paging — logical memory split into fixed-size pages, physical memory into frames of the same size; a page table maps them.
  • Segmentation — memory divided by logical units (code, stack, data) of different sizes.
  • TLB — fast cache of recent page-table entries.

Pages do not need to be next to each other in physical memory

Pages do not need to be next to each other in physical memory

Internal fragmentationExternal fragmentation
Wasted space inside an allocated blockFree space is split into small holes between blocks
Happens in paging (last page)Happens in contiguous allocation / segmentation
Fix: smaller blocksFix: compaction or paging
128 Index

Virtual memory lets a program use more memory than physically available by keeping only the needed pages in RAM (demand paging). Accessing a page that is not in RAM causes a page fault. Too many page faults = thrashing.

Example: reference string 7 0 1 2 0 3 0 4, 3 frames

AlgorithmIdeaPage faults
FIFOReplace the page that came in first7
LRUReplace the least recently used page6
OptimalReplace the page not needed for the longest time (theoretical best)6

Belady's anomaly: with FIFO, adding more frames can sometimes increase page faults.

LRU page faults C++ 14 lines
int lruFaults(vector<int> refs, int frames) {
    list<int> cache;                       // front = most recently used
    int faults = 0;
    for (int p : refs) {
        auto it = find(cache.begin(), cache.end(), p);
        if (it != cache.end()) cache.erase(it);          // hit
        else {
            faults++;
            if (cache.size() == frames) cache.pop_back(); // evict LRU
        }
        cache.push_front(p);
    }
    return faults;
}
129 Index

A program runs in user mode. To use hardware (files, network, new process) it makes a system call, which switches the CPU to kernel mode.

CategoryExamples (Linux)
Process controlfork(), exec(), exit(), wait()
File managementopen(), read(), write(), close()
Device managementioctl()
Informationgetpid(), time()
Communicationpipe(), socket(), shmget()
fork() C 10 lines
#include <unistd.h>
#include <stdio.h>

int main() {
    pid_t pid = fork();          // creates a child process
    if (pid == 0) printf("Child, pid = %d\n", getpid());
    else          printf("Parent, child pid = %d\n", pid);
    return 0;
}
// fork() returns 0 in the child and the child's pid in the parent
130 Index
  • File allocation: contiguous (fast, fragmentation), linked (no fragmentation, slow random access), indexed (index block holds pointers, e.g. inodes).
  • Disk access time = seek time + rotational latency + transfer time.
AlgorithmIdea
FCFSServe requests in arrival order
SSTFShortest seek time first (nearest track)
SCAN (elevator)Move to one end serving requests, then reverse
C-SCANServe in one direction only, jump back to the start
LOOK / C-LOOKLike SCAN / C-SCAN but turn at the last request, not the disk end
131 Index

Software engineering is the systematic, disciplined approach to developing, operating and maintaining software. The SDLC (Software Development Life Cycle) is the series of phases a project goes through.

The seven SDLC phases

The seven SDLC phases

PhaseOutput
PlanningFeasibility study, cost and time estimate
Requirement analysisSRS (Software Requirements Specification)
DesignArchitecture, database design, UI design (HLD / LLD)
ImplementationSource code
TestingBug reports, tested build
DeploymentReleased product
MaintenanceBug fixes, updates, enhancements

Q & A

  1. What is software crisis?
    The problems of the 1960s-70s where projects went over budget, were late, unreliable and hard to maintain, which led to software engineering as a discipline.
132 Index

A linear, sequential model: each phase must finish before the next begins.

Phases flow down like a waterfall

Phases flow down like a waterfall

AdvantagesDisadvantages
Simple and easy to manageHard to go back and change requirements
Clear milestones and documentationWorking software only at the end
Good for small projects with fixed, clear requirementsHigh risk for large or changing projects
133 Index

Agile builds software in short iterations, delivering working software often and welcoming changing requirements.

Agile Manifesto values:

  • Individuals and interactions over processes and tools
  • Working software over comprehensive documentation
  • Customer collaboration over contract negotiation
  • Responding to change over following a plan

Product backlog → sprint → increment

Product backlog → sprint → increment

Artifacts: Product Backlog, Sprint Backlog, Increment. Events: Sprint Planning, Daily Scrum, Sprint Review, Sprint Retrospective. Requirements are written as user stories: "As a <user>, I want <goal> so that <reason>".

Q & A

  1. Agile vs Waterfall?
    Waterfall: sequential, fixed requirements, delivery at the end, heavy documentation. Agile: iterative, requirements can change, frequent delivery, continuous customer feedback.
  2. Scrum vs Kanban?
    Scrum uses fixed-length sprints and defined roles. Kanban is a continuous flow on a board (To Do → Doing → Done) with limits on work in progress.
134 Index
ModelIdeaBest for
Iterative / IncrementalBuild the system in small parts, each adding featuresLarge projects with clear core needs
SpiralIterations with risk analysis in every loop (Plan → Risk → Engineer → Evaluate)Large, high-risk projects
V-ModelWaterfall where every development phase has a matching test phaseSafety-critical systems
PrototypeBuild a quick model to understand requirements, then the real systemUnclear requirements
RADRapid development with reusable components and user feedbackShort deadlines
DevOpsDevelopment + operations, CI/CD automationFrequent releases
135 Index
Functional requirementsNon-functional requirements
What the system should doHow well the system should do it
User can log in, place an order, download a reportPerformance, security, usability, reliability, scalability
Tested with feature testsMeasured with metrics (response < 2 s, 99.9% uptime)

Steps: elicitation (interviews, surveys, observation) → analysis → specification (SRS) → validation → management.

A good SRS is correct, complete, unambiguous, consistent, verifiable and traceable.

136 Index

Unit → Integration → System → Acceptance

Unit → Integration → System → Acceptance

Black box testingWhite box testing
Tests behaviour without seeing the codeTests internal code, paths and logic
Done by testersDone by developers
Equivalence partitioning, boundary value analysisStatement, branch and path coverage
  • Regression testing — re-test after a change to make sure nothing old broke.
  • Smoke testing — quick check that the main features work in a new build.
  • Alpha testing (inside the company) vs Beta testing (real users).
  • Verification = are we building the product right? Validation = are we building the right product?
A tiny unit test C++ 8 lines
// Function under test
int maxOf(int a, int b) { return a > b ? a : b; }

// Unit tests (boundary and normal cases)
assert(maxOf(3, 5) == 5);
assert(maxOf(5, 3) == 5);
assert(maxOf(-1, -1) == -1);
assert(maxOf(INT_MAX, 0) == INT_MAX);

Q & A

  1. What is boundary value analysis?
    Testing at the edges of valid ranges. For an age field 18–60, test 17, 18, 19, 59, 60 and 61, because bugs often hide at boundaries.
  2. Error vs defect vs failure?
    Error: a human mistake. Defect (bug): the fault in the code caused by it. Failure: the wrong behaviour seen when the defective code runs.
137 Index

UML (Unified Modeling Language) is a standard way to visualise a system design.

StructuralBehavioural
Class diagram — classes, attributes, methods, relationshipsUse case diagram — actors and what they can do
Object diagram — objects at one momentSequence diagram — messages between objects over time
Component diagramActivity diagram — workflow, like a flowchart
Deployment diagram — hardware nodesState machine diagram — states of an object
  • Class relationships: association (line), inheritance (hollow triangle), aggregation (hollow diamond), composition (filled diamond), dependency (dashed arrow).
  • Visibility: + public, - private, # protected.
138 Index

Good design has low coupling and high cohesion.

CouplingCohesion
How much modules depend on each otherHow closely the parts inside one module belong together
Want it LOWWant it HIGH
Worst: content coupling; best: data couplingWorst: coincidental; best: functional

Low coupling means a change in one module rarely breaks another; high cohesion means each module has one clear job.

139 Index
CategoryPatterns
Creational (object creation)Singleton, Factory, Abstract Factory, Builder, Prototype
Structural (composition)Adapter, Decorator, Facade, Proxy, Composite
Behavioural (communication)Observer, Strategy, Command, Iterator, State
Singleton: exactly one object C++ 13 lines
class Database {
private:
    Database() {}                          // no outside construction
public:
    static Database& instance() {
        static Database db;                // created once, thread-safe (C++11)
        return db;
    }
    Database(const Database&) = delete;    // no copies
    void operator=(const Database&) = delete;
};

Database &db = Database::instance();
Factory: hide which class is created C++ 9 lines
class Shape { public: virtual void draw() = 0; virtual ~Shape() {} };
class Circle : public Shape { public: void draw() override { cout << "Circle\n"; } };
class Square : public Shape { public: void draw() override { cout << "Square\n"; } };

unique_ptr<Shape> createShape(const string &type) {   // factory
    if (type == "circle") return make_unique<Circle>();
    return make_unique<Square>();
}
createShape("circle")->draw();
Observer: notify all subscribers C++ 8 lines
class Observer { public: virtual void update(const string &msg) = 0; };

class Channel {
    vector<Observer*> subs;
public:
    void subscribe(Observer *o) { subs.push_back(o); }
    void publish(const string &msg) { for (auto *o : subs) o->update(msg); }
};
140 Index
  • LOC — lines of code (simple size measure).
  • Function Point — size by inputs, outputs, inquiries, files and interfaces (language independent).
  • Cyclomatic complexity = E − N + 2 (edges − nodes + 2) = number of decisions + 1; the number of independent paths to test.
  • COCOMO — estimates effort: Effort = a × (KLOC)b person-months (organic, semi-detached, embedded).
141 Index

Version control records every change so a team can work together, review history and roll back. Git is distributed: every developer has the full history.

Bash / Shell 12 lines
git init                       # new repository
git clone <url>                # copy a remote repository
git status                     # what changed
git add .                      # stage changes
git commit -m "Add login page" # save a snapshot
git log --oneline              # history
git branch feature-x           # create a branch
git checkout -b feature-x      # create and switch
git merge feature-x            # merge into the current branch
git pull                       # fetch + merge from remote
git push origin main           # upload commits
git revert <commit>            # undo a commit with a new commit

merge keeps both histories with a merge commit; rebase replays your commits on top of another branch for a straight history.

143 Index
Problem Count the digits of a number (1234 -> 4).

A do-while loop is used so that the number 0 is counted as 1 digit.

Solution 1: do-while loop C++ 9 lines
int main() {
    int num = 1234;
    int len = 0;
    do{
        num = num / 10;
        len++;
    }while(num != 0);
    cout << len;   // 4
}
Solution 2: String method C++ 3 lines
int num = 1234;
int len = to_string(num).length();
cout << len;
144 Index
Problem Calculate x raised to the power n.
Solution 1: Loop O(n) C++ 7 lines
int x = 2, n = 5;
long long result = 1;
for(int i = 0; i < n; i++){
    result = result * x;
}
cout << result;   // 32
// STL: cout << pow(2, 5);
145 Index
Problem Find the largest and the smallest digit of a number.
Largest digit C++ 8 lines
int num = 234515;
int lrg = 0;
do{
    int digit = num % 10;
    if(digit > lrg) lrg = digit;
    num = num / 10;
}while(num != 0);
cout << lrg;   // 5
Smallest digit C++ 8 lines
int num = 234515;
int small = 9;
do{
    int digit = num % 10;
    if(digit < small) small = digit;
    num = num / 10;
}while(num != 0);
cout << small;   // 1
146 Index
Problem Power of 2 check and counting set bits.
Power of 2 check C++ 3 lines
bool isPow2(int n){
    return n > 0 && (n & (n - 1)) == 0;
}
Count set bits C++ 6 lines
int n = 13, count = 0;
while(n){
    count += n & 1;
    n >>= 1;
}
// or: __builtin_popcount(13)
147 Index
Problem Check whether a string is a palindrome (madam).
Solution 1: Two pointer (O(1) space) C++ 8 lines
string s = "madam";
int l = 0, r = s.length() - 1;
bool ok = true;
while(l < r){
    if(s[l] != s[r]){ ok = false; break; }
    l++; r--;
}
cout << (ok ? "Palindrome" : "Not Palindrome");
Solution 2: Reverse & compare C++ 4 lines
string s = "madam";
string r = s;
reverse(r.begin(), r.end());
cout << (s == r ? "Palindrome" : "Not Palindrome");
148 Index
Problem Find the largest and the smallest element of an array.
Solution 1: Single loop (interview best) C++ 10 lines
int arr[] = {10, 2, 4, 2, 10, 1};
int len = sizeof(arr) / sizeof(arr[0]);

int lrg = arr[0];
int small = arr[0];
for(int i = 1; i < len; i++){
    if(arr[i] > lrg) lrg = arr[i];
    if(arr[i] < small) small = arr[i];
}
cout << lrg << " " << small;   // 10 1
149 Index
Problem Reverse the elements of an array.
Solution 1: Two pointer [BEST] C++ 8 lines
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int l = 0, r = n - 1;
while(l < r){
    swap(arr[l], arr[r]);
    l++; r--;
}
for(int i = 0; i < n; i++) cout << arr[i] << " ";
Solution 2: STL reverse C++ 1 line
reverse(arr, arr + n);
150 Index
Problem Find the missing number in an array containing numbers from 1 to N.
Solution 1: Sum formula [BEST] C++ 6 lines
int arr[] = {1, 2, 4, 5, 6};
int n = 6;   // range 1..6
int expected = n * (n + 1) / 2;
int actual = 0;
for(int i = 0; i < 5; i++) actual += arr[i];
cout << expected - actual;   // 3