Midterm Mock Exam - Questions + Solutions

Updated 5 Oct 2026

DES431 Midterm Mock Exam: Questions + Solutions

Semi-closed book (one A4 sheet), no calculator, 2 hours. Covers Lectures 1–6 + Homework 1–3.
Format: each question is followed by its ✅ Answer. ⚠️ = a common trap.


Part I: Fill in the Blanks

1.1 The Hadoop tool for moving data between a relational DB and HDFS is Apache ____. The coordination service providing distributed locks is Apache ____.
✅ Sqoop, ZooKeeper

1.2 In Hadoop 2.0, the Execution Engine layer (a data-flow framework on YARN running an arbitrary DAG of tasks) is Apache ____. The scalable ML / data mining library is Apache ____.
✅ Tez, Mahout (⚠️ not Spark MLlib; the lecture's "umbrella" slide says Mahout)

1.3 The HDFS NameNode web UI runs on port ____; the YARN web UI runs on port ____.
✅ 50070, 8088

1.4 Change a file's replication to 4: hdfs dfs ____ 4 <file. Check that the file system is HEALTHY: hdfs ____ /.
✅ -setrep, fsck

1.5 list(<k2,v2) is produced by the ____ phase, <k2, list(v2) by the ____ phase; a reducer cannot start until ____. The number of part-r-xxxxx files = the number of ____.
✅ Map; Shuffle (and Sort); all mappers have finished; reducers
<k1,v1→Map→ list(<k2,v2) →Shuffle/Sort→ <k2,list(v2)→Reduce→ list(<k3,v3). Shuffle only groups by key; sorting is by key, not by value.

1.6 The best-compressing columnar format (585 GB → 131 GB) that is Hive-only is ____. The format that works with Java/Hive/Pig/Impala/Spark but is slower to write is ____. The binary key-value format is ____.
✅ ORC (78% smaller), Parquet (62% smaller), SequenceFile

1.7 For https://des431-lab.s3.amazonaws.com/2026-09-25/taxi.csv: bucket ____, prefix ____, object key ____.
✅ des431-lab, 2026-09-25, taxi.csv (the prefix only looks like a folder; object storage has no real hierarchy)

1.8 A SAN (block storage over IP) uses protocol ____; a NAS (file storage) uses SMB, CIFS, and ____.
✅ iSCSI, NFS

1.9 (HW3) The AWS service whose crawler fills a Data Catalog is AWS ____; the serverless SQL-on-S3 service that charges per data scanned is Amazon ____.
✅ Glue, Athena

1.10 The pipeline tool with GenerateFlowFile → Funnel → PutFile is Apache ____. Real-time streams come as ____ topics and ____ events.
✅ NiFi, Kafka, Flume

1.11 In EMR, the ____ node runs the NameNode + YARN Resource Manager; the ____ node runs a DataNode + Node Manager; the ____ node gives extra compute and holds no data. The status when ready is ____.
✅ Primary (Master), Core, Task, WAITING
⚠️ Core nodes DO hold data. "RUNNING" is wrong: the cluster is RUNNING while processing steps and WAITING when it is idle and ready.

1.12 OLTP, OLAP, and ____, which stands for ____.
✅ RTAP: Real-Time Analytics Processing

1.13 Data + ____ = Information; Information + ____ = Knowledge.
✅ Context (also accepted: meaning), Rules

1.14 The third MDM data type (stable values that categorize data, e.g. an exchange-rate table) is ____.
✅ Reference Data

1.15 The size of the intervals / number of categories when coding continuous data is the ____. Dropping a whole row because any field is missing is ____ deletion.
✅ Granularity, Listwise (keeping the row and using the fields that are there = pairwise)

1.16 The scikit-learn scaler that uses the median + IQR (robust to outliers) is ____.
✅ RobustScaler

1.17 A Combiner is also called a ____ or local reduce. Partition(key) = ____.
✅ Semi-reducer; Hash(key) mod n (n = number of reducers)


Part II: Short Answer

Question 2.1: Validation or Verification?

A food-delivery app checks a sign-up record. For each check, say validation or verification, and name the validation type:
(i) reject birth_month = 13 · (ii) send an OTP and wait for the user to type it back · (iii) reject somchai.gmail.com (no @) · (iv) check that referral code REF-8812 exists in the DB · (v) reject a CSV with 7 columns instead of 8.
What if the app does only validation? Give a bad record that passes every check.

#AnswerWhy
(i)Validation: Rangemonth ∈ [1, 12]
(ii)Verificationconfirms the number is real and belongs to the user
(iii)Validation: Formatemail must match XX@YY.ZZ
(iv)Verificationchecks existence against a business rule / DB
(v)Validation: Presence"file must have 8 columns"

Only validation: a well-formed but false record passes, e.g. 081-234-5678 has the right format but a mistyped digit (the OTP goes to a stranger), or somchai@gmail.com is valid but the mailbox doesn't exist. Validation = does it look right; verification = is it actually right.

Question 2.2: Protecting a Test Database

Choose Shuffling / Substitution / Masking / Nulling / Encryption:
(i) realistic but fake patient names · (ii) show only the last 4 digits of the national ID · (iii) blood_pressure keeps its distribution but can't be linked to a patient · (iv) the HIV-status column isn't needed at all.

✅ (i) Substitution (fake but realistic values) · (ii) Masking (X-XXXX-XXXXX-12-3) · (iii) Shuffling (reorder the values; the distribution stays, the link is broken) · (iv) Nulling (don't copy what you don't need)
⚠️ Encryption is a poor choice for an outsider: it's reversible, so whoever gets the key gets the data back.

Question 2.3: EMR Components

The cluster is 1 primary, 2 core, 0 task nodes.
(a) The role and components of each node type; which ones store HDFS data?
(b) Compute load triples for 6 hours: which node type do you add, and why are core nodes the worse choice?
(c) What if a core node is terminated mid-job vs a task node?

(a)

NodeRoleRunsStores HDFS?
Primary (Master)manages and monitors the cluster, coordinates data and tasks, tracks statusNameNode, YARN Resource ManagerNo (metadata only)
Coreholds data AND runs tasksDataNode, YARN Node Manager, Application Master, executorsYes
Taskextra compute onlyexecutors / tasksNo

(b) Add Task nodes. It's a compute spike, not a storage need, and task nodes hold no data, so you can add or remove them freely. Core nodes run DataNodes: removing them later forces re-replication (or loses blocks).
(c) Core terminated: its DataNode is gone, so its blocks are lost or under-replicated (with only 2 core nodes some blocks may have no copy left), its running tasks fail, and its intermediate map output is lost. Task terminated: only its tasks are lost; YARN reschedules them, no data is lost, and the job just runs slower.
Rule: scale compute with task nodes, scale storage with core nodes.

Question 2.4: Ephemeral Surprises

HDFS lives on the EC2 instance store. The student stops all instances at 23:50 to resume tomorrow.
(a) What happens to the data? What if they had rebooted instead?
(b) Which storage should they have used, and what does its path look like?

✅ (a) The instance store is ephemeral (it exists only while the instance runs), so stop erases the HDFS data. Data-loss triggers: disk failure, stop, hibernate, terminate. Reboot is OK.
(b) EMRFS on Amazon S3: s3://bucket-name/path-to-file, which is persistent and independent of the cluster. (Partially accepted: HDFS on EBS, hdfs://master-ip/path.)

Question 2.5: From JobTracker to YARN

A bank runs MapReduce V1 batch jobs; the fraud team wants streaming + ad-hoc queries on the same cluster.
(a) Why can't MRv1 serve them? (b) Match: (i) decides the resources for one app and sends heartbeats, (ii) grants container leases across the cluster, (iii) the "generalized TaskTracker", (iv) executes the app's process. (c) The Hadoop 2.0 layer for YARN, Tez, and Hive.

✅ (a) In MRv1 the JobTracker ties resource management and processing together, so the cluster can only run MapReduce, which is batch-only. It is not good for real-time, ad-hoc, stream data, or message queues.
(b) (i) Application Master · (ii) Resource Manager · (iii) Node Manager · (iv) Container
(c) YARN = Resource Management; Tez = Execution Engine; Hive = User API
⚠️ "YARN is faster" is not the answer. YARN separates resource management from processing, so other frameworks can share the cluster.

Question 2.6: Rows or Columns?

120 columns × 2 billion rows. Team A runs SELECT paytype, AVG(fare) … GROUP BY paytype hourly; Team B opens one full record.
(a) Which layout suits each team? (b) Two reasons a columnar format lowers Team A's Athena bill.

✅ (a) A → columnar: it reads only 2 of 120 columns, whose values sit together on disk. B → row-oriented: the whole record is stored contiguously and read in one pass.
(b) ① Column pruning: it scans ≈ 2/120 of the data. ② Better compression: similar values sit next to each other (ORC 78%, Parquet 62% smaller than text), so fewer bytes are scanned and billed. (Bonus: partition by paytype, as in HW3.)


Part III: Problem Solving

Question 3.1: Dirty Data (convenience-store POS log)

Business facts: max item price = 1,000 THB; schools order party packs of up to 1,000 snacks.

1  order_id,store_id,date,product,qty,price
2  1001,S01,25-09-2026,Milk,2,15.00
3  1002,S01,25-09-2026,Bread,1 12.00
4  1003,S02,25-09-2026,Coffee,-3,40.00
5  1004,S02,25-09-2026,Milk,,15.00
6  1005,S03,2026/09/25,Water,1,7.00
7  1006,S03,25-09-2026, milk ,1,15.00
8  1007,S01,25-09-2026,Coffee,1,4000.00
9  1001,S01,25-09-2026,Milk,2,15.00
10 1008,S04,25-09-2026,Bread,abc,12.00
11 1009,S02,31-09-2026,Water,2,7.00
12 1010,S01,25-09-2026,Snack,500,20.00

(a) For lines 3–12: the problem, its category (incomplete / noisy / inconsistent / duplicate / valid), and the check that catches it.
(b) Drop / fix / impute / keep, with a reason. Why not fill line 5 with the mean? Why are lines 8 and 12 treated differently?
(c) Put the cleaning steps in order and justify it.

✅ (a)

LineProblemCategoryCheck
3missing comma, only 5 fieldsIncomplete / malformedPresence (6 fields)
4qty = −3NoisyRange (qty 0)
5qty emptyIncompletePresence
6date YYYY/MM/DDInconsistentFormat
7" milk " (spaces, lowercase)Inconsistentnot a reject: standardize (trim + UPPER)
8price 4000 1000 maxNoisy (outlier, likely a typo)Range (business rule)
9exact copy of line 2DuplicateCross-record uniqueness on order_id (no per-row check catches it)
10qty = "abc"NoisyType
1131 September doesn't existNoisyRange on the day (⚠️ the format is fine!)
12500 snacks, within the 1,000 ruleValid outlierpasses everything; verify if in doubt

(b) 3 drop/quarantine (repairing it is a guess: qty 1 & price 12, or qty 11 & price 2?) · 4 drop/verify (a refund belongs in a separate record type) · 5 drop/verify, never impute: a sale is a fact, and the mean invents revenue that never happened (imputation is for ML features, not money) · 6 fix the date format · 7 fix → MILK · 8 drop/verify: it breaks a hard rule, so it's noise; don't auto-"fix" it to 40 · 9 drop the duplicate · 10 drop · 11 drop/verify (30-09 or 01-10?) · 12 keep.
8 vs 12: 8 violates a business rule (impossible, so noise); 12 fits one (rare but real, a valid outlier like the CEO salary). Deleting 12 under-reports 10,000 THB.

(c) Order: ① split + check the structure (6 fields; later checks read fields by position) → ② type (you can't range-check "abc") → ③ standardize (date format, product trim/UPPER) → ④ range / business rules → ⑤ dedupe (after standardizing, or "Milk" vs " milk " look different and slip through) → ⑥ outlier review → aggregate.
structure → type → standardize → range → dedupe → aggregate

Question 3.2: Write the Map & Reduce (revenue per product)

The mapper applies: R1 skip the header and rows without exactly 6 fields · R2 qty integer 0; 0 < price ≤ 1000 · R3 a real calendar date; convert YYYY/MM/DD → DD-MM-YYYY · R4 product trimmed + UPPER.
(a) Write Map/Reduce and the <k1,v1, <k2,v2, <k3,v3 types. (b) Trace lines 1–12. (c) MILK is wrong: why can't the mapper fix it, and what extra job fixes it? (d) Reducer as combiner? What about the average price?

✅ (a)

Map(long offset, String line):
    if (line starts with "order_id") return;   // R1 header
    f = line.split(",");
    if (f.length != 6) return;                 // R1 fields
    qty = parseInt(f[4]);                      // R2
    if (qty invalid or qty <= 0) return;
    price = parseDouble(f[5]);
    if (price invalid or price <= 0 or price 1000) return;
    date = toDDMMYYYY(f[2]);                   // R3
    if (date not a real date) return;
    product = f[3].trim().toUpperCase();       // R4
    Emit(product, qty * price);

Reduce(String product, Iterator<Doublerevenues):
    sum = 0; for each v: sum += v;
    Emit(product, sum);

Types: <k1,v1 = (offset: LongWritable, line: Text); <k2,v2 = (product: Text, revenue: DoubleWritable); <k3,v3 = (product: Text, total: DoubleWritable)

(b) 1 skip (header) · 2 (MILK, 30) · 3 skip (R1) · 4 skip (qty ≤ 0) · 5 skip (qty missing) · 6 (WATER, 7) (date converted) · 7 (MILK, 15) · 8 skip (price 1000) · 9 (MILK, 30) (a duplicate!) · 10 skip (not a number) · 11 skip (31 Sept) · 12 (SNACK, 10000)
Shuffle/sort: (MILK,[30,15,30]), (SNACK,[10000]), (WATER,[7]) → output MILK 75, SNACK 10000, WATER 7

(c) MILK should be 45; line 9 duplicates line 2. A mapper sees one record at a time, and the copies may be in different splits on different nodes; records with the same key only meet at the reducer after the shuffle.
Fix = chain 2 jobs: Job 1 (dedupe): map → (order_id, cleaned record); reduce → emit only the first record per key. Job 2 (revenue): reads Job 1's HDFS output directory as its input (the driver runs job 1, waits, then starts job 2).

(d) Yes: sum is associative and commutative, and the in/out types match, so it cuts network traffic. Average: no. avg(avg(10,20), 60) = avg(15, 60) = 37.5 ≠ 90/3 = 30. Emit (sum, count) and divide only in the final reducer.
Safe for a combiner: sum, count, max, min. Unsafe: average, median, distinct count.

Question 3.3: Word Count Trace

The lecture's WordCountMapper (line.split(" ") on line 5, word.toUpperCase().trim() on line 7); the summing reducer is also the combiner; 2 reducers.
Split 1: big data big deal · Split 2: data lake data warehouse · Split 3: Big lake
Hash: BIG 17, DATA 22, DEAL 9, LAKE 14, WAREHOUSE 31.
(a) Mapper output for Splits 1 and 3 · (b) combiner output; pairs shuffled with and without the combiner · (c) the contents of part-r-00000 / part-r-00001 · (d) what if Split 3 = "Big lake, data"?

✅ (a) S1: (BIG,1)(DATA,1)(BIG,1)(DEAL,1) · S3: (BIG,1)(LAKE,1) (Big → BIG)
(b) S1: (BIG,2)(DATA,1)(DEAL,1) · S2: (DATA,2)(LAKE,1)(WAREHOUSE,1) · S3: (BIG,1)(LAKE,1). Without the combiner 10 pairs, with it 8 (less network congestion).
(c) mod 2: BIG→1, DATA→0, DEAL→1, LAKE→0, WAREHOUSE→1. Shuffle + sort by key:
part-r-00000: DATA 3, LAKE 2 · part-r-00001: BIG 3, DEAL 1, WAREHOUSE 1 (2 reducers → 2 files)
(d) split(" ") → ["Big","","lake,","data"] → emits (BIG,1), ("",1), (LAKE,,1), (DATA,1).
Problem 1, noise: the empty string is counted as a word. Problem 2, inconsistency: LAKE, ≠ LAKE, so LAKE is undercounted. trim() removes only whitespace.
Fix: line.split("\\s+") (line 5); word.replaceAll("[^A-Za-z0-9]","").toUpperCase() and skip empty tokens (line 7).

Question 3.4: Binning + Normalization

Part A: waiting times 3, 5, 7, 10, 14, 18, 22, 26, 30
(a) Equal-width, N = 3 · (b) equal-frequency + smoothing by bin means · (c) what if 300 is added?

✅ (a) W = (30−3)/3 = 9 → [3,12): 3,5,7,10 · [12,21): 14,18 · [21,30]: 22,26,30
(b) {3,5,7} {10,14,18} {22,26,30} → means 5, 14, 26 → 5,5,5,14,14,14,26,26,26
(c) W = (300−3)/3 = 99 → [3,102) holds all 9, [102,201) is empty, [201,300] holds just 300. The outlier dominates equal-width bins; use equal-frequency, and remove the GPS error (noise) first.
Formula: W = (B − A) / N

Part B: income min 20,000, max 100,000, μ = 50,000, σ = 20,000.
(d) Normalize v = 60,000 to [0,1], to [−1,1], and as a z-score · (e) what if a CEO earning 1,020,000 joins? · (f) Is it noise? Which scaler? Which skew?

✅ (d) [0,1]: 40,000/80,000 = 0.5 · [−1,1]: 0.5×2 − 1 = 0 · z = 10,000/20,000 = 0.5
(e) 40,000/1,000,000 = 0.04; the old max now maps to 0.08, so 99% of customers are squashed into [0, 0.08]. Min-max is sensitive to outliers.
(f) Not noise: it's a valid outlier (the lecture's CEO-salary example). Use RobustScaler (median, IQR) or a log transform. Positive skew: mean median mode.
Min-max: v' = (v−min)/(max−min)·(newMax−newMin) + newMin · Z-score: v' = (v−μ)/σ


Part IV: Integrated Design: Bangkok "Taxi Pulse"

Background: 10,000 taxis × 1 ping / 10 s, 100-byte CSV (taxi_id, driver_id, timestamp, lat, lon, speed, direction, meter_on); join with a district table (PostgreSQL, 50 districts), hourly weather (JSON API), and complaint text; keep 3 years; refresh the dashboard hourly; hide driver_id and phone numbers from researchers; limited budget (on-premise or EMR). Assume 1 day ≈ 100,000 s and 1 year ≈ 400 days.

(a) The four V's with an example of each; structured / semi-structured / unstructured for each source; nominal / ordinal / discrete / continuous for speed, direction, meter_on.
✅ Volume ≈ 10 GB/day, 12 TB over 3 years · Velocity 1,000 pings/s + an hourly dashboard · Variety CSV + JSON + text + relational · Veracity lat = 0, speed = −1, duplicates, tunnel gaps, −99999
GPS CSV and the district table = structured; weather JSON = semi-structured; complaint text = unstructured.
speed = continuous; direction = nominal (⚠️ not ordinal: a compass is a circle); meter_on = nominal (binary)

(b) Pipeline (E/T/L + storage); 3 validation checks; handling a missing speed; one integration problem; a location concept hierarchy.
✅ Pipeline: sources (GPS via Kafka/FTP · PostgreSQL via Sqoop · weather API · text) → Extract (NiFi / Glue) → raw zone of the data lake (HDFS / S3) → Transform in staging (validate → clean → integrate → transform → reduce, with MapReduce / Hive / Spark on YARN) → Load into Hive/ORC warehouse tables → hourly Tableau dashboard; monitoring + scheduling around it.
Checks: Range 13.4 ≤ lat ≤ 14.0, 100.3 ≤ lon ≤ 101.0 (rejects 0), 0 ≤ speed ≤ 200 (rejects −1) · Format timestamp DD-MM-YYYY hh:mm:ss · Presence 8 fields · Type speed numeric.
Missing speed: time series, so forward fill / interpolate or recompute it from the distance between pings. Listwise deletion breaks the trajectory and biases results (gaps cluster in tunnels and dense areas).
Integration: entity identification ("Pathum Wan" vs "Pathumwan" vs the Thai name → a master district code); granularity (hourly weather vs 10-second pings → aggregate to the hour); units (km/h vs m/s → convert).
Hierarchy: (lat, lon) → grid cell → khwaeng → khet → Bangkok → Thailand (time: timestamp → hour → day → week/month → quarter → year). ~4 decimal places ≈ 11 m is enough.

(c) Volume estimate + HDFS at replication 3; file format; hot/warm/cold; lake vs warehouse; privacy; EMR nodes + where the archive lives.
✅ Sizing: 1,000 × 100,000 × 100 B = 10 GB/day → ×400 = 4 TB/year → 12 TB for 3 years → ×3 = 36 TB raw HDFS (the lecture's 15 TB cluster is too small).
Format: ORC (585 → 131 GB, 78% smaller) → 12 TB ≈ 3 TB; the queries read few columns (also OK: Parquet, 62%, for Spark/Impala).
Tiers: Hot (SSD/NVMe/RAM) = today + the dashboard tables · Warm (HDD/HDFS) = recent months in ORC · Cold (tape / Glacier) = raw data older than a year.
Lake vs warehouse: raw archive → data lake (schema-on-read, native format, cheap, "just in case") · dashboard → data warehouse (schema-on-write, cleansed, for business users).
Privacy: substitute driver_id with a pseudonym (trajectories stay linkable), null phone numbers, role-based masking, authentication/authorization, and a data catalog + governance policy.
EMR: 1 primary (NameNode + Resource Manager) · core nodes (DataNode + Node Manager + App Master/executors: storage + tasks) · task nodes added at peak (no data) · archive in S3 via EMRFS (s3://…), so it survives termination; cluster HDFS holds only working data.

(d) Average speed per district per hour: <k2,v2 and <k3,v3; why reducer-as-combiner is wrong + the fix; Pathum Wan has 20× more pings.
✅ Map: validate → map (lat, lon) to a district, take the hour → <(district, date-hour), (speed, 1). Reduce: <(district, date-hour), Σspeed / Σcount.
Combiner bug: split 1 has 10 and 20 → avg 15; split 2 has 60 → avg(15, 60) = 37.5, but the truth is 90/3 = 30. Fix: the combiner emits (sum, count): (30,2) and (60,1) → 90/3 = 30.
Skew: same key → same reducer (hash mod n), so one reducer does 20× the work and the job waits for that straggler; more reducers don't help a single hot key. Mitigate: a (sum, count) combiner, and a finer key (district, hour, grid cell) followed by a small second aggregation.

(e) What if: (i) the vendor changes the timestamp to Unix epoch at midnight · (ii) the weather API is down for 3 hours · (iii) HDFS on the instance store + termination every Friday · (iv) a new empty DataNode gets all the new blocks.
✅ (i) The format check rejects ~100% of rows, so the pipeline fails and the dashboard freezes ("source schema change"). Detect it with validation + monitoring (alert on the rejection rate); quarantine the rows (don't drop them), add an epoch parser, and reprocess from the raw data-lake zone (schema-on-read, so nothing is lost).
(ii) "Source late / unavailable": don't block the pipeline. Publish without weather (or forward-fill it and flag it as an estimate), then backfill and rerun when the API returns; add retries.
(iii) The instance store is ephemeral, so HDFS is erased every Friday and 3-year history never exists. Store the data in S3 via EMRFS and treat the cluster as disposable compute.
(iv) The new node becomes a hotspot (and its failure would hit a lot of recent data). Run the HDFS balancer, hdfs balancer -threshold 5 (default 10%), which moves blocks from over- to under-utilized nodes; limit its network use with hdfs dfsadmin -setBalancerBandwidth.

"What if" answer pattern: what breaks → which component detects or handles it (NameNode heartbeat, validation, monitoring, balancer, YARN) → what you do.