AI Computer Institute
Expert-curated CS & AI curriculum aligned to CBSE standards. A bharath.ai initiative. About Us

Grade 11 AI & Computer Science Practice Questions — Set 10

20 questions from the Grade 11 bank, each with its answer and a full explanation. Set 10 of 11 · 221 questions in this grade.

Reading is revision; testing is practice. Take the same questions as a timed quiz →

Question 181 · Calculus for Machine Learning: Derivatives and Gradient Descent · hard

A machine learning engineer at a Bengaluru fintech startup is training a one-parameter linear model to predict daily UPI transaction volume, whose mean-squared-error loss simplifies to L(w) = 2w² − 8w + 3 (in crore-transactions², where w is the model's single weight). Starting from an initial weight w₀ = 5 with a fixed learning rate η = 0.1, and applying the gradient descent update rule w_{t+1} = w_t − η·L'(w_t) for two successive steps, what is the value of w₂?

  1. w₂ = 3.08, the result of correctly using L'(w) = 4w − 8 in the update rule w_{t+1} = w_t − 0.1·L'(w_t) for two successive steps
  2. w₂ = 4.64, the result of mistakenly using L'(w) = 2w − 8 (dropping the factor of 2 that differentiating 2w² produces) in both update steps
  3. w₂ = 7.88, the result of adding the scaled gradient instead of subtracting it, which moves the weight up the loss curve instead of down toward the minimum
  4. w₂ = 3.80, the result of performing only one gradient descent update from w₀ instead of the two updates the question requires

Answer: A. w₂ = 3.08, the result of correctly using L'(w) = 4w − 8 in the update rule w_{t+1} = w_t − 0.1·L'(w_t) for two successive steps

ExplanationThe loss L(w) = 2w² − 8w + 3 is a quadratic in the single weight w, so by the power rule L'(w) = 4w − 8 — the coefficient 2 on w² doubles under differentiation, and the derivative of the constant 3 is zero, since a vertical shift of the parabola never affects its slope. Starting at w₀ = 5, gradient descent first computes L'(5) = 4(5) − 8 = 12, giving w₁ = w₀ − η·L'(w₀) = 5 − 0.1(12) = 5 − 1.2 = 3.8. Repeating the update from w₁ = 3.8: L'(3.8) = 4(3.8) − 8 = 15.2 − 8 = 7.2, so w₂ = 3.8 − 0.1(7.2) = 3.8 − 0.72 = 3.08. Each step pulls w toward the minimum of the parabola, located where L'(w) = 0, i.e. w* = 2 — the sequence 5 → 3.8 → 3.08 is steadily closing in on 2, exactly as expected on a convex quadratic. This steady convergence is not automatic: since L''(w) = 4 measures the curvature, gradient descent on this loss only converges for η < 2/L'' = 0.5. Because η = 0.1 satisfies that bound, each step shrinks the distance to w* = 2 rather than overshooting or diverging, which is why the weight lands at 3.08 rather than oscillating away from the minimum.

Question 182 · Information Theory: Entropy and KL Divergence · hard

NPCI's UPI transaction monitor logs daily outcomes across three categories — Success, Pending, and Failed — with the true historical distribution P = (1/2, 1/4, 1/4). An older forecasting model, still running in production, instead assigns probabilities Q = (1/4, 1/4, 1/2) to the same three categories. Using D_KL(P‖Q) = Σ p_i log₂(p_i/q_i), what is the Kullback-Leibler divergence (in bits) that measures the excess encoding cost of using the model's Q to describe outcomes actually governed by P?

  1. 1.75 bits, obtained by summing −p_i·log₂(q_i) directly across the three categories instead of the log-ratio term p_i·log₂(p_i/q_i).
  2. 0 bits, since P and Q are permutations of the same three probability values {1/2, 1/4, 1/4} and therefore have identical entropy, meaning no divergence exists between them.
  3. 0.25 bits, found by summing p_i·log₂(p_i/q_i) term-by-term: (1/2)(log₂2) + (1/4)(log₂1) + (1/4)(log₂0.5) = 0.5 + 0 − 0.25.
  4. −0.25 bits, obtained by summing p_i·log₂(q_i/p_i) instead of p_i·log₂(p_i/q_i), inverting the ratio inside the logarithm.

Answer: C. 0.25 bits, found by summing p_i·log₂(p_i/q_i) term-by-term: (1/2)(log₂2) + (1/4)(log₂1) + (1/4)(log₂0.5) = 0.5 + 0 − 0.25.

ExplanationThe Kullback-Leibler divergence D_KL(P‖Q) = Σ p_i log₂(p_i/q_i) measures the expected number of extra bits needed when outcomes generated by the true distribution P are encoded using a code optimized for Q instead. It is not a distance metric — it is asymmetric in general (D_KL(P‖Q) ≠ D_KL(Q‖P)) and requires Q to assign nonzero probability everywhere P does. Here P = (1/2, 1/4, 1/4) for (Success, Pending, Failed) and Q = (1/4, 1/4, 1/2). Computing term by term: - Success: (1/2)·log₂(0.5/0.25) = (1/2)·log₂2 = (1/2)(1) = 0.5 - Pending: (1/4)·log₂(0.25/0.25) = (1/4)·log₂1 = (1/4)(0) = 0 - Failed: (1/4)·log₂(0.25/0.5) = (1/4)·log₂0.5 = (1/4)(−1) = −0.25 Summing gives D_KL(P‖Q) = 0.5 + 0 − 0.25 = 0.25 bits. This positive value holds even though P and Q share the same entropy: H(P) = H(Q) = 1.5 bits, since Q is just P's probability values relabelled across categories (a permutation). Equal entropy only means the two distributions carry the same average uncertainty about their own outcomes — it says nothing about how well one distribution predicts data actually drawn from the other, which is exactly what KL divergence quantifies. A monitoring model can look "correct" by entropy alone while still assigning probability mass to the wrong categories, and that mismatch is what costs real bits (and real risk) once the model is used to encode or forecast actual transaction outcomes. The 1.75-bit figure comes from computing cross-entropy H(P,Q) = −Σ p_i log₂q_i instead of the log-ratio KL term; cross-entropy equals H(P) + D_KL(P‖Q) = 1.5 + 0.25 = 1.75, so it is a related but distinct quantity, not the divergence itself. The −0.25-bit figure comes from inverting the ratio inside the logarithm (using q_i/p_i instead of p_i/q_i), which flips the sign of every term. By Gibbs' inequality — a direct consequence of Jensen's inequality applied to the concave log function — KL divergence is always ≥ 0, so a negative result is a reliable signal that the ratio was inverted.

Question 183 · Variational Autoencoders: Probabilistic Generative Models · hard

A team building a generative model for handwritten Devanagari characters trains a VAE. For one input image x, the encoder network outputs a single-dimensional Gaussian posterior q(z|x) = N(μ, σ²) with μ = 3 and log(σ²) = 0. The prior over the latent variable is the standard normal p(z) = N(0, 1). Using the closed-form KL divergence between two univariate Gaussians, what is the value (in nats) of the KL(q(z|x) ‖ p(z)) term that this dimension contributes to the ELBO loss?

  1. 1.5 nats
  2. 4.5 nats
  3. 5.0 nats
  4. 9.0 nats

Answer: B. 4.5 nats

ExplanationThe ELBO that a VAE maximizes is E_q[log p(x|z)] − KL(q(z|x) ‖ p(z)), so computing this KL term correctly is central to understanding what the loss actually penalizes. For two univariate Gaussians q = N(μ₁, σ₁²) and p = N(μ₂, σ₂²), the KL divergence has the closed form ``` KL(q‖p) = ln(σ₂/σ₁) + (σ₁² + (μ₁ − μ₂)²) / (2σ₂²) − 1/2 ``` Specializing to the VAE prior p(z) = N(0, 1), so μ₂ = 0 and σ₂² = 1, this collapses to ``` KL(q‖p) = 0.5 · (σ₁² + μ₁² − 1 − log σ₁²) ``` which is exactly the per-dimension KL term used in the standard VAE loss (Kingma & Welling, 2013), since ln(σ₁) = 0.5·log(σ₁²). Here the encoder outputs μ = 3 and log(σ²) = 0, so σ² = e⁰ = 1. Substituting: ``` KL = 0.5 · (σ² + μ² − 1 − log σ²) = 0.5 · (1 + 9 − 1 − 0) = 0.5 · 9 = 4.5 nats ``` So the correct value is 4.5 nats. The distractors correspond to genuine derivation slips students make with this formula. 9.0 nats comes from computing (σ² + μ² − 1 − log σ²) = 9 correctly but forgetting the leading factor of 0.5 that comes from the −1/2 constant in the general two-Gaussian KL formula. 5.0 nats comes from dropping the "−1" term inside the parentheses — a natural mistake since it's easy to forget the KL divergence isn't just a sum of second moments but includes a constant correction that makes KL(q‖p) = 0 exactly when q equals the prior N(0,1). 1.5 nats results from using μ instead of μ² in the formula — substituting the mean directly rather than squaring it, giving 0.5·(1 + 3 − 1 − 0) = 1.5, which forgets that KL divergence penalizes squared distance from the prior mean, not linear distance (this matters because it changes how strongly the loss penalizes an encoder that pushes posteriors far from the origin).

Question 184 · LSTMs and GRUs: Solving the Vanishing Gradient Problem · hard

An LSTM's cell state follows the recurrence c_t = f_t ⊙ c_{t-1} + i_t ⊙ g_t, where f_t is the forget gate's sigmoid output at time t, ⊙ is element-wise multiplication, and i_t, g_t are the input gate and candidate values. Consider only the direct backward path through the cell state itself (set aside, for now, how i_t and g_t depend on c_{t-1} through h_{t-1}). Suppose the network has learned to hold the forget gate at a constant f_t = 0.9 (elementwise) at every one of 20 consecutive timesteps along a path used in backpropagation-through-time. What is ∂c_20/∂c_0 along this direct path, and what does this reveal about why LSTMs resist the vanishing gradient problem better than a vanilla RNN whose per-step Jacobian factor tanh′(z_t)·w is typically around 0.3?

  1. ∂c_20/∂c_0 = (0.9 × 0.25)^20 ≈ 1.1×10⁻¹³, because the cell state c_t is itself passed through a tanh nonlinearity at every timestep before being carried forward to c_{t+1}, so each step contributes both the forget-gate factor and a bounded tanh′ factor of at most 0.25, making the LSTM's cell-state path decay just as fast as a saturated vanilla RNN.
  2. ∂c_20/∂c_0 = 0.9^20 ≈ 0.122 (about 12%), because the cell-state recurrence is additive and linear in c_{t-1}, so its local derivative equals the forget gate itself; over 20 steps the gradient shrinks only as fast as the learned forget gate decays from 1, not as fast as the bounded tanh′(z_t)·w product of a vanilla RNN, where a per-step factor of 0.3 would decay the gradient to roughly 0.3^20 ≈ 3.5×10⁻¹¹ — a difference of about ten orders of magnitude.
  3. ∂c_20/∂c_0 = 20 × 0.9 = 18, because the cell-state update is additive (c_t is a sum of a forget term and a candidate term), so backpropagation through the recurrence accumulates the forget-gate values by summation across the 20 timesteps rather than multiplying them, which is precisely why LSTMs avoid vanishing gradients — their gradients grow rather than shrink.
  4. ∂c_20/∂c_0 = 1 exactly, regardless of the value of f_t, because the cell state forms a constant error carousel: once a gate writes to c_t, the internal linear self-loop guarantees gradients neither vanish nor explode no matter how the forget gate is set during training.

Answer: B. ∂c_20/∂c_0 = 0.9^20 ≈ 0.122 (about 12%), because the cell-state recurrence is additive and linear in c_{t-1}, so its local derivative equals the forget gate itself; over 20 steps the gradient shrinks only as fast as the learned forget gate decays from 1, not as fast as the bounded tanh′(z_t)·w product of a vanilla RNN, where a per-step factor of 0.3 would decay the gradient to roughly 0.3^20 ≈ 3.5×10⁻¹¹ — a difference of about ten orders of magnitude.

ExplanationDifferentiating the cell-state recurrence c_t = f_t ⊙ c_{t-1} + i_t ⊙ g_t with respect to c_{t-1} — restricting attention to the direct path, since the gates' dependence on h_{t-1} was explicitly set aside — gives ∂c_t/∂c_{t-1} = f_t. The forget gate literally is the local derivative, with no squashing nonlinearity sitting between c_{t-1} and c_t. Chaining this identity across 20 identical steps multiplies twenty copies of 0.9: 0.9^20 ≈ 0.122, so about 12% of the original gradient survives after 20 timesteps. Compare this to a vanilla RNN's recurrence h_t = tanh(Wh_{t-1} + Ux_t), whose local derivative is diag(tanh′(z_t))·W. Once a unit is even mildly saturated, tanh′(z_t) drops well below 1; compounding a typical combined per-step factor of 0.3 over the same 20 steps gives 0.3^20 ≈ 3.5×10⁻¹¹ — effectively zero in floating point, let alone over the hundreds of steps real sequences require. The LSTM's advantage is not that its gradient never shrinks (0.9^20 is still meaningful decay, not identity), but that the decay rate is a learned quantity bounded only by how close training drives f_t toward 1, rather than being clamped below 1 by a fixed saturating nonlinearity applied at every single step. A GRU has the same algebraic structure in its update-gate recurrence h_t = z_t ⊙ h_{t-1} + (1 − z_t) ⊙ h̃_t, which is why it inherits the same resistance to vanishing gradients. Passing c_t through an extra tanh at every step, treating the additive update as a summed (rather than multiplied) gradient across time, and assuming a perfect constant error carousel regardless of the forget gate's actual value are all specific, common misreadings of this mechanism.

Question 185 · Drug Discovery and Molecular Machine Learning · hard

A computational chemistry intern at an Indian pharmaceutical R&D lab is running a virtual screening pipeline to find lead compounds structurally similar to a reference API (active pharmaceutical ingredient) already approved by the CDSCO, hoping to identify candidates worth synthesizing for a target protein assay. Each molecule is encoded as a binary molecular fingerprint — a length-10 bit vector in which bit *i* is set to 1 if a particular substructural fragment (e.g., a ring system, functional group, or bonding pattern) is present in that molecule, and 0 otherwise. For Molecule P (a screening-library candidate), the bits set to 1 are at positions {1, 2, 3, 5, 7, 9}. For Molecule Q (the reference API), the bits set to 1 are at positions {2, 3, 5, 6, 7, 8}. The screening software ranks candidates by the Tanimoto (Jaccard) similarity coefficient, treating each fingerprint as the *set* of its "on" bit positions: T(P, Q) = |P ∩ Q| / |P ∪ Q|. What is T(P, Q) for this pair of molecules?

  1. 0.33 — obtained by dividing the number of shared fragments by |P| + |Q| directly, without correcting for fragments counted twice across both sets
  2. 0.50 — the number of fragments common to both molecules divided by the total number of distinct fragments present in either molecule
  3. 0.67 — obtained using the Sørensen–Dice coefficient formula, 2|P ∩ Q| / (|P| + |Q|), instead of the Tanimoto formula
  4. 0.75 — obtained by mistakenly assuming every fragment of Molecule P also belongs to Molecule Q, so |P ∩ Q| is taken to equal |P|

Answer: B. 0.50 — the number of fragments common to both molecules divided by the total number of distinct fragments present in either molecule

ExplanationTreat each fingerprint as a set of "on" bit positions: P = {1, 2, 3, 5, 7, 9} and Q = {2, 3, 5, 6, 7, 8}, each with |P| = |Q| = 6. Checking each element of P against Q: 1 ∉ Q, 2 ∈ Q, 3 ∈ Q, 5 ∈ Q, 7 ∈ Q, 9 ∉ Q. So the shared fragments are P ∩ Q = {2, 3, 5, 7}, giving |P ∩ Q| = 4. The union collects every fragment present in at least one molecule: P ∪ Q = {1, 2, 3, 5, 6, 7, 8, 9}, so |P ∪ Q| = 8. This matches the inclusion–exclusion identity |P ∪ Q| = |P| + |Q| − |P ∩ Q| = 6 + 6 − 4 = 8, since the four shared fragments would otherwise be double-counted. Therefore T(P, Q) = |P ∩ Q| / |P ∪ Q| = 4/8 = 0.50. This distinction matters in practice: Tanimoto similarity is the industry-standard metric in cheminformatics precisely because it normalizes by the union (fragments present in *either* molecule), making it robust to molecules of very different total fragment counts — unlike the Sørensen–Dice coefficient (2|P ∩ Q|/(|P|+|Q|) = 8/12 ≈ 0.67), which normalizes by the average size of the two sets instead and is a different, though related, similarity measure sometimes confused with it. Dividing by |P|+|Q| without ever forming the union (4/12 ≈ 0.33) undercounts similarity by penalizing overlap twice, and assuming full containment of one fingerprint in the other (6/8 = 0.75) overstates similarity by miscounting the intersection itself.

Question 186 · Ring Attention: Distributed Attention Across Devices · hard

In Ring Attention, N GPUs are arranged in a ring; each GPU keeps a fixed shard of the query matrix while key/value blocks circulate around the ring, one hop per step. To compute *exact* softmax attention without ever materializing the full row of attention scores on any single device, each GPU maintains a running max m and a running unnormalized softmax denominator l, updating both online as each new K/V block arrives — the same trick FlashAttention uses across on-chip tiles, applied here across devices. Suppose a GPU holding query block Q_i has processed two incoming K/V blocks from its ring neighbours, in order. After block 1, its local softmax reference max is m1 = 2 and its local unnormalized denominator is l1 = 3 (i.e., l1 = Σ exp(score − m1) over block 1's keys). Block 2 then arrives with local max m2 = 5 and local unnormalized denominator l2 = 4, computed the same way. Using the exact online-softmax merge rule Ring Attention relies on — where the merged max is m = max(m1, m2) and each block's denominator is rescaled by exp(local max − m) before being combined — what is the correctly recombined denominator l for the query row after merging these two blocks, using e ≈ 2.71828?

  1. l ≈ 4.15, obtained by updating the running max to m = 5 and shrinking block 1's denominator by e^(2−5) while leaving block 2's term unchanged since its local max already equals the new global max.
  2. l = 7, obtained by simply adding l1 and l2 together, since both partial denominators are assumed to already be expressed relative to the same softmax reference point.
  3. l ≈ 83.34, obtained by leaving the running max fixed at m1 = 2 from the first block and rescaling only block 2's denominator by e^(5−2) to match it.
  4. l ≈ 64.26, obtained by updating the running max to m = 5 but rescaling block 1's denominator by e^(5−2) instead of e^(2−5), inverting the direction of the correction.

Answer: A. l ≈ 4.15, obtained by updating the running max to m = 5 and shrinking block 1's denominator by e^(2−5) while leaving block 2's term unchanged since its local max already equals the new global max.

ExplanationSoftmax is shift-invariant: softmax(x)_j = exp(x_j − c) / Σ_k exp(x_k − c) for any constant c. This is exactly what lets attention be computed block-by-block instead of all at once — each block can pick its own convenient reference constant (its local max, for numerical stability) and the results can later be reconciled onto a common reference. That reconciliation is the log-sum-exp merge rule: given two blocks with local maxima m1, m2 and local unnormalized sums l1, l2, the true global max is m = max(m1, m2), and the merged sum must move every prior partial sum onto that new reference: l = l1·e^(m1−m) + l2·e^(m2−m). Ring Attention performs precisely this update every time a K/V block completes one hop around the ring, which is what lets a device hold only one block of K/V at a time (linear memory per device) while still producing output numerically identical to full, materialized attention. Plugging in the given values: m1 = 2, l1 = 3, m2 = 5, l2 = 4, so the merged max is m = max(2, 5) = 5. Block 1's sum must be rescaled to this new reference: 3·e^(2−5) = 3·e^(−3) ≈ 3 × 0.0498 ≈ 0.149. Block 2's local max already equals the new global max, so its term needs no rescaling: 4·e^(5−5) = 4·e^0 = 4. Adding these gives l ≈ 0.149 + 4 = 4.149 ≈ 4.15. The three wrong values each correspond to a genuine implementation bug in this merge step: adding l1 and l2 directly (7) ignores that the two blocks used different reference constants and are therefore not yet comparable; freezing the running max at the first block's value (83.34) fails to track the true row-wise maximum as larger scores arrive later in the ring rotation, which also risks numerical overflow in the un-rescaled term; and rescaling block 1's sum by e^(5−2) instead of e^(2−5) (64.26) flips the sign of the correction, inflating rather than shrinking the older block's contribution. Getting this recurrence exactly right — not approximately right — is what makes Ring Attention mathematically equivalent to standard full attention rather than an approximation.

Question 187 · Data Warehousing: Building Analytics Powerhouses · hard

An Indian e-commerce company's central data warehouse fact table, at the grain "one row per completed order," holds 8 crore (80,000,000) rows. To speed up OLAP queries that slice sales by payment method, a data engineer builds a bitmap index on the Payment_Mode dimension column, which takes exactly 4 distinct values — UPI, Debit/Credit Card, Cash on Delivery, and Net Banking. A bitmap index stores one separate bitmap vector per distinct value, and each vector contains exactly one bit per fact-table row (that bit is 1 if the row's Payment_Mode matches the vector's value, else 0). Bits are packed 8 to a byte with no padding, and 1 MB is taken as 2^20 bytes. What is the total storage required for this entire bitmap index, in MB?

  1. ≈38.15 MB — obtained by multiplying rows by the column's cardinality of 4 to get total bits, packing 8 bits per byte, then dividing by 2^20 bytes/MB
  2. ≈9.54 MB — treats the index as a single 80,000,000-bit vector, missing that one full bitmap must be stored separately for each distinct Payment_Mode value
  3. 40.00 MB — correctly computes 40,000,000 total bytes but divides by 10^6 (decimal MB) instead of 2^20, understating the true binary-MB size
  4. ≈305.18 MB — correctly multiplies rows by the 4 distinct values to get total bits, but skips converting bits to bytes before dividing by 2^20, overstating storage by a factor of 8

Answer: A. ≈38.15 MB — obtained by multiplying rows by the column's cardinality of 4 to get total bits, packing 8 bits per byte, then dividing by 2^20 bytes/MB

ExplanationA bitmap index's size scales with two independent factors — the number of fact-table rows AND the number of distinct values in the indexed column — because a separate bit-vector is stored per distinct value, and each vector must be as long as the table itself. With cardinality 4 and 80,000,000 rows, total bits needed = 4 × 80,000,000 = 320,000,000 bits. Packing 8 bits per byte with no padding: 320,000,000 ÷ 8 = 40,000,000 bytes. Converting to binary MB (2^20 = 1,048,576 bytes per MB): 40,000,000 ÷ 1,048,576 ≈ 38.1469 MB, which rounds to 38.15 MB. This is exactly why bitmap indexes are the standard choice in star-schema data warehouses for low-cardinality dimension columns like payment mode, gender, or a boolean flag, but a poor choice for high-cardinality columns like customer_id: storage grows linearly with the number of distinct values, so a 4-valued column costs only about 4 times a single full-table bit-vector, and in return the warehouse gets extremely fast bitwise AND/OR/XOR operations for combining filters across multiple dimensions — something a B-tree index cannot match on columns with few repeating values.

Question 188 · Semantic Segmentation: Pixel-Level Understanding · hard

A Grade 11 project team trains a 3-class semantic segmentation model to label a 10×10-pixel patch of ISRO Cartosat-3 satellite imagery as Background, Building, or Road. On a held-out 100-pixel test patch, the confusion matrix (rows = ground truth, columns = predicted) is: | Actual \ Predicted | Background | Building | Road | Row total | |---|---|---|---|---| | Background | 50 | 3 | 2 | 55 | | Building | 4 | 20 | 1 | 25 | | Road | 1 | 2 | 17 | 20 | | Column total | 55 | 25 | 20 | 100 | The standard evaluation metric for semantic segmentation, mean Intersection-over-Union (mIoU), is defined as the unweighted average of each class's IoU = TP/(TP+FP+FN), taken across ALL classes including background. What is the mIoU for this confusion matrix?

  1. ≈0.746 — the mean of the three per-class IoU values (50/60 for Background, 20/30 for Building, 17/23 for Road), each class weighted equally regardless of its pixel count.
  2. ≈0.870 — this equals the overall pixel accuracy of 87/100, which is a different metric that simply divides all correctly classified pixels by the total pixel count.
  3. ≈0.703 — the mean IoU obtained by averaging only the Building and Road IoU values and leaving Background out of the average entirely.
  4. ≈0.770 — the ratio obtained by first summing TP, FP, and FN across all three classes and then computing a single combined IoU, rather than averaging the three separate per-class ratios.

Answer: A. ≈0.746 — the mean of the three per-class IoU values (50/60 for Background, 20/30 for Building, 17/23 for Road), each class weighted equally regardless of its pixel count.

ExplanationFor each class, TP is the diagonal entry, FN is (row total − TP), and FP is (column total − TP), since the row total holds every ground-truth pixel of that class and the column total holds every pixel the model predicted as that class. Background: TP=50, row total=55, column total=55, so FN=55−50=5 and FP=55−50=5. IoU = 50/(50+5+5) = 50/60 = 0.833. Building: TP=20, row total=25, column total=25, so FN=5 and FP=5. IoU = 20/(20+5+5) = 20/30 = 0.667. Road: TP=17, row total=20, column total=20, so FN=3 and FP=3. IoU = 17/(17+3+3) = 17/23 = 0.739. mIoU is the macro-average of these three ratios: (0.833 + 0.667 + 0.739)/3 = 2.239/3 ≈ 0.746. Pixel accuracy — (50+20+17)/100 = 87/100 = 0.870 — counts every correct pixel equally, so it is dominated by whichever class has the most pixels (here, Background). A model can score high on pixel accuracy while performing poorly on smaller classes like Road, which is exactly why mIoU is preferred: it forces every class, however rare, to contribute equally to the score. Dropping Background from the average (giving 0.703) is a common error when students assume "background doesn't count," but the standard mIoU definition includes every class present in the label set unless a task explicitly states otherwise. Pooling TP, FP, and FN globally before dividing (87/113 ≈ 0.770) computes a pixel-weighted "micro" IoU instead of the class-balanced "macro" average that mIoU is defined to be — it silently lets the largest class dominate again, defeating the entire purpose of using IoU over pixel accuracy in the first place.

Question 189 · AI Art Ethics: Ownership, Bias, and Indian Cultural Context · hard

An Indian ed-tech team audits the training data behind a text-to-image model before deploying it in a Grade 11 AI ethics module. Of the 500,000 images tagged "painting" in the training set, only 900 are labelled as Madhubani, Warli, or Pattachitra — India's major traditional folk-painting traditions. Published studies on diffusion models show that when a prompt like "a painting" is left unconditioned (no style specified), the model's output style frequency closely tracks that style's frequency in the training data. The class runs this unconditioned prompt 5,000 times as a data-bias experiment. Based on this training-data frequency, how many outputs should the class expect to show an Indian traditional folk style, how does this compare to India's roughly 17.8% share of world population, and which framing of the resulting gap — bias/erasure versus copyright infringement — is legally and ethically accurate?

  1. The model would be expected to render Indian traditional styles in about 9 of the 5,000 outputs (5,000 × 900⁄500,000 ≈ 0.18%) — nearly 99 times below the 17.8% that population-proportional representation would predict; since Madhubani, Warli, and Pattachitra are styles belonging to entire communities rather than a single identifiable author, this gap reflects a bias/erasure problem, not copyright infringement.
  2. Multiplying 5,000 by a rounded 900⁄500,000 ≈ 1.8% gives about 90 expected Indian-style outputs, and since each Madhubani or Warli piece carries individual copyright held by its creator's family, training on these images without licensing is a clear copyright violation.
  3. The correct count is 9 expected Indian-style outputs, yet the Indian Copyright Act extends the same individual-author protections to folk traditions as it does to named artists, making this underrepresentation legally prosecutable copyright infringement rather than a bias concern.
  4. Because generative models sample new images in proportion to a style's real-world population share rather than its training-set frequency, about 890 of the 5,000 outputs (5,000 × 17.8%) would show Indian traditional styles, meaning no representation bias exists in this scenario.

Answer: A. The model would be expected to render Indian traditional styles in about 9 of the 5,000 outputs (5,000 × 900⁄500,000 ≈ 0.18%) — nearly 99 times below the 17.8% that population-proportional representation would predict; since Madhubani, Warli, and Pattachitra are styles belonging to entire communities rather than a single identifiable author, this gap reflects a bias/erasure problem, not copyright infringement.

ExplanationThe expected count follows directly from the model's training-frequency approximation: 5,000 × (900⁄500,000) = 5,000 × 0.0018 = 9 expected outputs in an Indian traditional style. Comparing this training-set frequency (0.18%) to India's share of world population (17.8%) gives a ratio of 17.8⁄0.18 ≈ 99, meaning the model would portray these traditions at a rate roughly 99 times lower than population-proportional representation would suggest — a measurable, quantifiable bias baked into the training corpus itself rather than into any individual prompt. On ownership: copyright law protects a specific original expression — a particular painting, photograph, or drawing — created by an identifiable author, not a style, technique, or genre; this is the same principle that means no one holds copyright over "Impressionism" or "oil painting" as such. Madhubani, Warli, and Pattachitra are centuries-old community traditions passed across generations of artists, so the traditions themselves carry no single copyright holder that a model could be said to have infringed simply by learning the style. The underrepresentation the class measured is therefore correctly diagnosed as a bias/erasure problem — a skewed training corpus causing entire cultural traditions to nearly vanish from unprompted outputs — and is a separate legal question from copyright infringement, which would instead depend on whether specific copyrighted images were used without a license, not on how frequently a style appears in outputs.

Question 190 · Transformer Architecture from Scratch · hard

You are implementing scaled dot-product attention from scratch for a CBSE Class 11 AI project, following Vaswani et al.'s original Transformer (d_model = 512, h = 8 heads, so d_k = d_model/h = 64). Each entry of your query vector q and key vector k is drawn independently with mean 0 and variance 1, and all 64 entries within q are mutually independent (same for k), with q and k independent of each other. Before any scaling is applied, what is the standard deviation of the dot product q·k, and does dividing by √d_k = 8 correctly restore the score to unit variance?

  1. Std = 8; dividing q·k by 8 (=√d_k) brings its variance down to exactly 1, which is precisely the 1/√d_k scaling the paper applies before the softmax.
  2. Std = 64; dividing q·k by 64 brings its variance down to 1, so the paper's 1/√d_k factor equals 1/64 in this case.
  3. Std = 8, yet unit variance actually needs dividing by d_k itself (64), so 1/√d_k under-corrects and leaves the scores too large going into the softmax.
  4. Std = √512 ≈ 22.6, since the relevant scaling dimension is d_model, not the per-head key dimension d_k = 64.

Answer: A. Std = 8; dividing q·k by 8 (=√d_k) brings its variance down to exactly 1, which is precisely the 1/√d_k scaling the paper applies before the softmax.

ExplanationModel each coordinate q_i and k_i as independent, mean-zero, unit-variance random variables, with q and k also independent of each other. For one coordinate, Var(q_i k_i) = E[q_i²k_i²] − (E[q_i k_i])² = E[q_i²]·E[k_i²] − 0 = 1·1 = 1, using independence and the fact that E[x²] = Var(x) when the mean is zero. The 64 coordinate products q_i k_i are themselves independent, so the variance of the sum q·k = Σ_{i=1}^{64} q_i k_i equals the sum of the 64 individual variances: Var(q·k) = 64 × 1 = 64, giving standard deviation √64 = 8. Dividing a random variable by a constant c scales its variance by 1/c², so dividing q·k by c = 8 gives Var(q·k/8) = 64/8² = 1 — exactly unit variance. Since 8 = √64 = √d_k, this is exactly the paper's 1/√d_k scaling, and it depends only on the per-head dimension d_k, not on d_model = 512. Dividing by d_k = 64 instead (rather than √d_k) would shrink the variance to 64/64² = 1/64, over-correcting and flattening the softmax rather than stabilizing it. This is precisely why the √d_k divisor matters in practice: without it, as d_k grows, dot-product scores grow in magnitude, pushing the softmax into saturated regions with near-zero gradients and making the network much harder to train.

Question 191 · Contrastive Learning: Learning from Similarities · hard

ISRO's self-supervised pretraining team trains a contrastive (SimCLR-style) encoder on unlabeled satellite image patches. After L2-normalisation, every embedding is a unit vector, so cosine similarity equals the plain dot product. In one mini-batch, the anchor patch embedding is z_a = (1, 0). The positive key — a differently-augmented view of the *same* patch — is z_p = (0.5, √3/2). Two negative keys, from unrelated patches, are z_n1 = (0, 1) and z_n2 = (−1, 0). Using the InfoNCE loss L_i = −log[ exp(sim(z_a, z_p)/τ) / Σ_k exp(sim(z_a, z_k)/τ) ] with temperature τ = 0.5, where the sum in the denominator runs over the positive key and both negative keys, what is L_i, in nats, to three decimal places?

  1. L_i ≈ 0.349 nats, obtained by dividing each cosine similarity by τ before exponentiating and summing over all three keys.
  2. L_i ≈ 0.604 nats, obtained by using the raw cosine similarities directly as logits without dividing by τ first.
  3. L_i ≈ 0.812 nats, obtained by multiplying each cosine similarity by τ instead of dividing by it before exponentiating.
  4. L_i ≈ 0.504 nats, obtained by dividing by τ correctly but then taking log base 2 instead of the natural logarithm.

Answer: A. L_i ≈ 0.349 nats, obtained by dividing each cosine similarity by τ before exponentiating and summing over all three keys.

ExplanationBecause all embeddings are unit vectors, cosine similarity is just the dot product. sim(z_a, z_p) = (1)(0.5) + (0)(√3/2) = 0.5. sim(z_a, z_n1) = (1)(0) + (0)(1) = 0. sim(z_a, z_n2) = (1)(−1) + (0)(0) = −1. The InfoNCE logits are these similarities scaled by 1/τ, with τ = 0.5, i.e. multiplied by 2: the positive logit is 0.5/0.5 = 1.0, the first negative logit is 0/0.5 = 0.0, and the second negative logit is −1/0.5 = −2.0. Temperature scaling sharpens the softmax — dividing by a small τ spreads the logits further apart before the exponential, which is exactly what makes contrastive training push hard negatives away more forcefully. Exponentiating: e^1.0 = 2.71828, e^0.0 = 1.00000, e^−2.0 = 0.13534. These sum to 3.85362, and the positive key's share of that sum is 2.71828 / 3.85362 = 0.70539. The loss is the negative natural log of this softmax probability: L_i = −ln(0.70539) ≈ 0.349 nats. A value this close to zero signals the encoder already ranks the true augmented pair well above the negatives, since −ln(1) = 0 would be the loss for a perfect match. The distractors reproduce specific, common implementation slips. Skipping the division by τ entirely (using the raw similarities 0.5, 0, −1 as logits) understates how peaked the distribution should be and gives ≈0.604 nats. Multiplying by τ instead of dividing by it does the opposite — it flattens the logits to 0.25, 0, −0.5 — and gives ≈0.812 nats, a much larger loss than the model actually has. Dividing by τ correctly but then evaluating the loss with log base 2 instead of natural log (a mix-up with information-theoretic bits) rescales the correct softmax probability's loss by 1/ln(2), giving ≈0.504 nats — numerically plausible but inconsistent with how the InfoNCE loss (and its cross-entropy form) is defined using natural log.

Question 192 · StyleGAN: Style Transfer in Generation · hard

In a StyleGAN synthesis block, AdaIN operates on a feature map one channel at a time: it normalizes the channel to zero mean and unit variance using that channel's own spatial statistics, then rescales and shifts it using per-channel style parameters (y_s, y_b) produced from the intermediate latent vector w by a learned affine transform "A". Suppose one channel has 4 spatial activations, before AdaIN, of 1, 1, 5, 5, and for this channel A(w) outputs scale y_s = 1.5 and bias y_b = -0.5. Using the population variance (divide by N, not N-1) for the instance statistics, what is the AdaIN output for the activation whose raw value is 1, and which statement correctly describes the underlying mechanism?

  1. -2.0 is the correct output: normalize using channel mean 3 and standard deviation 2, giving (1-3)/2 = -1, then apply y_s and y_b as 1.5 x (-1) + (-0.5) = -2.0 -- AdaIN erases the channel's original statistics before re-imposing the style from w, which is exactly why feeding different w vectors into different resolution levels produces clean style mixing rather than blended artifacts.
  2. 1.0 is the output if AdaIN is treated as a plain affine layer applied directly to the raw activation, 1.5 x 1 + (-0.5) = 1.0, skipping instance normalization entirely -- but this ignores that AdaIN's defining property is removing the channel's own mean and variance first, not simply reweighting the unnormalized value.
  3. 2.0 results from swapping the roles of the two style parameters, computing (-0.5) x (-1) + 1.5 = 2.0 -- treating y_b as the multiplicative scale and y_s as the additive bias -- whereas the synthesis network's learned affine transform actually designates y_s as the scale and y_b as the bias for that channel.
  4. -1.25 results from normalizing with the channel's variance instead of its standard deviation, computing (1-3)/4 = -0.5, then 1.5 x (-0.5) + (-0.5) = -1.25 -- but instance normalization divides by the standard deviation, the square root of the variance, not the variance itself.

Answer: A. -2.0 is the correct output: normalize using channel mean 3 and standard deviation 2, giving (1-3)/2 = -1, then apply y_s and y_b as 1.5 x (-1) + (-0.5) = -2.0 -- AdaIN erases the channel's original statistics before re-imposing the style from w, which is exactly why feeding different w vectors into different resolution levels produces clean style mixing rather than blended artifacts.

ExplanationAdaIN is computed per channel, per instance: given a channel's spatial activations, compute the instance mean μ and instance standard deviation σ (population statistics, dividing by N), normalize each activation as (x − μ)/σ, then apply the style-specific scale and bias: AdaIN(x) = y_s · (x − μ)/σ + y_b. For the channel values 1, 1, 5, 5, the mean is μ = 3 and the variance is (4+4+4+4)/4 = 4, so σ = 2. For the activation x = 1, the normalized value is (1 − 3)/2 = −1, and applying the given style parameters gives 1.5 × (−1) + (−0.5) = −2.0. This matters for style transfer because normalization discards the channel's original mean and variance — the "content" statistics inherited from the previous layer — before the style parameters derived from w reintroduce a fresh mean and variance. Because every synthesis block re-injects w this way, swapping in different w vectors at different resolution levels (style mixing) genuinely replaces coarse features like pose and face shape at low-resolution blocks and fine features like color and texture at high-resolution blocks, rather than producing a blend of two contents.

Question 193 · Drug Discovery AI: Accelerating Medicine · hard

A Hyderabad-based AI drug-discovery startup builds a machine-learning model to prioritize which molecules from a virtual compound library to test in the lab against an EGFR kinase target (relevant to lung-cancer therapy). The full library has 10,000 candidate molecules, of which 200 are experimentally confirmed true binders (validated in earlier wet-lab assays used as ground truth). The AI ranks all 10,000 molecules by predicted binding score. Among the top-ranked 1,000 molecules (the top 10% of the library), 100 turn out to be true binders. Using the standard virtual-screening enrichment factor, EF(x%) = [hits in top x% / molecules in top x%] ÷ [total hits / total molecules], what is EF(10%) for this model, and what does that value mean?

  1. EF(10%) = 5, meaning the top-ranked decile is five times as enriched in true binders as a random selection drawn from the whole library.
  2. EF(10%) = 10, since 10% of the top-ranked molecules turned out to be true binders, so the model is said to perform ten times better than chance.
  3. EF(10%) = 0.2, because the baseline library-wide hit rate of 2% must be divided by the top-decile hit rate of 10% to compare the two screening strategies.
  4. EF(10%) = 0.5, since only 100 of the library's 200 true binders were captured within the top decile, giving the fraction of actives recovered.

Answer: A. EF(10%) = 5, meaning the top-ranked decile is five times as enriched in true binders as a random selection drawn from the whole library.

ExplanationEnrichment factor compares how concentrated true binders are in the model's top-ranked subset versus what plain random screening would give. First compute the two hit rates separately. The library-wide (random) hit rate is total hits divided by total molecules: 200/10,000 = 0.02, i.e. 2%. The top-decile hit rate is hits found in that subset divided by the subset's size: 100/1,000 = 0.10, i.e. 10%. The enrichment factor is the ratio of the selected hit rate to the baseline hit rate: EF(10%) = 0.10 / 0.02 = 5. This says the AI model's top 10% of predictions is five times richer in true EGFR binders than picking 1,000 molecules at random — exactly the kind of prioritization gain that lets a pharma lab test far fewer compounds experimentally while still finding most of the actives, which is the whole economic case for AI-driven virtual screening. The 10 value mistakes the raw top-decile hit-rate percentage (10%) for the enrichment factor itself, forgetting that enrichment is measured relative to the random baseline, not in isolation — a 10% hit rate is only impressive if random screening does much worse than 10%, which is exactly what dividing by the baseline captures. The 0.2 value inverts the ratio, computing baseline-over-selected instead of selected-over-baseline; that inverted quantity would only fall below 1 when the model performs worse than random, which contradicts the model clearly concentrating actives near the top. The 0.5 value is a real, useful number — it is the recall (fraction of all 200 true binders captured in the top decile, 100/200) — but recall answers "how much of the total treasure did we find," while enrichment factor answers "how much better than chance is our search," and the question specifically asks for the latter.

Question 194 · Actor-Critic: Policy + Value Learning · hard

An IRCTC-style dynamic fare-adjustment agent uses one-step actor-critic (TD(0)) reinforcement learning. Its critic maintains a state-value estimate V(s), and its actor maintains a softmax policy π(a|s;θ). At time step t, the critic estimates V(s_t) = 10 and V(s_{t+1}) = 13 (in scaled reward units), the agent receives reward r_t = 4 after taking action a_t (raising fares on a high-demand route), and the discount factor is γ = 0.9. Using the standard one-step actor-critic update rule, what is the TD error δ_t used as the advantage estimate, and how should the actor adjust the probability of having taken a_t in s_t?

  1. δ_t = r_t + γV(s_{t+1}) − V(s_t) = 4 + 0.9(13) − 10 = 5.7; since δ_t > 0, the actor increases π(a_t|s_t) by updating θ ← θ + α_θ δ_t ∇_θ ln π(a_t|s_t;θ), because the action performed better than the critic's baseline expectation.
  2. δ_t = r_t + V(s_{t+1}) − V(s_t) = 4 + 13 − 10 = 7; since δ_t > 0, the actor increases π(a_t|s_t) using this undiscounted TD error, because the discount factor only applies to the critic's own bootstrapped update, not to the actor's advantage signal.
  3. Using δ_t = r_t + γV(s_{t+1}) − V(s_t), which equals 4 + 0.9(13) − 10 = 5.7, the actor should decrease π(a_t|s_t) rather than increase it, because a positive TD error means the critic underestimated V(s_t) and the correction should be absorbed by the value function, not the policy.
  4. δ_t = V(s_t) − r_t − γV(s_{t+1}) = 10 − 4 − 0.9(13) = −5.7; since δ_t < 0, the actor decreases π(a_t|s_t) by updating θ ← θ + α_θ δ_t ∇_θ ln π(a_t|s_t;θ), because the action underperformed relative to the critic's estimate.

Answer: A. δ_t = r_t + γV(s_{t+1}) − V(s_t) = 4 + 0.9(13) − 10 = 5.7; since δ_t > 0, the actor increases π(a_t|s_t) by updating θ ← θ + α_θ δ_t ∇_θ ln π(a_t|s_t;θ), because the action performed better than the critic's baseline expectation.

ExplanationThe one-step actor-critic algorithm combines TD(0) value learning (the critic) with policy-gradient updates (the actor) using the critic's TD error as a low-variance estimate of the advantage function A(s_t,a_t) = Q(s_t,a_t) − V(s_t). Step 1 — compute the TD error: δ_t = r_t + γV(s_{t+1}) − V(s_t) = 4 + 0.9 × 13 − 10 = 4 + 11.7 − 10 = 5.7. Step 2 — interpret the sign: δ_t is a sample estimate of how much better (or worse) the return actually received was compared to the critic's expectation V(s_t) at the moment action a_t was chosen. δ_t = 5.7 > 0 means the fare-raising action led to more reward-to-go than the critic predicted, so a_t was better than average for that state. Step 3 — apply the update rules: the critic moves its estimate toward the bootstrapped target, V(s_t) ← V(s_t) + α_w δ_t, while the actor performs gradient ascent on expected return using δ_t in place of the true (unknown) advantage: θ ← θ + α_θ δ_t ∇_θ ln π(a_t|s_t;θ). Because δ_t is positive, this pushes θ in the direction that raises the log-probability of a_t in state s_t — the actor becomes more likely to raise fares again in similar high-demand states. The critic's role as a subtracted baseline matters here: because E[δ_t | s_t] equals the true advantage under the current policy, using δ_t rather than the raw bootstrapped return r_t + γV(s_{t+1}) keeps the policy-gradient estimate unbiased while sharply reducing its variance compared to plain REINFORCE. The three incorrect statements each embed a specific, common actor-critic error. One drops the discount factor before bootstrapping off V(s_{t+1}), turning 5.7 into an incorrect 7 and inventing a nonexistent 'actor-only, undiscounted' rule — γ discounts every bootstrapped estimate the critic produces, and the actor consumes that same δ_t unchanged. Another computes δ_t correctly as 5.7 but then reasons that a positive TD error should shrink the action's probability, inverting the entire gradient-ascent direction: a positive δ_t always means 'do more of this,' not 'let the critic quietly absorb the credit.' The last one flips the sign of the TD-error formula itself, computing V(s_t) − r_t − γV(s_{t+1}) instead of r_t + γV(s_{t+1}) − V(s_t), which lands on −5.7 and decreases the action's probability — the right-looking direction reached through the wrong formula and the wrong numeric error.

Question 195 · Process Scheduling: Algorithms & Trade-offs · hard

An IRCTC ticket-booking server's OS scheduler receives four batch jobs (fare-caching, seat-map refresh, PNR-status sync, and waitlist recompute) at the arrival times below, each needing the listed CPU burst before it can hand results back: | Process | Arrival Time (ms) | Burst Time (ms) | |---|---|---| | P1 | 0 | 8 | | P2 | 1 | 4 | | P3 | 2 | 9 | | P4 | 3 | 5 | The scheduler uses preemptive Shortest-Remaining-Time-First (SRTF): at every arrival, it compares the new job's burst against the *remaining* time of whichever job is currently running, and switches immediately if the new job is shorter. No two jobs ever have equal remaining time at a decision point in this trace. What is the average waiting time (in ms) across all four processes?

  1. 6.50 ms — obtained by running SRTF exactly as specified: P1 runs 0-1 (remaining drops to 7) then is preempted by P2 (burst 4 < 7); P2 runs 1-5 uninterrupted since neither P3's 9 nor P4's 5 ever undercuts its shrinking remainder; at t=5 the shortest remainder is P4 (5), which runs 5-10; then P1's leftover 7 runs 10-17; P3 runs last, 17-26 — giving waits of 9, 0, 15, 2 ms
  2. 7.75 ms — obtained by treating this as non-preemptive SJF instead: the CPU is never taken away from a running job, so a shorter job that arrives mid-burst must wait until the CPU next goes idle before it can be dispatched
  3. 13.00 ms — obtained by correctly building the SRTF Gantt chart and completion times, but then averaging turnaround time (completion minus arrival) for each process instead of waiting time (turnaround minus burst)
  4. 8.75 ms — obtained by ignoring remaining-time comparisons entirely and running the four jobs strictly in arrival order back-to-back, i.e. plain FCFS with no preemption

Answer: A. 6.50 ms — obtained by running SRTF exactly as specified: P1 runs 0-1 (remaining drops to 7) then is preempted by P2 (burst 4 < 7); P2 runs 1-5 uninterrupted since neither P3's 9 nor P4's 5 ever undercuts its shrinking remainder; at t=5 the shortest remainder is P4 (5), which runs 5-10; then P1's leftover 7 runs 10-17; P3 runs last, 17-26 — giving waits of 9, 0, 15, 2 ms

ExplanationTrace SRTF minute by minute, always comparing the *remaining* time of the running process against every newly arrived job's full burst. ``` t=0: only P1 present (rem 8) -> P1 runs t=1: P2 arrives (burst 4). Running P1 has rem 7. 4 < 7 -> preempt, run P2. P1's rem stays 7 (it only executed 1 ms). t=2: P3 arrives (burst 9). P2 has rem 3 (ran 1 ms of its 4). 9 > 3 -> P2 keeps running. t=3: P4 arrives (burst 5). P2 has rem 2. 5 > 2 -> P2 keeps running. t=4: P2 has rem 1, no new arrivals -> P2 keeps running. t=5: P2 completes (ran 1-5, all 4 ms). Candidates: P1 rem 7, P3 rem 9, P4 rem 5. Smallest is P4 -> run P4. t=5-10: P4 runs uninterrupted (no new arrivals; its remainder 5->0 stays below P1's 7 and P3's 9 throughout) -> P4 completes at t=10. t=10: Candidates: P1 rem 7, P3 rem 9. P1 smaller -> run P1. t=10-17: P1 runs its remaining 7 ms uninterrupted -> completes at t=17. t=17-26: only P3 left (rem 9) -> runs uninterrupted -> completes at t=26. ``` Completion times: P2=5, P4=10, P1=17, P3=26. Waiting time = (Completion − Arrival) − Burst for each process: - P1: (17−0)−8 = 9 ms - P2: (5−1)−4 = 0 ms - P3: (26−2)−9 = 15 ms - P4: (10−3)−5 = 2 ms Average waiting time = (9+0+15+2)/4 = 26/4 = **6.50 ms**. This trace is the classic illustration of SRTF's core trade-off: P2 and P4 (the short jobs) finish almost immediately after arriving, but P3 — unlucky enough to be the longest job and to arrive while shorter jobs keep cutting in line — waits 15 ms before it ever touches the CPU. SRTF minimizes average waiting time among all scheduling policies for a fixed arrival/burst sequence, but it does so by risking starvation of long jobs and by paying a preemption (context-switch) cost that this idealized trace ignores. The 7.75 ms option comes from dropping preemption (non-preemptive SJF only picks a new job when the CPU frees up, so P2 would have to wait until t=8 instead of jumping in at t=1); the 8.75 ms option comes from ignoring burst length altogether and running strict FCFS; and the 13.00 ms option is the average *turnaround* time for this same correct SRTF trace — a common bookkeeping slip since turnaround and waiting time differ by exactly the burst time of each process.

Question 196 · Variational Autoencoders: Teaching Machines to Dream · hard

A VAE's encoder network processes an input image and outputs the parameters of a 2-dimensional diagonal Gaussian posterior q(z|x) = N(z; μ, diag(σ²)): mean vector μ = (0, 1) and log-variance vector log σ² = (0, 1) for the two latent dimensions. The KL-divergence term added to the negative ELBO loss for a diagonal Gaussian posterior against the standard normal prior N(0, I) has the closed form KL(q(z|x) ‖ N(0,I)) = (1/2) Σᵢ (σᵢ² + μᵢ² − 1 − log σᵢ²). Computing σᵢ² correctly as exp(log σᵢ²) for each dimension, what is the total KL-divergence value (in nats) this encoder output contributes to the loss?

  1. ≈0.859 nats — dimension 1 (μ=0, σ²=1) already matches the prior and contributes 0, while dimension 2 contributes (e−1)/2 ≈ 0.859
  2. ≈1.859 nats, obtained by summing σᵢ²+μᵢ²−log σᵢ² for each dimension and halving, without subtracting the '−1' term per dimension
  3. ≈4.5 nats, obtained by recovering each σᵢ² as 10^(log σᵢ²) instead of exp(log σᵢ²), then applying the formula unchanged
  4. ≈−0.5 nats, obtained by plugging the raw log σᵢ² values directly in as σᵢ² instead of first exponentiating them

Answer: A. ≈0.859 nats — dimension 1 (μ=0, σ²=1) already matches the prior and contributes 0, while dimension 2 contributes (e−1)/2 ≈ 0.859

ExplanationFor a diagonal-covariance Gaussian posterior, the KL divergence to the standard normal prior decomposes into an independent term per latent dimension, so each dimension can be evaluated separately before summing. Dimension 1 has μ₁ = 0 and log σ₁² = 0, so σ₁² = e⁰ = 1. Substituting into the per-dimension term: σ₁² + μ₁² − 1 − log σ₁² = 1 + 0 − 1 − 0 = 0. This dimension's posterior is already N(0,1), identical to the prior, so it correctly contributes zero divergence — a well-behaved dimension carries no information cost. Dimension 2 has μ₂ = 1 and log σ₂² = 1, so σ₂² = e¹ = e ≈ 2.71828. Substituting: σ₂² + μ₂² − 1 − log σ₂² = e + 1 − 1 − 1 = e − 1 ≈ 1.71828. Summing the two per-dimension terms gives 0 + (e − 1) = e − 1, and halving per the formula gives KL = (e − 1)/2 ≈ 0.859 nats — the value this encoder output contributes to the loss. The ≈1.859 nats answer comes from dropping the '−1' inside each per-dimension term before halving, silently removing the penalty that keeps this divergence from exploding as latent dimensionality grows — an easy transcription slip when implementing the formula by hand. The ≈4.5 nats answer comes from decoding log σ² with base-10 exponentiation instead of the natural exponential that the Gaussian's own definition (and frameworks like PyTorch/TensorFlow) require, wildly overestimating each σᵢ². The ≈−0.5 nats answer comes from forgetting that the encoder head outputs log-variance rather than variance itself, and plugging the raw log σ² values in as σ² directly — a genuine and common implementation bug, whose telltale sign is that it yields a negative number, something a true divergence between two probability distributions can never actually produce.

Question 197 · Building a Blog with Flask and SQLAlchemy · hard

A student is building a personal blog for a CBSE Computer Science project using Flask and Flask-SQLAlchemy. The models are defined as: ```python from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100)) comments = db.relationship('Comment', backref='post', lazy=True) class Comment(db.Model): id = db.Column(db.Integer, primary_key=True) body = db.Column(db.Text) post_id = db.Column(db.Integer, db.ForeignKey('post.id')) ``` The database currently holds exactly 8 Post rows (each with at least one comment). The home route runs: ```python @app.route('/') def home(): posts = Post.query.all() for post in posts: print(len(post.comments)) return render_template('home.html', posts=posts) ``` Assuming no caching beyond SQLAlchemy's default session identity map and no query result is reused across requests, how many total SQL SELECT statements does this view function execute against the database?

  1. 9 queries total — the loop triggers a separate SELECT for each post's comments due to the default lazy='select' loading strategy, the classic N+1 pattern.
  2. 8 queries total, since only the comment lookups inside the loop count as database access; retrieving the post list itself is cached in Python memory.
  3. 2 queries total, because SQLAlchemy automatically rewrites the loop into a single JOIN that eagerly fetches every post's comments alongside the posts.
  4. 16 queries total, because each access to post.comments issues one query to count the comments and a second query to actually retrieve the rows.

Answer: A. 9 queries total — the loop triggers a separate SELECT for each post's comments due to the default lazy='select' loading strategy, the classic N+1 pattern.

ExplanationFlask-SQLAlchemy's db.relationship() defaults to lazy='select' unless told otherwise, and lazy=True is exactly that setting. Under lazy='select', a relationship attribute is populated by its own SELECT statement the first time it is touched on a given instance — it is not fetched alongside the parent object in the original query. So Post.query.all() issues exactly one SELECT that returns all 8 Post rows in a single round trip. The for loop then walks those 8 Post instances; the first time each instance's .comments attribute is read (inside len(...)), SQLAlchemy fires a fresh SELECT * FROM comment WHERE post_id = ? scoped to that instance. Because there are 8 distinct posts, that happens 8 separate times. Adding the initial post query gives 1 + 8 = 9 total queries — the textbook N+1 problem, where N is the number of parent rows returned by the first query. Collapsing this would require an eager-loading strategy: lazy='joined' (or Post.query.options(joinedload(Post.comments)).all()) folds everything into a single JOIN, while lazy='selectin' issues exactly one extra batched query covering every post's comments at once. len() itself does no database work beyond triggering the relationship's first access — it reads a Python list once the relationship has resolved into memory, so it never issues a separate counting query, and the default strategy performs no automatic JOIN rewriting on its own.

Question 198 · Building a Simple Chat Application · hard

A Grade 11 student, Aisha, is building a simple LAN chat application in Python using sockets for her school's computer club, following a client-server model (the server relays messages — it is not a broadcast medium). Aisha's laptop sends a text message of L = 4000 bits to the server over a link with transmission rate R_A = 2 Mbps and propagation delay d_A = 20 ms. The server uses store-and-forward relaying: it waits until the ENTIRE message has arrived before forwarding any of it. There are N = 5 other students currently connected to the chat room, and the server has only ONE physical network interface, so it must push out the 5 outgoing copies of the message one after another (serially) over a link of rate R_S = 1 Mbps; each of the 5 server-to-client links has its own propagation delay of d_S = 10 ms. Ignoring server processing delay and any queuing beyond this serial transmission, how long after Aisha starts sending does the LAST of the 5 students receive the message completely?

  1. 36 ms, since the server relays the message to all five clients simultaneously the instant it finishes receiving it in full.
  2. 52 ms, obtained by adding the store-and-forward delay at the server to five sequential transmission slots on its interface plus one final propagation delay.
  3. 92 ms, obtained by adding a full 10 ms propagation delay for each of the five relayed copies in sequence instead of only for the last one.
  4. 30 ms, obtained by ignoring the time Aisha's message needs to fully arrive at the server before the server can begin relaying it to anyone.

Answer: B. 52 ms, obtained by adding the store-and-forward delay at the server to five sequential transmission slots on its interface plus one final propagation delay.

ExplanationThe message must fully arrive at the server before store-and-forward relaying can begin: this upload leg takes L/R_A + d_A = (4000 bits)/(2×10⁶ bps) + 20 ms = 2 ms + 20 ms = 22 ms. From that instant, the server pushes the 5 outgoing copies onto its single interface one after another (it cannot send them all at once, since they share one physical link). Each copy takes L/R_S = (4000 bits)/(1×10⁶ bps) = 4 ms of transmission time, so the fifth and final copy finishes leaving the server at 22 ms + 5×4 ms = 42 ms. That last copy then travels its own link for d_S = 10 ms, reaching the fifth student at 42 ms + 10 ms = 52 ms. The other four students actually receive their copies earlier — at 36 ms, 40 ms, 44 ms, and 48 ms respectively — because their transmission slots on the server's interface come before the fifth one; only the last recipient determines the overall delivery time. Note that 36 ms is exactly when the FIRST student receives the message (or the time all students would receive it under the mistaken assumption that the server can transmit all 5 copies at once), 92 ms comes from wrongly stacking a propagation delay for every relayed copy instead of only the last, and 30 ms comes from forgetting that the server must fully receive Aisha's message before it can relay anything at all.

Question 199 · Smart Contracts: Programmable Transactions · hard

A Grade 11 student deploys the following Solidity smart contract on a test network to simulate a simple digital wallet: ```solidity pragma solidity ^0.8.19; contract SimpleWallet { mapping(address => uint256) public balance; function deposit() public payable { balance[msg.sender] += msg.value; } function transfer(address to, uint256 amount) public { balance[msg.sender] -= amount; balance[to] += amount; } } ``` Asha deposits 5 ETH, so balance[Asha] equals 5. She then calls transfer(Rahul, 8), trying to send 8 ETH even though her balance is only 5. Given that this contract is compiled with Solidity ^0.8.19, which has automatic overflow and underflow checking built into the compiler, what happens to balance[Asha] and balance[Rahul] once this transaction is processed on the blockchain?

  1. Solidity silently wraps the subtraction (no underflow protection by default), so balance[Asha] jumps to a huge number near 2^256 and balance[Rahul] gains 8.
  2. The transaction reverts entirely because the subtraction underflows; balance[Asha] and balance[Rahul] remain exactly as they were before the call, though Asha still pays gas for the failed attempt.
  3. Solidity clamps the result at zero instead of reverting, so balance[Asha] drops to 0 and balance[Rahul] gains 8.
  4. Execution runs out of instructions after the first line, so balance[Asha] is permanently reduced by 8 while balance[Rahul] never changes.

Answer: B. The transaction reverts entirely because the subtraction underflows; balance[Asha] and balance[Rahul] remain exactly as they were before the call, though Asha still pays gas for the failed attempt.

ExplanationSince Solidity 0.8.0, the compiler automatically inserts overflow and underflow checks into every arithmetic operation, so subtracting 8 from a balance of 5 does not silently wrap around to a huge number the way it could in older compiler versions, and Solidity has no built-in behavior that clamps an underflowing result at zero either. Instead, the check immediately triggers a Panic error and halts execution at that exact line. Because blockchain transactions are atomic, an EVM revert undoes every state change attempted during that call, so the recipient's balance never actually increases even though its update comes after the failing subtraction in the code, meaning nothing is left permanently reduced. Both balances end up exactly as they were before the call was ever sent. What does not get reversed is the gas already spent computing up to the revert point, which is consumed permanently, a key reason sending more than you have still costs the sender something even though the transfer itself never happens.

Question 200 · Database Indexing: Optimize Query Performance · hard

An e-commerce platform stores its order history in a table defined as `Orders(customer_id, order_date, amount)`. To speed up per-customer order lookups, the database administrator creates the following index: ```sql CREATE INDEX idx_cust_date ON Orders(customer_id, order_date); ``` This composite B-tree index physically stores its entries sorted first by `customer_id`, and only within each group of matching `customer_id` values are the entries further sorted by `order_date`. Applying this leftmost-prefix rule of composite indexes, which of the following queries can have both its filter condition and its sort order satisfied directly from `idx_cust_date`, without any additional full-table scan or separate sorting step?

  1. The query `WHERE order_date = '2026-01-15'`, which filters on the index's second column without referencing the first
  2. The query `WHERE customer_id = 501 ORDER BY order_date`, which filters on the leading column and then sorts by the next one
  3. The query `WHERE amount > 500`, which filters on a column that is absent from the index entirely
  4. The query `ORDER BY order_date` with no `WHERE` clause restricting `customer_id` at all

Answer: B. The query `WHERE customer_id = 501 ORDER BY order_date`, which filters on the leading column and then sorts by the next one

ExplanationA composite B-tree index defined as (customer_id, order_date) stores its entries sorted primarily by customer_id, and only within each customer_id group are entries further sorted by order_date. Filtering on customer_id = 501 lets the database seek directly to that one contiguous block of index entries, and because those entries are already arranged by order_date inside the block, the ORDER BY is satisfied for free, with no separate sorting step required. Filtering on order_date alone cannot use the same kind of seek, because rows sharing a given date are scattered across many different customer_id groups instead of sitting together in the index. Filtering on amount gets no benefit at all, since that column was never part of the index definition. Ordering by order_date alone, without first narrowing to one customer_id, also fails to produce a globally sorted result, because order_date is sorted only locally within each customer_id group rather than across the whole index; for instance, a later order placed by a customer with a small customer_id sits earlier in the index than an earlier order placed by a customer with a large customer_id, since customer_id is the primary sort key. This is why the column order chosen when a composite index is created determines exactly which query patterns can actually take advantage of it.
← Set 9Set 11 →