Rain probabilities are 0.5 today, 0.6 tomorrow, and 0.7 for at least one of the two days. Find probability of both.
Your answer
Answer & solution
Answer: D: 0.4 (no official key was published)
Let A and B denote rain today and tomorrow. Inclusion–exclusion gives P(A∪B)=P(A)+P(B)−P(A∩B). Thus P(A∩B)=0.5+0.6−0.7=0.4. This is D. Multiplying 0.5 by 0.6 would assume independence, which is not stated and is inconsistent with the given union probability. The word either is interpreted as inclusive or, as required by the standard union reading.
Apply Newton–Raphson to x²−2=0 starting at−1. Does it converge to−1, +sqrt (2), −sqrt (2), or fail?
Your answer
Answer & solution
Answer: C (no official key was published)
Newton’s update is x_next=x−(x²−2)/(2x)=(x+2/x)/2. From−1 it gives−1.5, then approximately−1.416667. Negative iterates remain negative. Put u=−x>0; then u_next=(u+2/u)/2. After the first step u≥sqrt (2), and this iteration decreases toward sqrt (2), since its only positive fixed point is sqrt (2). Hence the original iterates approach−sqrt (2), C, rather than crossing to the positive root.
Find determinant of the upper-triangular matrix with rows (6, −8, 1, 1), (0, 2, 4, 6), (0, 0, 4, 8), (0, 0, 0, −1).
Your answer
Answer & solution
Answer: B: −48 (no official key was published)
The determinant of an upper-triangular matrix is the product of its diagonal entries. This follows by expanding repeatedly along the first column, whose entries below the diagonal are zero. Here the product is 6·2·4·(−1)=−48. The off-diagonal entries do not affect this determinant, so B is correct. Adding diagonal entries would compute the trace, a different quantity.
Which standard representation permits O(1) concatenation: singly linked, doubly linked, circular doubly linked, or array list?
Your answer
Answer & solution
Answer: C with head-only representations; stored tails also suffice (no official key was published)
A circular doubly linked list exposes its tail as head.prev. For nonempty lists with heads h1, h2 and tails t1, t2, set t1.next=h2, h2.prev=t1, t2.next=h1, h1.prev=t2. Only four links change, so concatenation is O(1), C. Empty-list cases need only pointer assignments. A head-only linear list requires traversal to find its tail, but an explicitly stored tail pointer also makes singly or doubly linked concatenation constant-time. Thus uniqueness of C depends on the usual representation metadata, not merely the link direction.
Match all-pairs shortest paths, quicksort, minimum spanning tree, connected components with dynamic programming, divide-and-conquer, greedy, DFS.
Your answer
Answer & solution
Answer: B: 3, 4, 1, 2 (no official key was published)
Floyd–Warshall solves all-pairs paths through dynamic-programming subproblems. Quicksort partitions around a pivot and recursively sorts subarrays, a divide-and-conquer strategy. Prim or Kruskal builds an MST using safe greedy edge choices. Repeated DFS visits each connected component. Thus the four matches are 3, 4, 1, 2, option B. These refer to standard representative algorithms rather than asserting that each task has only one possible solution paradigm.
Answer: A: ⊕ left, ⊙ right (no official key was published)
In X→X⊕Y, additional⊕ operators are introduced inside the left X. Thus id⊕id⊕id groups as (id⊕id)⊕id. In Y→Z⊙Y, additional⊙ operators occur in the right Y, grouping id⊙id⊙id as id⊙(id⊙id). Therefore⊕ is left associative and⊙ right associative, A. The lower nonterminal level also makes⊙ bind more tightly, but precedence and associativity are distinct properties.
Which structure is essential for efficient infix-to-postfix conversion: operator stack, operand stack, both stacks, or parse tree?
Your answer
Answer & solution
Answer: A (no official key was published)
Operands can be emitted directly to the postfix output. Operators must wait until higher-precedence operators and parenthesized subexpressions are resolved, so a stack stores pending operators and delimiters. When an operator is popped, it is appended to the output. Thus the standard shunting-yard conversion needs an operator stack, A, not an operand-value stack. An operand stack is used later to evaluate postfix, and an explicit parse tree is an alternative representation rather than a requirement of this direct conversion.
A language permits arrays whose sizes are unknown at compile time and requires efficient memory use. Can it be compiled using static allocation, dynamic allocation, or only interpreted?
Your answer
Answer & solution
Answer: C (no official key was published)
The compiler can generate runtime code that evaluates an array’s size, allocates that much storage and records its address and dimensions. Dynamic allocation therefore handles unknown compile-time sizes while avoiding allocation for an arbitrary worst-case bound, giving C. Interpretation is not necessary: compilation can defer particular operations until runtime. Static allocation alone cannot efficiently reserve exactly the required unknown sizes in the general case.
What does conditional expansion in a macro processor do: runtime tests, conditional runtime expansion, recursion, or choosing statements during macro expansion?
Your answer
Answer & solution
Answer: D (no official key was published)
The macro processor evaluates an expansion-time condition, often based on macro arguments or expansion variables, and includes or omits corresponding model statements in the generated text. This occurs while expanding the macro, before the resulting program runs. Therefore D is the matching description. Runtime conditionals instead remain as executable control flow in the expanded program; they do not decide what source text the macro processor generates.
Choose the feature motivating heap allocation: recursion, dynamic data structures, dynamic scope, none.
Your answer
Answer & solution
Answer: B / listed item 2 (no official key was published)
Recursion normally creates nested activation lifetimes, which a stack handles. Dynamic scope concerns name lookup and does not itself force arbitrary object lifetimes. General dynamic structures such as linked nodes may be allocated and released in an order unrelated to calls and returns, so they need storage managed outside a strict activation stack: the heap, item 2. This is the conventional distinction. Particular bounded or region-scoped structures could use specialized pools, so “required” refers to supporting general dynamic lifetimes, not every individual dynamic object.
Define x*y=¬x+y with Boolean OR+. Let z=x*y. Find z*x.
Your answer
Answer & solution
Answer: B: x (no official key was published)
Substitute z=¬x+y. Then z*x=¬z+x=¬(¬x+y)+x. De Morgan gives¬(¬x+y)=x¬y. Finally x¬y+x=x by absorption. Thus B. A truth-table check gives 0 for x=0 and 1 for x=1 regardless of y. The custom star is not ordinary multiplication, so the definition must be substituted before simplifying.
At which 8085 vector address does RST 7.5 start:0000H, 0075H, 003CH, 0034H?
Your answer
Answer & solution
Answer: C: 003CH (no official key was published)
The 8085 vectored restart spacing is eight bytes. The RST 7.5 interrupt vector corresponds to 7.5·8=60 decimal, which is 3C hexadecimal. Thus the routine begins at 003CH, C. Writing 0075H would confuse the interrupt’s label with a hexadecimal address. The related RST 6.5 vector is 0034H, explaining another distractor.
Does an RS232-style start bit synchronize each received byte, a whole byte sequence, provide parity, or synchronize only the last byte?
Your answer
Answer & solution
Answer: A (no official key was published)
Between asynchronous frames the line is idle. The start-bit transition tells the receiver that a new character frame has begun, allowing it to align sampling instants for that frame’s data bits. This resynchronization occurs for each byte, A. It is not a parity check and does not establish one permanent clock phase for an unlimited sequence. Strictly RS232 specifies electrical/interface aspects; the question refers to the familiar asynchronous framing used over that interface.
Match DMA I/O, cache, interrupt I/O, condition-code register with disk, high-speed RAM, printer, ALU.
Your answer
Answer & solution
Answer: B: 2, 1, 3, 4 (no official key was published)
DMA transfers blocks between a device such as a disk and memory without a CPU instruction for every word. Cache uses fast RAM to serve frequently accessed data. A printer is a conventional example of interrupt-driven I/O, while the ALU sets condition flags such as zero, carry or overflow. Thus the mapping is 2, 1, 3, 4, B. Device interfaces may support several transfer methods; these are representative associations rather than exclusive physical capabilities.
An N-bit adder uses 4-bit 74181 ALUs and 4-bit 74182 carry generators, with N divisible by 4. What is best asymptotic addition delay?
Your answer
Answer & solution
Answer: B: proportional to log N (no official key was published)
A four-way carry generator combines propagate/generate information for four lower-level groups. Cascading these in a balanced hierarchy reduces the number of groups by a factor of four per level. Therefore carry information traverses O(log₄ N)=O(log N) levels, followed by constant local sum-generation work. B is the best bounded-fan-in architecture among the choices. A serial chain would take linear time, but is not the best organization; constant delay would require unbounded fan-in or a different physical model.
On all integers define n*m=max (n, m). Is this a monoid, Abelian group, group, or none?
Your answer
Answer & solution
Answer: D (no official key was published)
Maximum is associative, commutative and closed on integers. A monoid additionally needs an identity e satisfying max (e, n)=n for every integer n. That would require e≤n for every integer, but no least integer exists: choose n=e−1 to contradict it. Thus there is no identity and hence no group structure either, giving D. On a set with an added−∞ element, that element would be an identity, but it is not an integer in the stated domain.
Choose a tautology: A(p∨q)→p; Bp∨(q→p); Cp∨(p→q); Dp→(p→q).
Your answer
Answer & solution
Answer: C (no official key was published)
Replace implication by disjunction with a negated antecedent. C becomes p∨¬p∨q, which is always true. A and B both fail at p=false, q=true. D simplifies to¬p∨q and fails at p=true, q=false. Thus C is the only tautology. Showing one falsifying assignment for each other candidate is enough to exclude it, while the excluded-middle pair p∨¬p proves C for all assignments.
Hasse chains are f<e<b<a, f<g<a, f<d<c<a, with no further covers. How many complements does e have?
Your answer
Answer & solution
Answer: B: 3 (no official key was published)
The bottom is f and top is a. A complement z must satisfy e∧z=f and e∨z=a. For each of g, d, c, the only common lower bound with e is f and only common upper bound is a; all three qualify. The remaining elements do not: f has join e, a has meet e, e meets itself at e, and b has meet e. Therefore exactly three complements exist, B. Complements need not be unique in a nondistributive lattice.
Over{a, b}, which is uncountable: all finite strings, all languages, regular languages, or Turing-recognizable languages?
Your answer
Answer & solution
Answer: B (no official key was published)
Finite strings can be enumerated by length and lexicographic order, so Σ* is countably infinite. All languages form its power set P(Σ*), which is uncountable by Cantor’s theorem. In contrast, finite automata and Turing machines each have finite descriptions over a finite alphabet, so there are only countably many of either and hence only countably many languages they describe. Thus B. The distinction is between elements that are strings and arbitrary sets of those strings.
A page reference always repeats the previous page, is likely among recently used pages, always hits resident memory, or always faults.
Your answer
Answer & solution
Answer: B (no official key was published)
Temporal locality is the tendency to reuse recently accessed data or instructions, for example within a loop. Hence the next page reference is likely to be among a recent working set, B. This is a statistical tendency, not an absolute guarantee. A program can move to a new phase and access a different page, and whether that page is resident depends on available memory and replacement history. Thus the three statements containing always are too strong.
Match disk scheduling, batch processing, time sharing, interrupt processing to SCAN, FIFO, round robin, LIFO respectively.
Your answer
Answer & solution
Answer: C: 2, 4, 1, 3 (no official key was published)
SCAN moves the disk head systematically across pending requests. FIFO is the basic batch-job queue discipline. Round robin rotates time slices among runnable processes. Nested interrupts return in reverse order of entry, a LIFO stack behavior. The resulting mapping is 2, 4, 1, 3, C. Actual schedulers may add priorities or other refinements; the question asks for these conventional associations.
Does I/O redirection rename files, allow an existing file to supply program input, necessarily connect two programs by a pipe, or none?
Your answer
Answer & solution
Answer: B (no official key was published)
Redirection changes where a program’s input/output stream is connected. For example, connecting standard input to an existing file lets a program read that file using its usual input operations, which is B. The file need not be renamed. A pipe connects streams between processes and is related but distinct; redirection to a regular file does not require a second program. Therefore C is not a necessary description.
When an interrupt occurs, does the OS ignore it, always block the current process, always resume it, or may it block/schedule another process?
Your answer
Answer & solution
Answer: D in the broad interrupt/trap model (no official key was published)
The handler’s action depends on the event. An ordinary completed-I/O interrupt may simply update device state and return, while a fault or trap requiring an unavailable resource may block the current process and allow another to run. Thus neither always blocking nor always resuming is a general rule. D correctly expresses a possible outcome. This uses interrupt broadly enough to include synchronous traps/faults; a narrow device-only definition would need more careful distinctions about why the interrupted process blocks.
Thrashing reduces page I/O, decreases multiprogramming by definition, implies excessive page I/O, or improves performance?
Your answer
Answer & solution
Answer: C (no official key was published)
Thrashing occurs when processes repeatedly fault because their active working sets do not fit in available frames. The system spends excessive time moving pages rather than executing useful instructions, so C describes it. It increases rather than reduces paging traffic and degrades performance. Reducing the degree of multiprogramming may be a remedy, but is not automatically the meaning or inevitable direct effect of thrashing, so B confuses response with condition.
Does a page dirty bit avoid unnecessary disk writes, record LRU order, enforce read-only access, or none?
Your answer
Answer & solution
Answer: A (no official key was published)
A dirty bit records whether a page has been modified since its backing-store copy was synchronized. On eviction, a clean page can be discarded because an up-to-date copy already exists; a dirty page normally needs writeback. This avoids unnecessary writes for unchanged pages, A. Recent use is tracked by reference/access information or timestamps, while write protection uses permission bits. Those functions should not be confused with modification status.
Find maximum of f (x)=2x²−2x+6 on[0, 2], among 6, 10, 12, 5.5.
Your answer
Answer & solution
Answer: B: 10 (no official key was published)
Differentiate: f′(x)=4x−2 vanishes at x=1/2. Since f″=4>0, this point is a minimum, with value 5.5. The maximum on the closed interval must therefore occur at an endpoint. Evaluate f (0)=6 and f (2)=8−4+6=10. The larger is 10, B. Choosing the stationary value without determining whether it is a maximum would give the wrong distractor.
I12 is obtained by swapping rows 1 and 2 of the identity. What is the first column of AI12 relative to A?
Your answer
Answer & solution
Answer: C: A’s second column (no official key was published)
The first column of I12 is the second standard basis vector e2. Therefore the first column of AI12 is A e2, which is exactly A’s second column. Right multiplication by this permutation matrix swaps columns 1 and 2 of A. Left multiplication would swap rows instead. Thus C. The direction of multiplication is essential; simply recalling that I12 was built by a row swap does not mean its right action swaps rows.
For y″(t)=f (t), the source gives y (0)=0 and asks for the first four forward-Euler y values at step h. Forum prints an extra initial second-derivative condition.
Your answer
Answer & solution
Answer: Underdetermined as printed; intended zero-slope sequence is 0, 0, h²f (0), h²[2f (0)+f (h)] (no official key was published)
Introduce v=y′. Forward Euler gives y[k+1]=y[k]+h v[k] and v[k+1]=v[k]+h f (kh). With v (0)=v0, the four grid values y(0), y(h), y(2h), y(3h) are 0, hv0, 2hv0+h²f (0), 3hv0+2h²f (0)+h²f (h). Thus the missing initial first derivative matters. Setting v0=0 gives the intended sequence near B, but the paper’ B omit the h² factor multiplying f (h).
p (0)=5, p (1)=4, p (2)=9, p (3)=20. Find minimum degree among 1, 2, 3, 4.
Your answer
Answer & solution
Answer: B: 2 (no official key was published)
Successive first differences are−1, 5, 11. Their differences are 6, 6, constant and nonzero, so the data cannot come from a linear polynomial and suggest a quadratic with leading coefficient 6/2=3. Write p (x)=3x²+bx+c. From p (0)=5, get c=5; p (1)=4 gives b=−4. Then p (2)=12−8+5=9 and p (3)=27−12+5=20. The quadratic exists and degree 1 is impossible, so the minimum is 2, B.
A BST contains 1…8. Which preorder is valid:53124786, 53126487, 53241678, 53124768?
Your answer
Answer & solution
Answer: D (no official key was published)
For D, root 5 divides the remaining sequence into left subtree 3, 1, 2, 4 and right subtree 7, 6, 8. In the left subtree, 3 has left subtree 1→right child 2 and right child 4. In the right subtree, 7 has children 6 and 8. This constructs the required BST. A gives 7, 8, 6 after entering root 7’s right subtree before returning to a smaller value 6. B returns to 4 after beginning root 5’s right subtree at 6. C returns to 1 after entering the right subtree of 3 at 4. These violate preorder’s contiguous subtree blocks, leaving D.
T(1)=1 and T(n)=2T(floor (n/2))+sqrt (n) for n≥2. Choose O(sqrt n), O(n), O(log n), none.
Your answer
Answer & solution
Answer: B: Θ(n) (no official key was published)
At recursion depth j there are roughly 2j subproblems of size n/2j. Their combined nonrecursive work is sqrt (n)·2j/2, increasing geometrically toward the leaves. Summing through depth about log 2 n gives O(n), and there are Θ(n) leaves each contributing constant work, providing Ω(n). Hence T(n)=Θ(n), so B. Equivalently the Master theorem has nlog 2 2=n and toll n1/2, which is polynomially smaller; rounding does not change the asymptotic order.
A priority queue is used to implement a LIFO stack. PUSH inserts an item with a chosen integer key; POP deletes the minimum. Should keys be nonincreasing, nondecreasing, strictly increasing, or strictly decreasing?
Your answer
Answer & solution
Answer: D as the sufficient unambiguous scheme (no official key was published)
The newest live item must have the smallest key so it is returned first. Assign successively decreasing keys, for example 0, −1, −2, …; then delete-min exactly follows last-in-first-out order. Strict decrease prevents ties whose unspecified resolution could return an older item. Thus D is the standard sufficient choice. A merely nonincreasing sequence permits equal keys and does not guarantee LIFO without an extra tie rule. Keys need only outrank still-live items, so global decrease is a simple implementation policy rather than the only possible schedule-aware assignment.
A declares x, y. Nested B declares x, z and contains S1; sibling C declares i and contains S2. Which variables are visible?
Your answer
Answer & solution
Answer: C: S1 sees B.x, z, A.y; S2 sees A.x, A.y, C.i (no official key was published)
Lexical lookup searches the enclosing declaration chain. At S1, the local x in B shadows A’s x; B’s z and A’s y are accessible. At S2, procedure C is a sibling of B, not nested inside B, so B’s x and z are inaccessible. C sees its own i and the x, y declared in A. This is option C. The dynamically most recent caller is irrelevant in this Pascal-like lexical-scope question.
For expression prefix (a*b)*c op…where op is+, *, or exponentiation, which operators permit the accumulated product to remain in one register?
Your answer
Answer & solution
Answer: A: + or * under the standard left-to-right accumulator model (no official key was published)
After computing a*b, the single accumulator holds that intermediate value. If op is+or*, ordinary precedence and left associativity allow completing the multiplication by c before moving to the following operation; the accumulator can be reused without spilling a*b. If op is exponentiation, the c-power subexpression binds more tightly and normally must be computed before multiplying by the held a*b, creating a second live intermediate. Thus A in the stated compiler-evaluation model. The omitted suffix and machine instruction set are not fully specified; recomputation or different schedules can change storage requirements, so this is not an architecture-independent impossibility theorem.
Approximate ln7=integral from 1 to 7 of 1/x using uniform trapezoids. Given bound (b−a)h² max|f″|/12, find minimum count guaranteeing error≤10^−4.
Your answer
Answer & solution
Answer: C: 600 by the supplied bound (no official key was published)
For f (x)=1/x, f″(x)=2/x³, whose maximum on[1, 7] is 2. With N trapezoids, h=6/N. The error bound becomes (6/12)·(36/N²)·2=36/N². Requiring 36/N²≤10−4 gives N²≥360000 and N≥600. Thus C is the smallest integer certified by this bound. The actual error can be smaller than the bound; the question asks a guarantee from the supplied estimate, not the smallest empirically sufficient count.
For f (x, y, z)=¬x+¬y·x+xz, which is valid: ¬y·x is prime, xz is a minterm, xz is an implicant, y is prime?
Your answer
Answer & solution
Answer: C (no official key was published)
Step through it (15 steps)
The term xz appears directly in the sum, so whenever xz=1, the function is 1; hence it is an implicant, C. It is not a minterm because it omits y. Simplifying f by absorption gives¬x+¬y+z, so¬y·x can be enlarged to¬y and is not prime. Finally y alone does not imply f: at (x, y, z)=(1, 1, 0), y=1 but f=0. Thus D is false.
Execute MVI A, 55H; MVI C, 25H; ADD C; DAA. Find final A among 7AH, 80H, 50H, 22H.
Your answer
Answer & solution
Answer: B: 80H (no official key was published)
Binary addition first gives 55H+25H=7AH. The low nibble A hexadecimal represents 10, which is invalid as one BCD digit. DAA adds 06H to correct that nibble, producing 80H. The resulting high nibble 8 is valid, so no further 60H correction is required. Thus B. Interpreting the initial bytes as packed decimal 55 and 25 confirms the decimal sum 80; stopping before DAA would incorrectly choose 7AH.
A microinstruction selects none or one of three operations of kind 1, and any subset of six operations of kind 2. Minimum bits among 9, 5, 8, none?
Your answer
Answer & solution
Answer: C: 8 (no official key was published)
The first field has four possibilities: no operation or one of three. It requires log 2 4=2 bits. The six independently selectable operations have 26 possible subsets, including none, so they require 6 bits. Together there are 4·64=256 combinations, requiring 8 bits, which the 2+6 field construction achieves. Thus C. Encoding the second field as one of seven choices would incorrectly forbid simultaneous operations.
Given sqrt ((224)r)=(13)r, find base r among 10, 8, 5, 6.
Your answer
Answer & solution
Answer: C: 5 (no official key was published)
Step through it (6 steps)
Convert the positional numerals to values: (224)r=2r²+2r+4 and (13)r=r+3. Squaring gives 2r²+2r+4=(r+3)²=r²+6r+9. Rearranging yields r²−4r−5=(r−5)(r+1)=0. A valid positive radix containing digit 4 must exceed 4, so r=5, option C. Check 224₅=64 and 13₅=8, whose square is 64.
f=(f1 AND f2) OR f3, with f1 minterms{8, 9, 10}, f2{7, 8, 12, 13, 14, 15}. Forum gives target f={8, 9}; GFG prints{7, 9}. Find f3 among listed choices.
Your answer
Answer & solution
Answer: The printed target is impossible (no official key was published)
The AND term is the intersection of the two minterm sets, namely{8}. Therefore the OR output must include 8 regardless of f3. Of the listed candidates, only{9} qualifies, B. The paper’s target{7, 9} excludes 8 and cannot be produced by this network. This material source disagreement is preserved; the answer is not an official-key match or a silent replacement of the paper’s output.
A poset has elements x, a 1, …, an, y with x≤ai≤y and no other comparisons among the ai. How many extending total orders?
Your answer
Answer & solution
Answer: A: n! (no official key was published)
Every extending order must put x before all ai and y after all ai. The middle n elements are mutually incomparable, so they can occur in any permutation. Each permutation gives one valid total order, and every extension is obtained this way. Thus the count is n!, A. This uses exactly the listed order relations and their reflexive/transitive consequences; additional unmentioned comparisons among the ai would reduce the number.
Vertices 1…100 are adjacent when their difference is 8 or 12. Count connected components among 8, 4, 12, 25.
Your answer
Answer & solution
Answer: B: 4 (no official key was published)
Every allowed difference is divisible by 4, so a path preserves residue modulo 4. There are at least four components. Each residue class contains 25 vertices; after rescaling by 4, its edges connect indices differing by 2 or 3. These 25 indices form a connected graph: all odd indices connect by 2, all even indices connect by 2, and the edge 1–4 of difference 3 joins the two chains. Hence each residue class is one component, proving exactly four, B. The boundary argument is necessary; a gcd observation alone would only prove the lower bound for a finite interval.
How many equivalence relations exist on{1, 2, 3, 4}:15, 16, 24, 4?
Your answer
Answer & solution
Answer: A: 15 (no official key was published)
Equivalence relations correspond exactly to set partitions. Count by block sizes: one block gives 1; type 3+1 gives 4; type 2+2 gives 3; type 2+1+1 gives C(4, 2)=6; four singleton blocks gives 1. Total 1+4+3+6+1=15, option A. This counts unlabeled equivalence classes; multiplying by permutations of the classes would count the same relation repeatedly.
Which regex describes binary strings with no substring 100? Choice D is 0*(10+1)*.
Your answer
Answer & solution
Answer: D (no official key was published)
Any leading run of zeros is harmless and is covered by 0*. After the first 1, there cannot be two consecutive zeros, or the preceding 1 followed by those zeros would form 100. Thus the remaining word can be partitioned into blocks 1 and 10, covered by (1+10)*. Conversely, a word built this way has no pair of zeros after a 1, so it cannot contain 100. Hence 0*(10+1)* is exactly the desired language, D. It includes ε and all-zero strings, which also avoid the forbidden substring.
Choose the undecidable task: bounded-step TM acceptance, TM language equivalence, DFA nonemptiness, CFG nonemptiness.
Your answer
Answer & solution
Answer: B (no official key was published)
Given a step bound k, simulate the TM for at most k steps and answer, so A is decidable. DFA nonemptiness is reachability of an accepting state. CFG nonemptiness is found by marking variables that derive terminal strings until a fixed point. TM language equivalence is undecidable: if decidable, it could compare any TM with one recognizing the empty language and thereby decide TM language emptiness, an undecidable semantic property. Thus B. Bounded simulation differs crucially from unbounded acceptance.
Which language is deterministic context-free: {wcwR:w∈{a, b}*}, unmarked even palindromes over{a, b, c}, {a^n b^n c^n}, or all palindromes over{a, b, c}?
Your answer
Answer & solution
Answer: A (no official key was published)
For A, the symbol c uniquely marks the midpoint because w uses only a, b. A DPDA pushes symbols before c, then deterministically switches to popping and comparing symbols after c, accepting when they match exactly and input ends. Unmarked palindrome languages require finding an unspecified midpoint and are not deterministic context-free over a multi-symbol alphabet. The equal-three-block language is not even context-free. Hence A. The delimiter’s exclusion from w is essential; without it, the same deterministic switch is unavailable.
Similar questions7 more → · asked again: GATE 2014 Set 3, Q31
Resource count excluding deadlock
Deadlocks
Tap to enlarge
Three processes each may require two units of one resource. Minimum units guaranteeing no allocation deadlock among 3, 5, 4, 6?
Your answer
Answer & solution
Answer: C: 4 (no official key was published)
With only three units, each process can hold one and wait for a second, creating deadlock. With four units, if all unfinished processes hold at most one, at least one unit remains available to give some process its second. It can finish and release its units, after which the argument repeats. Therefore four is sufficient and three can fail, so C. This is the standard worst-case incremental-allocation guarantee with eventual completion and no other resources; a restrictive admission policy could safely serialize processes with fewer units.
Nine processes repeat P(mutex);critical section;V(mutex). A tenth replaces its initial P by V. What maximum number can be inside simultaneously?
Your answer
Answer & solution
Answer: D: 10, none of 1, 2, 3 (no official key was published)
The faulty process never consumes a permit when entering and adds permits both before entering and after leaving. With a counting semaphore, it can complete enough loops to accumulate at least nine permits while the others wait to run. Then schedule all nine correct processes through P and pause each inside its critical section. Finally let the faulty process enter too: all ten are inside. Ten is the absolute upper bound because only ten processes exist, so it is attained. Even a saturating binary semaphore can be repeatedly reopened by the faulty process to admit more peers before they leave. Thus D.
R(a, b, c, d) has atomic domains and only FDs a→c, b→d and their consequences. Which normal form applies?
Your answer
Answer & solution
Answer: A: 1NF but not 2NF (no official key was published)
Step through it (4 steps)
Neither a nor b can be derived from the other attributes, so every key must contain both. The closure of ab includes c and d, so ab is the candidate key. Attribute c depends on only a, and d on only b, both proper subsets of that composite key. These are partial dependencies of nonprime attributes, violating 2NF. Atomic domains establish 1NF, so A is correct. The statement that no other independent FDs hold rules out an unstated single-attribute key that would alter this analysis.
S.d references the primary key of R. Which can violate this reference: insert R, insert S, delete R, delete S?
Your answer
Answer & solution
Answer: D: insert S and delete R (no official key was published)
Inserting into S can introduce a nonnull d value absent from R. Deleting a referenced row from R can leave existing S rows without a parent. These are operations 2 and 3, D. Inserting a valid new R row cannot remove an existing reference target; deleting an S row removes a referencing requirement. This concerns the foreign-key constraint specifically, not a separate duplicate-primary-key violation on insertion into R. A DBMS may reject or cascade dangerous operations, but those enforcement policies do not change which raw changes can create a violation.
An 8085 must drive a one-bit output port at I/O address FF hexadecimal through a D flip-flop. The transferred bit is D3, and the output must clear at power-on. Using exactly one ten-input NAND gate, one inverter and one D flip-flop, give the interface circuit. State clock/reset polarities explicitly.
Answer & solution
Answer: D←D3; CLK←NAND(A15,…,A8,IO/M,NOT(/WR)); asynchronous clear from reset; Q is the port output. (no official key was published)
The eight-bit I/O address FFH is all ones. In an 8085 I/O cycle, that address is duplicated on the high address bus A15…A8, so these eight nonmultiplexed lines can be decoded without adding an address latch. Do not use AD7…AD0 directly throughout the write: those pins carry the data during the data phase.
Let /WR denote the active-low write strobe and IO/M=1 denote an I/O cycle. Use the one inverter to form W=NOT(/WR). The ten-input NAND receives A15,A14,…,A8,IO/M,W. Its output is CLK = NOT(A15·A14·…·A8·IO/M·W).
A complete connection list is: 8085 D3 → D input of the flip-flop. A15…A8, IO/M, NOT(/WR) → the ten NAND inputs. NAND output → positive-edge-triggered CLK. RESET OUT → active-high asynchronous CLEAR. Q → the one-bit output. Any asynchronous preset input is tied inactive.
For FFH on an I/O write, CLK goes low while /WR is asserted and rises when that write ends. The positive edge captures D3 while the data is valid. For another port, a memory cycle, or a nonwrite cycle, at least one NAND input is zero and the clock remains high. Asynchronous clearing makes Q=0 during the power-on reset independently of clock activity.
The flip-flop's clear polarity matters. The above netlist chooses an active-high CLEAR so the 8085's active-high RESET OUT connects directly. With an active-low /CLR device instead, connect the same active-low power-on /RESET IN net that resets the CPU to /CLR. Do not connect RESET OUT directly to /CLR and do not silently use a second inverter. The edge and reset assumptions are explicit because the question does not specify a particular flip-flop part. This is an ideal bus-timing design, assuming normal setup/hold timing and no wait-state or reset anomaly.
An 8085 must drive a one-bit output port at I/O address FF hexadecimal through a D flip-flop. The transferred bit is D3, and the output must clear at power-on. Write an 8085 program producing equal ON and OFF intervals of seven bus/machine cycles each.
Answer & solution
Answer: MVI A,00H; LOOP: CMA; OUT FFH; JMP LOOP. Each steady-state half-period is 1+3+3=7 machine cycles. (no official key was published)
Only accumulator bit 3 affects this one-bit port. Complementing the entire accumulator is therefore enough to toggle the output: bit 3 alternates between 0 and 1. One program is
MVI A,00H
LOOP: CMA
OUT FFH
JMP LOOP
CMA takes one machine cycle, OUT takes three, and an unconditional JMP takes three. Between the end of one OUT and the end of the next OUT, the processor executes JMP, CMA and OUT. The total is 3+1+3=7 machine cycles. The same instruction path is used whether D3 is changing from 0 to 1 or from 1 to 0, so both steady-state half-periods are equal. At the FFH output port, values FFH and 00H alternate, but only their D3 bits are stored.
The initialization MVI is outside the loop and does not contribute to repeated periods. Power-on clearing ensures the initial output is low; the interval from reset release to the very first transition need not equal a later half-period. Interrupts and inserted wait states must be absent if exact timing is required.
Here “bus cycles” is interpreted as the 8085 machine-cycle count, not seven clock T-states. The instructions take 4+10+10=24 T-states in a normal execution, so a complete square-wave period is 14 machine cycles, or 48 T-states. Counting instruction bytes or taking “7” as seven T-states would give the wrong timing model.
A singly linked list L=(a1,…,an), n≥0, has nodes with fields next:^list and val:integer. Swap adjacent pairs a_(2i−1),a_(2i), 1≤i≤floor(n/2), by filling the four boxes: 1 function change(p:^list):^list; 2 var q,t:^list; 3 begin 4 if p=nil then change:=p 5 else if p^.next=nil then change:=[B5] 6 else begin 7 q:=p^.next; 8 [B8]:=q; 9 t:=q^.next; 10 [B10]:=p; 11 [B11]:=change(t) 12 end 13 end
Answer & solution
Answer: B5=p; B8=change; B10=q^.next; B11=p^.next. (no official key was published)
The required fillings are line 5: p; line 8: change; line 10: q^.next; line 11: p^.next. With them, the nontrivial branch is
Before the change, the first two nodes and the remaining list have the shape p → q → t. The function must return q as the new head, so line 8 assigns the function result rather than overwriting a next pointer. Save t before reversing q's link; otherwise the remaining list could be lost. Then q^.next:=p reverses the first pair, and p^.next:=change(t) joins its second node to the recursively transformed remainder. The final shape is q → p → change(t).
For an empty list, returning nil preserves it. For a one-node list, returning p preserves the last unpaired node. These are also the induction bases. Assuming the recursive call correctly swaps all pairs in the suffix of length n−2, linking the reversed first pair to that result swaps every required pair in the whole list and preserves every node exactly once.
For example, 1→2→3→4→5 becomes 2→1→4→3→5. The code exchanges nodes through pointers, not merely their stored integer values. It takes Θ(n) time and Θ(n) recursive-stack space, with about floor(n/2) pair-processing calls. Pascal's function-name assignment in line 8 is the mechanism for returning a pointer; it is not another recursive call.
The vertices are the n² integer lattice points (x,y), 1≤x,y≤n, n≥2. Distinct vertices are adjacent when BOTH |x1−x2|≤1 and |y1−y2|≤1; an edge has Euclidean length sqrt((x1−x2)²+(y1−y2)²). This is the GateForum p11 adjacency, including the second-coordinate bound omitted in GFG. Find the minimum spanning-tree weight.
Answer & solution
Answer: n²−1. (no official key was published)
There are n² vertices, so every spanning tree has exactly n²−1 edges. Distinct integer lattice points are at distance at least 1; hence every spanning tree has weight at least n²−1.
This bound is achievable without using any diagonals. In each row, connect its n vertices consecutively with n−1 horizontal unit edges. This uses n(n−1) edges and leaves n connected row paths. Connect consecutive rows by vertical unit edges along the first column, using n−1 more edges. The result is connected and has n(n−1)+(n−1)=n²−1 edges; equivalently, joining the disjoint row trees by a path cannot create a cycle. Its weight is exactly n²−1, matching the lower bound.
For n=2 this construction has three unit edges and weight 3. Using a diagonal would replace a unit edge by one of length √2 and cannot improve the minimum.
For this minimum, however, the same answer remains valid under that literal variant. All distinct vertices are still at least unit distance apart, and the unit-edge construction is still allowed. Thus this particular answer is robust even though the printed graph definitions differ.
The vertices are the n² integer lattice points (x,y), 1≤x,y≤n, n≥2. Distinct vertices are adjacent when BOTH |x1−x2|≤1 and |y1−y2|≤1; an edge has Euclidean length sqrt((x1−x2)²+(y1−y2)²). This is the GateForum p11 adjacency, including the second-coordinate bound omitted in GFG. Find the maximum spanning-tree weight; also distinguish the literal GFG graph that constrains only |x1−x2|≤1.
Answer & solution
Answer: (2n−2)√(1+(n−1)²)+(n−1)+nΣ_(j=2)^(n−1)√(1+max(j−1,n−j)²) (no official key was published)
In the stated king-move grid, every edge is either horizontal/vertical with weight 1 or diagonal with weight √2. We therefore want as many diagonal edges as a spanning tree can contain.
Color vertex (x,y) by the parity of x+y. A diagonal changes both coordinates by one, so it preserves this parity; a horizontal or vertical edge changes it. Both parity classes are nonempty for n≥2. A connected spanning tree must consequently include at least one unit edge to join the two classes. Since it has n²−1 edges in total, its weight is at most (n²−2)√2+1.
To attain the bound, observe that the diagonal-only graph has exactly two connected components, one of each parity. Here is a constructive connectivity argument. Repeatedly use an upward diagonal to reduce y until reaching the first row; at a side boundary choose the inward direction, always possible because n≥2. On the first row, vertices of a fixed parity can move two columns at a time through a vertex of the second row. Thus all vertices of each parity are connected by diagonals. Take a spanning tree inside each diagonal component. Together they use n²−2 diagonal edges. Add any unit edge between the components. This produces a spanning tree attaining the upper bound.
For n=2 the two diagonals, joined by one side, have weight 2√2+1. Under the paper's literal omission of the y-bound, longer edges are allowed when n≥3. Its maximum is instead
Here is a separate optimality proof for that literal graph. Call vertices on y=1 or y=n boundary vertices. For each interior vertex at row j, select an edge to a farthest boundary row in an adjacent column. Such a column always exists for n≥2. Its length is √(1+max(j−1,n−j)²), a maximum edge across the cut isolating that vertex. Add these edges while each interior vertex is still isolated; all chosen parents are boundary vertices, so no cycle arises. By the maximum-spanning-tree cut property, each addition is safe.
Next add all 2n−2 boundary diagonals with |dx|=1 and |dy|=n−1. They are globally maximum edges, each of length √(1+(n−1)²), and form two disjoint alternating-row paths on the 2n boundary vertices. Interior attachments do not join those paths. Finally join them by a same-column edge from y=1 to y=n, of length n−1. Every competing cross-component edge with an interior endpoint is at most √(1+(n−2)²)<n−1 for n≥3. Remaining boundary cross-edges have length at most n−1, so this last edge is also cut-safe. At n=2 there are no interior vertices and the bridge length is 1.
The safe selections form a spanning tree and give the displayed sum: n equal-length interior attachments for each row j, 2n−2 boundary diagonals, and one bridge. Thus both materially different printed graphs have an explicit maximum and a proof, rather than silently restoring a bound.
Consider this pseudo-Pascal program, where z is global: program what; var z:integer; procedure recur(x); begin if x<=40 then begin x:=x+z; recur(x); z:=x+10 end end; begin z:=10; recur(z); writeln(z) end. If x is passed by value, what is printed?
Answer & solution
Answer: 30. (no official key was published)
Step through it (13 steps)
Pass by value gives every call its own local x, but all calls still share the same global z. It is important not to copy z into each activation or to overwrite a caller's x with its child's final x.
On descent, no assignment z:=x+10 has executed yet: it comes after the recursive call. Therefore z stays 10 while the successive calls enter with x=10,20,30,40,50. The calls entering with 10,20,30,40 first update their local x to 20,30,40,50 respectively. The final call enters with x=50; because 50≤40 is false, it immediately returns.
The outer call is last to write the shared global, so writeln(z) prints 30. The temporary value 60 produced by the deepest active body is not the final answer. Also, x=40 does execute its body, because both visual sources show ≤40 rather than <40. The individual marks for this nested leaf are not printed; they are left unknown rather than assigning an invented share of the original group's marks.
Consider this pseudo-Pascal program, where z is global: program what; var z:integer; procedure recur(x); begin if x<=40 then begin x:=x+z; recur(x); z:=x+10 end end; begin z:=10; recur(z); writeln(z) end. If x is passed by value, how many times is recur called, including the call from the main program?
Answer & solution
Answer: 5 total calls, of which 4 are recursive calls. (no official key was published)
Step through it (13 steps)
At every recursive descent, the global z is still 10, since z is assigned only after recur(x) returns. Each active call therefore adds 10 to its own copy of x and invokes the next call. The entry arguments are
The first four entries satisfy x≤40 and execute the recursive-call statement. The last entry, with x=50, fails the test and returns without another call. It is nevertheless an invocation and must be included when counting how many times recur is called. Thus there are five calls in total, four of them made recursively by the procedure itself.
A count of four confuses the number of executed recursive-call statements, or the number of nonbase activations, with the total requested calls. A count based on doubling x would instead be using reference semantics, in which x aliases z; that is not this subpart. The literal ≤ is also essential: a call with argument 40 recurses once more. Original10(a)(ii) is a separate normalized leaf, but neither source prints its own mark allocation, so its marks remain null.
Consider this pseudo-Pascal program, where z is global: program what; var z:integer; procedure recur(x); begin if x<=40 then begin x:=x+z; recur(x); z:=x+10 end end; begin z:=10; recur(z); writeln(z) end. If x is passed by reference, what is printed?
Answer & solution
Answer: 110. (no official key was published)
Step through it (11 steps)
The main program calls recur(z), so its reference parameter x is another name for the global variable z. Passing that reference onward as recur(x) keeps the same alias in every activation. There are not separate saved integer values of x in the suspended calls.
Initially x=z=10. The first body executes x:=x+z, doubling the shared variable to 20. The next call doubles it to 40. Because the guard is x≤40, the call seeing 40 also executes the body and doubles it to 80. The next call sees 80 and returns immediately. Thus four activations exist, three with a pending final assignment.
On unwinding, every z:=x+10 reads the current shared value, because x aliases z. The three pending assignments make the values 80→90→100→110. The program consequently prints 110.
It would be incorrect to use the descent values 10,20,40 as saved local copies during unwinding: that is pass-by-value behavior. It would also be incorrect to stop at 80, since the three assignments following recursive calls still have to execute. The example shows why mutation of a reference argument can interact unexpectedly with a global variable naming the same storage location.
Use the GFG grammar with start symbol S: S → bSe | PQR P → bPc | ε Q → cQd | ε R → dRe | ε. Terminals are b,c,d,e. Generated words are b^i c^j d^k e^m with nonnegative integer exponents. GateForum instead prints S→bSc and mistakenly gives nonpositive exponents; those literal variants must be distinguished. What condition on i,j,k,m characterizes the generated language?
Answer & solution
Answer: i, j, k, m≥0 and i+k=j+m (no official key was published)
Let t be the number of uses of S→bSe before S→PQR. Let p,q,r be the numbers of recursive productions used by P,Q,R. Their contributions are P⇒bp cp, Q⇒cq dq and R⇒dr er. Combining them with the outer b/e pairs gives
i=t+p, j=p+q, k=q+r, m=r+t, where t,p,q,r are nonnegative integers. Adding opposite equations yields the necessary relation i+k=j+m.
To prove sufficiency, assume all four exponents are nonnegative and i+k=j+m. Choose any integer t satisfying max(0,i−j)≤t≤min(i,m), and put p=i−t, q=j−i+t, r=m−t. These parameters are nonnegative and reproduce every exponent, including k=j−i+m. Such a t always exists: i−j≤m follows from k≥0, while i−j≤i follows from j≥0. Thus the equality, together with nonnegativity, is also sufficient.
Its full generated form is bt+pcp+qdq+rer ct, with a trailing block of c symbols after the d/e blocks. For example S⇒bSc⇒bPQRc⇒bcdc is possible, contradicting that the paper's claim that every generated word is in b*c*d*e*. Restricting to words of the claimed block form forces either t=0, or q=r=0 so no d/e lies before the final c. The t=0 case gives i=p,j=p+q,k=q+r,m=r, hence i+k=j+m and j≥i. The other case gives only bi ci, already included in that subset.
Taken literally as string exponents, only zero exponents are meaningful, leaving ε; the language intended by the grammar is not that singleton. This solution uses nonnegative counts, as explicitly printed, and discloses both source differences.
Use the GFG grammar with start symbol S: S → bSe | PQR P → bPc | ε Q → cQd | ε R → dRe | ε. Terminals are b,c,d,e. Generated words are b^i c^j d^k e^m with nonnegative integer exponents. GateForum instead prints S→bSc and mistakenly gives nonpositive exponents; those literal variants must be distinguished. Find a shortest word having two distinct parse trees.
Answer & solution
Answer: bcde (length 4) (no official key was published)
Bcde has two different parses. The difference is whether the initial b and final e are supplied by the outer S rule or by P and R:
Parse 1: S⇒PQR, with P⇒bPc⇒bc, Q⇒ε, R⇒dRe⇒de. Concatenation gives bcde. Parse 2: S⇒bSe⇒bPQRe, with P⇒ε, Q⇒cQd⇒cd, R⇒ε. This also gives bcde.
These are distinct parse trees because the first root uses S→PQR and the second root uses S→bSe. Merely changing the order of independent rewrites would not demonstrate ambiguity; here the production at the root really differs.
To prove shortestness, fix a word's exponents. Every parse is uniquely determined by t, the number of outer S→bSe applications, since p=i−t, q=j−i+t and r=m−t determine the unique chains in P,Q,R. Two parses require two possible t values. If consecutive valid choices are t and t+1, the lower choice has p≥1 and r≥1. Those two recursive chains alone contribute at least two b/c symbols and two d/e symbols, so the total length is at least four. The displayed word attains that bound.
A hash table has n≥1 buckets, uses external chaining, and is initially empty. K distinct keys are inserted. Each key hashes uniformly to one of the n buckets. Under the standard additional assumption that different keys hash independently, find the probability that bucket 1 is empty after K insertions.
Answer & solution
Answer: ((n−1)/n)^K, for independent uniform hashing. (no official key was published)
A single inserted key avoids bucket 1 with probability (n−1)/n=1−1/n. Bucket 1 is empty after K insertions exactly when every one of those K keys avoids it. Under independent hashing, multiply the K probabilities to obtain
P(bucket 1 empty) = (1−1/n)K.
The table may have collisions in other buckets; they do not affect this event. External chaining allows arbitrarily many keys in a bucket, so K need not be at most n. For K=0 the probability is 1, including the n=1 case, by the empty-product convention. For n=1 and K≥1 it is 0, because the only bucket must receive every key. For n=2,K=3 it is (1/2)3=1/8.
The independence qualification is substantive. The source supplies the uniform probability for any individual key, but marginal uniformity alone is not enough to multiply events. For example, choose one uniformly random bucket U and send all keys to U. Every key is marginally uniform, yet bucket 1 remains empty with probability 1−1/n for every K≥1, rather than (1−1/n)K. The displayed answer uses the usual independent-uniform hashing model and is not claimed under that correlated alternative.
A hash table has n≥1 buckets, uses external chaining, and is initially empty. K distinct keys are inserted. Each key hashes uniformly to one of the n buckets. Under the standard additional assumption that different keys hash independently, find the probability that none of the K insertions causes a collision.
Answer & solution
Answer: n! / ((n−K)! n^K) for 0≤K≤n; 0 for K>n. (no official key was published)
After j collision-free insertions, exactly j buckets are occupied. Conditional on that event, the next independently hashed key must choose one of the n−j empty buckets, which has probability (n−j)/n. Multiplying from j=0 through K−1 gives
P(no collision in K insertions) = 1·(n−1)/n·(n−2)/n·…·(n−K+1)/n = n! / ((n−K)! nK), for 0≤K≤n.
For K>n the probability is zero by the pigeonhole principle. Do not extend the factorial formula to a negative factorial. At K=0, the empty product is 1; at K=1, no collision is possible and the result is also 1. For n=3,K=2 it is 2/3, because only the second key can cause the first collision.
An equivalent counting argument considers nK equally likely ordered bucket-choice sequences. Collision-free choices are injective assignments of the K ordered keys to the n buckets, numbering n(n−1)…(n−K+1). The keys are distinct, but that does not make their bucket values distinct automatically.
This derivation needs independent uniform hashing, not just equal marginal bucket probabilities. Under the correlated scheme that sends every key to one common randomly chosen bucket, the probability is already zero at K=2 despite uniform marginals. That source-model limitation is stated explicitly rather than hidden in the multiplication.
A hash table has n≥1 buckets, uses external chaining, and is initially empty. K distinct keys are inserted. Each key hashes uniformly to one of the n buckets. Under the standard additional assumption that different keys hash independently, find the probability that the first collision occurs on insertion K.
Answer & solution
Answer: [n! / ((n−K+1)! n^(K−1))]·(K−1)/n for 2≤K≤n+1; 0 otherwise. (no official key was published)
The event consists of two parts: the first K−1 insertions are collision-free, and the Kth key hits one of their occupied buckets. Given the first part, there are exactly K−1 occupied buckets, so the conditional probability of the second part is (K−1)/n.
For 2≤K≤n+1, the requested probability is therefore
The upper endpoint n+1 is legitimate: the first n keys could fill all n buckets without a collision, after which the next key certainly collides. Its probability is n!/nn. For K=1 the event is impossible because an empty table has no occupied bucket. For K>n+1, a first collision must already have happened, so the probability is also zero.
As a check, write pj for the probability of no collision after j insertions. Then P(first at K)=pK−1−p_K. Summing from K=2 to n+1 telescopes to p1−pn+1=1, as required. For n=2 the probabilities are 1/2 at K=2 and 1/2 at K=3. These arguments all use independent uniform bucket choices; the source's uniform marginals alone do not determine the distribution of the first collision.
Similar questions1 more → · asked again: GATE 1993, Q8.6
Count injections into a larger set
Sets, Relations & Functions
Tap to enlarge
Let F be all one-to-one functions from {1,…,n} to {1,…,m}, where m≥n≥1. How many functions belong to F?
Answer & solution
Answer: m!/(m−n)! = C(m,n)n!. (no official key was published)
Choose the values of the function in domain order. There are m choices for f(1). Once it is chosen, injectivity excludes that value for f(2), leaving m−1 choices. In general f(i) has m−i+1 choices after the preceding i−1 images have been fixed. The multiplication principle gives
|F| = m(m−1)…(m−n+1) = m!/(m−n)!.
Another way is to choose the n-element image set, in C(m,n) ways, then assign its distinct members to the n labelled domain elements, in n! ways. Hence |F|=C(m,n)n!, the same result.
The distinction between a function and an image set matters: C(m,n) alone discards the order in which the n selected values are assigned to 1,…,n. For n=2,m=3, the image set {1,2} supplies both f(1)=1,f(2)=2 and f(1)=2,f(2)=1. There are six injections overall, not three. At n=1 the answer is m, and at m=n it is n!, the number of permutations, providing simple boundary checks.
Let F be all one-to-one functions from {1,…,n} to {1,…,m}, where m≥n≥1. How many f satisfy f(i)=1 for some domain element i?
Answer & solution
Answer: n(m−1)!/(m−n)! = C(m−1,n−1)n!. (no official key was published)
Because f is one-to-one, the codomain value 1 can occur at exactly one domain position if it occurs at all. Choose that position i in n ways. The remaining n−1 domain elements must receive distinct values from the other m−1 codomain values, giving (m−1)!/(m−n)! assignments. Thus the total is
n·(m−1)!/(m−n)!.
There is no double-counting: each satisfying function has a unique preimage of 1, so it appears in exactly one of the n cases. Equivalently, choose its image set to contain 1 and n−1 other values, then order the n image values over the domain. This gives C(m−1,n−1)n!, equal to the first expression.
As a probability check, divide by all m!/(m−n)! injections. The fraction whose image contains a specified codomain value is n/m, consistent with an image set containing n out of m values symmetrically. At n=1 there is only one satisfying function, f(1)=1. At n=m every injection is a bijection, so all n! functions qualify. These checks also show why simply multiplying the total by 1/m would be wrong: any of n domain positions, not a fixed one, may map to 1.
Let F be all one-to-one functions from {1,…,n} to {1,…,m}, where m≥n≥1. GFG asks for f(i)<f(j) for ALL 1≤i<j≤n; GateForum asks for this for SOME pair. Give the count for each printed variant.
Answer & solution
Answer: ALL pairs: C(m,n). SOME pair: m!/(m−n)!−C(m,n). (no official key was published)
Universal condition, f(1)<f(2)<…<f(n). Choose any n distinct codomain values. There is exactly one way to place them in increasing order on the ordered domain. Consequently the number is C(m,n). Choosing the set contributes all the freedom; multiplying by n! would wrongly include orders that violate monotonicity.
Count its complement. Failure means f(i)≥f(j) for every i<j. Since f is injective, equality is impossible, so failure is exactly strict decrease: f(1)>f(2)>…>f(n). For each n-element image set there is one decreasing order, giving C(m,n) failures. Subtracting from all injections gives
m!/(m−n)! − C(m,n).
For n=1, the universal statement is vacuously true and all m functions count; the existential statement has no available pair and counts zero. Both formulas reflect this difference. For n=3,m=3, there is one universally increasing permutation, while five permutations have at least one increasing pair; only 3,2,1 fails the existential condition. For n=2 the two numerical answers happen to coincide, which can conceal the wording discrepancy in small checks.
Both source readings are therefore retained. There is no verified official original or key establishing which quantifier is intended, and neither answer is presented as if it solved the other statement.
Let R be a reflexive and transitive relation on a set A. Define E={(a,b):aRb and bRa}. Prove that E is an equivalence relation.
Answer & solution
Answer: E is reflexive, symmetric and transitive. (no official key was published)
We must check the three equivalence-relation axioms on the same set A.
Reflexivity: for every a∈A, reflexivity of R gives aRa. Both required directions in the definition of E are then the same true statement, so aEa.
Symmetry: if aEb, the definition supplies both aRb and bRa. Reversing their order immediately gives bEa. No symmetry assumption about R is needed; taking its mutual part creates symmetry.
Transitivity: suppose aEb and bEc. Then aRb and bRc, so transitivity of R yields aRc. We also have cRb and bRa, so another use of transitivity gives cRa. Both directions hold, establishing aEc.
Thus E is reflexive, symmetric and transitive, hence an equivalence relation. Its classes group elements that are mutually related by R. In a directed-reachability interpretation, R says one vertex can reach another, and E groups vertices that can reach each other in both directions.
The proof does not claim that R itself is symmetric or antisymmetric. A reflexive, transitive relation is a preorder and may relate distinct elements in both directions. Passing to E-classes is precisely how the companion part removes that possible failure of antisymmetry.
Let R be a reflexive and transitive relation on a set A. Define E={(a,b):aRb and bRa}. For E-classes C,D, define C≤D when there exist a∈C,b∈D with aRb. Prove that this gives a partial order on A/E.
Answer & solution
Answer: The quotient relation is well-defined, reflexive, antisymmetric and transitive. (no official key was published)
First show that the existential definition is independent of representatives. Suppose aRb with a∈C,b∈D. If a′∈C and b′∈D, then a′Ea and bEb′, so a′Ra and bRb′. By transitivity, a′RaRbRb′ gives a′Rb′. Thus one pair of related representatives implies every pair is related; changing representatives cannot change the answer.
Reflexivity: choose a∈C. Since aRa, the defining witness gives C≤C.
Antisymmetry: suppose C≤D and D≤C. Choose any a∈C,b∈D. Representative independence gives aRb from the first relation and bRa from the second. Hence aEb, so a and b have the same E-class and C=D. Antisymmetry is equality of classes, not necessarily equality of their individual representatives.
Transitivity: suppose C≤D and D≤H. Choose a∈C,b∈D,c∈H. Representative independence supplies aRb and bRc; transitivity of R yields aRc. Therefore C≤H.
All partial-order axioms hold. The preliminary representative step is essential when starting from existential witnesses: the witness b from C≤D and the witness b′ from D≤H might be different elements of D. Their E-equivalence supplies bRb′, which connects the two chains. Omitting that link would leave a gap in a direct transitivity proof. No total-order claim follows: two equivalence classes can be incomparable when neither direction of R holds between them.
For positive integers n,m, consider the directly recursive, nonmemoized function function F(n,m:integer):integer; begin if (n<=0) or (m<=0) then F:=1 else F:=F(n-1,m)+F(n,m-1) end. Use C(s,t)=C(s−1,t)+C(s−1,t−1). Find F(n,2).
Answer & solution
Answer: (n+1)(n+2)/2 = C(n+2,2). (no official key was published)
Start with m=1. The recurrence says F(n,1)=F(n−1,1)+F(n,0)=F(n−1,1)+1, and F(0,1)=1. Therefore F(n,1)=n+1.
Now use m=2. We get F(n,2)=F(n−1,2)+F(n,1)=F(n−1,2)+(n+1), with F(0,2)=1. Summing the increments from 1 through n gives
This equals C(n+2,2), anticipating the general binomial formula. A direct induction check also works: the proposed formula for n−1 is n(n+1)/2; adding n+1 gives (n+1)(n+2)/2. The base n=0 gives 1 as required.
For n=1, F(1,2)=F(0,2)+F(1,1)=1+2=3, consistent with the formula. The offset matters: n(n+1)/2 would correspond to a different boundary condition and would incorrectly give 1 when n=1. Both axes in this program have value 1, not 0.
For positive integers n,m, consider the directly recursive, nonmemoized function function F(n,m:integer):integer; begin if (n<=0) or (m<=0) then F:=1 else F:=F(n-1,m)+F(n,m-1) end. Use C(s,t)=C(s−1,t)+C(s−1,t−1). Find F(n,m).
Answer & solution
Answer: C(n+m,n) = C(n+m,m). (no official key was published)
The boundary values are F(0,m)=F(n,0)=1. Compare them with G(n,m)=C(n+m,n): G(0,m)=C(m,0)=1 and G(n,0)=C(n,n)=1, so the axes agree.
Thus G obeys exactly the same recurrence and boundaries as F. Induction on n+m proves equality: each interior value depends only on two smaller sums, so once their equality is established the new value also agrees. Therefore F(n,m)=C(n+m,n)=C(n+m,m).
A useful combinatorial interpretation is the number of lattice paths from (0,0) to (n,m) using n horizontal and m vertical moves. Select which n of the n+m positions are horizontal. On either axis there is only one path, and every interior path arrives from one of its two preceding grid points, explaining both the boundary and recurrence.
The answer is symmetric in n and m, as the function definition requires. At m=2 it specializes to (n+1)(n+2)/2. This formula is the returned value, not the number of function activations; the directly recursive implementation recomputes many identical arguments, which the next subpart counts separately.
For positive integers n,m, consider the directly recursive, nonmemoized function function F(n,m:integer):integer; begin if (n<=0) or (m<=0) then F:=1 else F:=F(n-1,m)+F(n,m-1) end. Use C(s,t)=C(s−1,t)+C(s−1,t−1). How many calls to F occur when evaluating F(n,m), including the original call?
Answer & solution
Answer: 2C(n+m,n)−1. (no official key was published)
The execution forms a full binary recursion tree. Each nonbase call executes exactly two child calls, and each base call has no children. Every base call returns 1, while every internal call returns the sum of its two children's values. The root's return value is consequently the number L of leaf activations. From the recurrence solution, L=F(n,m)=C(n+m,n).
In a full binary tree with I internal nodes and L leaves, the number of edges is 2I because every internal node has two children. It is also I+L−1 because a tree has one fewer edge than nodes. Equating gives I=L−1, so the total number of call activations is I+L=2L−1. Therefore the requested count, including the root call, is
2C(n+m,n)−1.
For n=m=1, the root calls F(0,1) and F(1,0), giving three activations; the formula gives 2·2−1=3. For n=1,m=2 it gives five. If only calls initiated recursively were requested, one would subtract the original root and obtain 2C(n+m,n)−2, but that is not the wording here.
This counts the actual nonmemoized execution tree, including repeated argument pairs as separate calls. Counting only distinct states, or assuming a dynamic-programming implementation, would answer a different complexity question.
A size-balanced binary tree has, at every node, left and right subtree sizes differing by at most one. Node distance is the number of edges from the root, and tree height h is the greatest root-to-leaf distance. Prove by induction on h that a tree of height h has at least 2^h nodes.
Answer & solution
Answer: Every such tree has N≥2^h; the bound is attainable. (no official key was published)
Use induction on the nonnegative height h. For h=0 the tree consists of the root, so N=1=20.
For h≥1, at least one child subtree has height h−1; otherwise no root-to-leaf path could have length h. Call that subtree T and let its size be s. By the induction hypothesis, s≥2h−1. The other child subtree has size t≥s−1, because the defining balance condition bounds the size difference by one. Empty subtrees are allowed and have size zero, so this also handles h=1.
Counting the root gives
N=1+s+t ≥1+s+(s−1)=2s ≥2h.
This proves the assertion. We did not assume the two subtrees have equal height or that every level is full. Size balance is a statement about node counts, and the proof uses exactly that statement.
The bound is sharp. For h≥1, combine a minimum-size tree of height h−1, with 2h−1 nodes, and a perfect tree of height h−2, with 2h−1−1 nodes, below a new root. Their sizes differ by one and their subtrees satisfy the same condition. The total is 2h and the height is h. At h=1 the smaller subtree is empty. This construction also explains why the stronger bound 2h+1−1 would be false: a size-balanced tree need not be perfect at its last level.
A size-balanced binary tree has, at every node, left and right subtree sizes differing by at most one. Node distance is the number of edges from the root, and tree height h is the greatest root-to-leaf distance. For h≥1, how many nodes are at distance h−1 from the root?
Answer & solution
Answer: Exactly 2^(h−1). (no official key was published)
The level at distance h−1 is full, so it contains 2h−1 nodes. To justify fullness rather than assume it, first use the proved size bound: a size-balanced tree of height h has N≥2h nodes.
For any node whose subtree has s nodes, its child sizes sum to s−1 and differ by at most one. Hence each child has at least floor((s−1)/2) nodes. Starting from N≥2h, induction on depth shows that every node at depth d≤h−1 has subtree size at least 2h−d−1. Indeed, a parent lower bound 2h−d−1 gives each child at least 2h−d−1−1.
In particular, at every depth d<h−1 this lower bound is at least 3. Such a subtree has both children nonempty. Beginning with one root, the node count therefore doubles at each step until depth h−1, giving exactly 2h−1 nodes there. The last level h may be only partly occupied, so this does not assert that the entire tree is perfect.
For h=1 the requested level is the root itself and the formula gives 1. For h=2 a smallest example has four nodes: its depth-1 level still has both children, while only one node need occur at depth 2. The paper explicitly states h≥1.
An array A[1..n], n≥1, contains positive integers, and M>0. Complete the boxes in this program so it prints the shortest nonempty contiguous-subarray length having sum at least M, or n+1 if none exists. The program uses one-based array indexing: 1 begin 2 i:=1; j:=1; 3 sum:=[B3]; 4 min:=n; finish:=false; 5 while not finish do 6 if [B6] then 7 if j=n then finish:=true 8 else 9 begin 10 j:=j+1; 11 sum:=[B11] 12 end 13 else 14 begin 15 if (j-i)<min then min:=j-i; 16 sum:=sum-A[i]; 17 i:=i+1 18 end; 19 writeln(min+1) 20 end
Answer & solution
Answer: B3=A[1]; B6=sum<M; B11=sum+A[j]. (no official key was published)
Fill line 3 with A[1], line 6 with sum<M, and line 11 with sum+A[j]. The invariant is that sum equals A[i]+…+A[j], with value zero if the current window is empty (i=j+1).
Initially i=j=1, so sum must be A[1]. If sum<M, the current window is too small. Removing positive elements cannot help it reach M, so extend the right endpoint. Line 10 has already incremented j, which is why line 11 adds A[j], not A[j+1]. If j=n, there is no further element to add and the loop can terminate.
If sum≥M, the current window is feasible. Its actual length is j−i+1, but min deliberately stores length minus one, so line 15 compares j−i. Remove A[i] and advance i to look for a shorter feasible window with the same right endpoint. Repeated shrinking examines the best ending-at-j choice before extending again. Positivity ensures that once a left endpoint is discarded, retaining it for later right endpoints cannot improve on a feasible length already considered.
For A=[2,3,1,2] and M=5, the first feasible window is [2,3], length 2. It stores min=1. After shrinking and extending, [3,1,2] is feasible but longer. The final print is 2. If no window reaches M, min stays n and the sentinel print is n+1. If one element alone reaches M, min becomes 0 and the answer is 1; removing that element creates a temporary empty window of sum zero, which safely forces extension or termination because M>0.
Both i and j only increase, giving O(n) time and O(1) auxiliary space. Negative array elements would invalidate the monotonic shrinking argument. The strict comparison at line 6 is essential: equality sum=M already satisfies the requested threshold. Full code and its statement numbering are reconstructed from the paper pp8–9, where the boxes and assignments remain visible.
The following C-like code removes duplicate values from a sorted singly linked list. Node has int val and Node *next. Assume the input is acyclic and contains n≥2 nodes; j points to a separate valid integer. Pointer-member syntax is normalized from the reproduced typesetting. Node *remove_duplicates(Node *head,int *j) { Node *t1,*t2; *j=0; t1=head; if(t1!=NULL) t2=t1->next; else return head; *j=1; if(t2==NULL) return head; while(t2!=NULL) { if(t1->val!=t2->val) { /* S1 */ (*j)++; t1->next=t2; t1=t2; /* S2 */ } t2=t2->next; } t1->next=NULL; return head; } How many times is the comparison S1 evaluated?
Answer & solution
Answer: n−1. (no official key was published)
The first input node is taken as the initial retained node t1. Before the loop, t2 is set to the second input node. The loop then advances t2 exactly once through every remaining original node, stopping at NULL. Since there are n−1 nodes after the first, S1 is evaluated exactly n−1 times.
Rewiring t1->next inside S2 does not skip any as-yet unvisited node. When S2 executes, t1 is moved to the current t2, but that current node's own next pointer has not been changed. The subsequent t2=t2->next therefore advances to its original successor. When S2 does not execute, t1 remains the retained node and the same successor step still happens. Thus all-equal and all-distinct lists perform the same number of value comparisons.
For example, on [1,1,2,2], S1 compares the second 1, first 2, and second 2 against the current retained value, for three comparisons. The while-condition test is a different comparison and is not included in this count.
This leaf uses the full shared stem and belongs to that single group; it is not evidence for an extra exam question. The displayed code restores legal pointer-member notation while retaining its algorithmic operations.
The following C-like code removes duplicate values from a sorted singly linked list. Node has int val and Node *next. Assume the input is acyclic and contains n≥2 nodes; j points to a separate valid integer. Pointer-member syntax is normalized from the reproduced typesetting. Node *remove_duplicates(Node *head,int *j) { Node *t1,*t2; *j=0; t1=head; if(t1!=NULL) t2=t1->next; else return head; *j=1; if(t2==NULL) return head; while(t2!=NULL) { if(t1->val!=t2->val) { /* S1 */ (*j)++; t1->next=t2; t1=t2; /* S2 */ } t2=t2->next; } t1->next=NULL; return head; } What are the minimum and maximum numbers of executions of the block S2?
Answer & solution
Answer: Minimum 0; maximum n−1. For d distinct values, the block runs d−1 times. (no official key was published)
The list is sorted, so equal values occur in contiguous runs. The first run's first node is retained before the loop begins. Thereafter S2 executes precisely when t2 reaches the first node of a new value run, because its value differs from that in the last retained node t1.
If the input has d distinct values, there are d runs and exactly d−1 transitions to new runs. Thus the S2 block, and each of its three statements, executes d−1 times. Since 1≤d≤n for a nonempty list, the minimum is 0 and the maximum is n−1.
The minimum occurs when all n values are equal: every comparison S1 is false, t1 stays at the first node, and the final t1->next=NULL detaches all duplicate nodes from the returned chain. The maximum occurs when all n values are distinct: every one of the n−1 loop iterations takes S2, retains the current node and advances t1.
For [1,1,2,2,3], d=3 and S2 runs twice, once on the first 2 and once on the first 3. It does not run once per duplicate removed. This distinction prevents reversing the extremes: an all-equal list removes the most duplicate links but executes S2 the fewest times. The final NULL assignment is outside S2 and is not counted as one of these block executions.
The following C-like code removes duplicate values from a sorted singly linked list. Node has int val and Node *next. Assume the input is acyclic and contains n≥2 nodes; j points to a separate valid integer. Pointer-member syntax is normalized from the reproduced typesetting. Node *remove_duplicates(Node *head,int *j) { Node *t1,*t2; *j=0; t1=head; if(t1!=NULL) t2=t1->next; else return head; *j=1; if(t2==NULL) return head; while(t2!=NULL) { if(t1->val!=t2->val) { /* S1 */ (*j)++; t1->next=t2; t1=t2; /* S2 */ } t2=t2->next; } t1->next=NULL; return head; } What does the integer *j contain when the function completes?
Answer & solution
Answer: The number of distinct input values, equal to the number of nodes in the returned deduplicated list. (no official key was published)
For a nonempty list, the code explicitly sets *j=1 before entering the loop. This counts the first retained value. Every later S2 execution marks the first encounter with a new value and increments *j once. Since sorted order puts equal values together, no later run repeats an earlier value.
If there are d distinct input values, S2 executes d−1 times and the final value is 1+(d−1)=d. The returned chain contains exactly one representative of each run, so d is also its number of nodes. For [2,2,5,5,5,9], the initialization counts 2, and the two increments count 5 and 9, giving *j=3. The number of removed duplicate nodes is n−*j, not *j itself.
The early cases are consistent even though this question assumes n≥2. An empty list returns with *j=0; a one-node list returns with *j=1. The *j=1 assignment after the empty-list check is therefore essential to interpreting the result. Omitting it would incorrectly leave the counter at d−1.
The function changes links but does not free detached nodes. Its logical output is deduplicated, but claiming that it releases their memory would go beyond the code. Sortedness is also essential for “distinct values”: on an unsorted list such as [1,2,1], the code would count three runs rather than two globally distinct values. This explanation applies to the ordered-list precondition actually given.
In this question a B+-tree of order d has d to 2d key entries in each nonroot internal node, and an internal node with M keys has M+1 children. An internal root has 1 to 2d keys. All leaves are at equal edge-distance h from the root. Use this stated convention, not the alternative convention that “order” means maximum fan-out. With ℓ≥2 leaves, how many key entries are stored across all internal nodes?
Answer & solution
Answer: ℓ−1 internal key entries. (no official key was published)
Let I be the number of internal nodes and let kv be the number of key entries in internal node v. That node has kv+1 children, so summing all internal-node child counts counts every tree edge exactly once:
Σ_internal v (kv+1) = number of edges.
The whole tree has I+ℓ nodes and is connected and acyclic, so it has I+ℓ−1 edges. Therefore
Σ kv + I = I+ℓ−1, and hence Σ kv = ℓ−1.
This argument includes the root, whose minimum occupancy differs from other internal nodes. It does not depend on the height, branching distribution, or order d, only on the fact that every internal node has one more child than key entries.
For a root with three leaf children, there are two root keys and ℓ−1=2. If an internal node with five leaf children is inserted one level lower, its four keys and the necessary separator keys above it still obey the same identity. The result counts stored separator entries in internal nodes; it is not the number of data records in the leaves, nor a claim about the number of distinct values across the entire B+-tree. Leaf keys can have different occupancy conventions without affecting this edge-count identity.
In this question a B+-tree of order d has d to 2d key entries in each nonroot internal node, and an internal node with M keys has M+1 children. An internal root has 1 to 2d keys. All leaves are at equal edge-distance h from the root. Use this stated convention, not the alternative convention that “order” means maximum fan-out. For d=4 and exactly 52 leaves, find the maximum number of internal nodes.
Answer & solution
Answer: 13 internal nodes, attainable at height 3. (no official key was published)
With 52 leaves, the total number of internal key entries is 52−1=51. If there are I internal nodes, the root uses at least one key and every other internal node uses at least d=4. Hence
1+4(I−1)≤51, so 4I≤54 and I≤13.
An upper bound alone is not enough: equal leaf depth might prevent attaining it. Here it is attainable. Build a height-3 tree as follows: Depth 0: one root with two children (one key). Depth 1: two internal nodes, each with five children (four keys each). Depth 2: ten internal nodes. Give eight of them five leaf children and two of them six leaf children. Depth 3: 8·5+2·6=52 leaves.
Every nonroot internal node has five or six children, within the permitted five-to-nine range for d=4. All leaves are at depth three. The internal-node count is 1+2+10=13, and their key total is 1+8+8·4+2·5=51, confirming the arithmetic.
Thus 13 is both an upper bound and an achievable maximum. Treating order 4 as a maximum of four children would use a different B+-tree definition and give a wrong result for the convention explicitly supplied in this paper.
In this question a B+-tree of order d has d to 2d key entries in each nonroot internal node, and an internal node with M keys has M+1 children. An internal root has 1 to 2d keys. All leaves are at equal edge-distance h from the root. Use this stated convention, not the alternative convention that “order” means maximum fan-out. For h≥1, find the minimum number of leaves.
Answer & solution
Answer: 2(d+1)^(h−1). (no official key was published)
Since h≥1, the root is internal. Its minimum one key gives a minimum of two children. Every other internal node has at least d keys, hence at least d+1 children.
At depth 1 there are therefore at least 2 nodes. At depth 2 there are at least 2(d+1), and continuing to the leaf level h gives
minimum leaves = 2(d+1)h−1.
The exponent is h−1 because the first branching step is performed by the root, with minimum fan-out two; the remaining h−1 steps have minimum fan-out d+1. Multiplying by d rather than d+1 would confuse the minimum number of keys with the number of child pointers.
The bound is attainable: give the root exactly two children and every other internal node exactly d+1 children, stopping with leaves at depth h. All nonroot internal nodes then have exactly d keys, the root has exactly one, and every leaf lies at the required common depth. For h=1 the tree is a root with two leaf children, and the formula gives 2. For d=4,h=3 it gives 2·5²=50 leaves, consistent with the 52-leaf construction in the companion part. A tree of height zero is outside this subpart and would instead consist of a single leaf.
Construct a finite-state machine with the minimum number of states accepting exactly the strings over {a,b} whose number of a symbols is divisible by 2 and number of b symbols is divisible by 3.
Answer & solution
Answer: Six-state DFA tracking (#a mod 2, #b mod 3); start and only accepting state q00. (no official key was published)
Step through it (2 parts)
The future acceptance of a prefix depends on two remainders, not on the order of its symbols. Let qij mean that the prefix contains i a's modulo 2 and j b's modulo 3. Use Q={q00,q01,q02,q10,q11,q12}; start at q00 and make only q00 accepting. An a toggles i, while a b advances j modulo 3.
State on a on b Accepting?
q00 q10 q01 yes
q01 q11 q02 no
q02 q12 q00 no
q10 q00 q11 no
q11 q01 q12 no
q12 q02 q10 no
This table completely specifies the machine and can be drawn as two three-state b-cycles with paired a-transitions between them. By induction on input length, its state is always the pair of remainders claimed above. Therefore it accepts exactly the required strings, including the empty string because zero is divisible by both divisors.
To prove minimum size, first note that every qij is reachable by ai bj. Next take any distinct qij and qkl. Append the suffix a^((-i) mod 2)b^((-j) mod 3). From qij this reaches q00 and accepts. From qkl it reaches the nonzero remainder pair ((k−i) mod 2,(l−j) mod 3), so it rejects. Every pair of states is thus distinguishable by a common suffix. The six distinct residual languages require at least six DFA states; our six-state construction meets this lower bound. Merely multiplying 2 by 3 would suggest the answer but would not, without distinguishability, prove minimality.
A language L is accepted by a finite-state machine. Prove that finite-state machines also accept L′={s: ss′∈L for some string s′} and Lᴿ={s: s is the reversal of some string in L}.
Answer & solution
Answer: For prefixes, accept all states that can reach an old final state. For reversal, reverse edges and exchange starts/finals using an ε-NFA. (no official key was published)
Begin with a DFA M=(Q,Σ,δ,q0,F) for L. This loses no generality because any finite-state recognizer can be determinized. The two constructions solve different problems: L′ consists of prefixes that can still be completed to an accepted word; Lᴿ reverses complete accepted words.
Prefix construction: compute C={q∈Q: δ*(q,t)∈F for some t∈Σ*}. These are exactly the states from which some accepting state is reachable, found by a reverse graph search starting at F. Keep Q,Σ,δ,q0 unchanged and replace the accepting set F by C. The new machine accepts s precisely when δ*(q0,s) belongs to C, which is equivalent to the existence of t with δ*(q0,st)∈F. That is exactly s∈L′. No new states are needed. If L is nonempty, q0∈C and ε is a prefix; if L is empty, C is empty and no word is accepted.
Reversal construction: retain all old states and reverse every labeled transition. For each δ(p,a)=q, add an a-transition q→p. Introduce a fresh start state r with ε-transitions to every f∈F, and make q0 the sole final state. The result is generally nondeterministic because reversing edges can create several transitions with the same label. A path q0 --a1...an--> f in the old machine becomes f --an...a1--> q0 in the new one, and the converse follows by reversing the path again. Thus exactly the reversed words are accepted. If a DFA is required, apply ε-closure and subset construction. Simply exchanging start/final states without reversing edges, or reversing edges while insisting on a single old final as start, would not establish closure for arbitrary L.
A language L is a subset of Pascal with expressions using only + and <, assignment statements, while statements, and compound statements begin ... end. Give an unambiguous grammar. The source does not specify lexical details, empty statements, or a trailing-semicolon convention.
Answer & solution
Answer: Use separate addition/comparison levels, one comparison per expression, and explicit statement/block productions. (no official key was published)
Here is one unambiguous grammar under the conventional choices that + binds more tightly than <, + associates to the left, and < is nonassociative. The lexer supplies tokens id and num; reserved words are distinct tokens, and := is assignment. Start symbol S denotes one statement.
S → id := E | while E do S | begin L end L → S R R → ; S R | ε E → A | A < A A → A + P | P P → id | num | ( E )
The grammar deliberately uses nonempty compound statements with semicolons between statements, not after the last one. If empty blocks are required, add the separate production S→begin end. If an optional trailing semicolon is required, replace R by R→ε | ; T and T→ε | S R. These are explicit syntax extensions, not facts supplied by the question.
The expression hierarchy enforces a unique outer operator structure. An unparenthesized < must be the single comparison at the E level, so a+b<c+d parses as (a+b)<(c+d), and a<b<c is rejected unless parentheses explicitly group a comparison. Left recursion at A gives (a+b)+c, not a+(b+c). Parentheses delimit a complete nested expression. At statement level, id, while and begin select disjoint alternatives. The keyword do separates a while condition from its body; matching begin/end delimit a compound body, and semicolons separate its statements. There is no if/else construct and hence no dangling-else ambiguity.
For example, while x<y+1 do begin x:=x+1; y:=y+2 end has a unique parse: its loop body is the entire block, containing two assignments. Static type rules, such as requiring a Boolean while condition and compatible assignment types, belong to semantic analysis rather than this context-free grammar. The source does not uniquely determine every optional Pascal syntax feature; the stated conventions make this proposed grammar precise.
The grammar is assign-stmt→LHS := E; E→E+T | T; T→T*V | V; V→id | (E); LHS→id. Variables have integer or real types. Convert expressions and assignments to postfix using typed tokens (+,i), (+,r), (*,i), (*,r), (:=,i), (:=,r). give-type(id) and give-name(id) return an identifier's type and name. Give a syntax-directed translation scheme. Mixed-type conversion and narrowing policies are not stated in the source.
Answer & solution
Answer: Synthesize type and postfix code; choose numeric promotion for each operator, emit left operand then right operand then typed operator, and check assignment compatibility. (no official key was published)
Use synthesized attributes X.type and X.code for E,T,V; use LHS.type and LHS.name for the assignment target. A code value is a token list, and || denotes concatenation. Identifier type is i or r. The following semantic actions specify the traversal without depending on a particular parser implementation.
For E→E1+T, let t=join(E1.type,T.type), where join(i,i)=i and every other numeric pair gives r. Set E.type=t and E.code=E1.code || T.code || [(+,t)]. For T→T1*V, set t=join(T1.type,V.type), T.type=t and T.code=T1.code || V.code || [(*,t)]. Subscripting E1 and T1 distinguishes the right-hand-side occurrence from the left-hand-side occurrence of the same nonterminal.
For assign-stmt→LHS:=E, check that the expression can be assigned to the destination. Emit [address(LHS.name)] || E.code || [(:=,LHS.type)]. Writing the LHS first follows the conventional postfix assignment form x y (:=,i); the assignment operator consumes the target address and the computed value. In a textual postfix language the name in that first position can denote its address implicitly.
A necessary semantic convention: with precisely the six listed typed operator tokens, the r arithmetic operators must accept integer operands by implicit widening, and (:=,r) must widen an integer value when needed. Under that convention the rules above handle mixed expressions. For integer x,y and real z, the translation of z:=x+y*z is z x y z (*,r) (+,r) (:=,r). Multiplication is emitted first, preserving the grammar's precedence. A real-to-integer assignment is rejected unless an explicit narrowing rule has been authorized.
If the target instead requires both operands already to have the operator's physical type, implicit widening is unavailable. Then replace operand code c by c||[i2r] whenever its integer result is consumed as real, and similarly before assignment to a real target. This alternative introduces an extra conversion token not supplied in the question. Homogeneous expressions need no such extension. Type tags alone do not define a real-to-integer rounding rule or a machine-level cast. Keeping these conventions explicit avoids silently inventing conversion behavior while still giving a complete translation scheme for the stated operator alphabet.
Consider this Pascal nesting and call structure, with no calls other than those shown. Main declares X; A, nested in Main, declares Y; B, nested in A, declares Z; C, nested in B, also declares Z. Main calls A; A calls B; B calls C and, after C returns, calls A. C contains no procedure calls. At an instant there are five activation records on the runtime stack. Show its top, static and dynamic links, and local variables. Source skeleton: program Main; var X: integer; procedure A; var Y: integer; procedure B; var Z: integer; procedure C; var Z: integer; begin {no procedure calls} end; begin C; A end; begin B end; begin A end. Ellipses in the source allow other non-call work; the skeleton preserves every shown declaration and call.
Answer & solution
Answer: Bottom to top: Main, A1, B1, A2, B2. Dynamic links follow the call chain; static links B2→A2, A2→Main, B1→A1, A1→Main. (no official key was published)
Distinguish a procedure's lexical parent from the activation that calls it. The dynamic link records the caller; the static link records the active instance of the enclosing lexical scope. Calls to A from inside B are recursive calls to a procedure declared directly inside Main, not declarations of a new A inside B.
Trace the shown calls. Main calls A1, which calls B1. B1's call to C1 creates only the fourth record, and C1 makes no further calls. C1 returns before the following call to A2, so its record has been removed. A2 is then the fourth record, and its call to B2 creates the fifth. At any matching five-record stage of this call pattern, the active chain is therefore:
Stack position Activation Local slot Dynamic link Static link
TOP B2 B2.Z A2 A2
A2 A2.Y B1 Main
B1 B1.Z A1 A1
A1 A1.Y Main Main
BOTTOM Main Main.X null null
Other ordinary record fields, such as a return address and saved registers, may exist but are not assigned values by the problem. A1.Y and A2.Y are distinct storage cells, as are B1.Z and B2.Z. No numeric values for X,Y,Z can be recovered from the ellipses. The completed C1 record, including its separate C1.Z slot, is absent.
The dynamic chain is B2→A2→B1→A1→Main. The different static chain from B2 is B2→A2→Main. In particular, A2's static link must not point to B1 merely because B1 called it. To create A2, B1 can follow its own static chain B1→A1→Main to find A's lexical parent. This is the central distinction the example tests.
The Mealy state table gives (next state,output) for inputs 0 and 1: A: 0→(B,1), 1→(H,1) B: 0→(F,1), 1→(D,1) C: 0→(D,0), 1→(E,1) D: 0→(C,0), 1→(F,1) E: 0→(D,1), 1→(C,1) F: 0→(C,1), 1→(C,1) G: 0→(C,1), 1→(D,1) H: 0→(C,0), 1→(A,1). No initial state is specified. Find the equivalence partition of its states.
Answer & solution
Answer: {A}, {B}, {C,D}, {E,F,G}, {H}. (no official key was published)
Two Mealy states are equivalent if every finite input string produces the same output string from either state. In particular they must first agree on their immediate output for each input. The output pairs are (1,1) for A,B,E,F,G and (0,1) for C,D,H. This gives the initial partition P0={ABEFG,CDH}.
Refine each block according to the blocks reached on inputs 0 and 1, while retaining the output test. In P0, A and B lead respectively to blocks (ABEFG,CDH); E,F,G lead to (CDH,CDH); and C,D,H lead to (CDH,ABEFG). Hence P1={AB,EFG,CDH}.
Now use P1 to distinguish formerly similar successor states. A reaches (AB,CDH), whereas B reaches (EFG,CDH), splitting A from B. C and D both reach (CDH,EFG), whereas H reaches (CDH,AB), splitting H from CD. The states E,F,G still both transition into CDH. Thus P2={A,B,CD,EFG,H}.
Check stability: C and D have equal outputs and both go into CD on 0 and EFG on 1. Each of E,F,G has output 1 on both inputs and goes into CD on both inputs. No further split is needed. The singleton blocks trivially satisfy stability, so P2 is the equivalence partition.
Refinement never separates equivalent states: a split witnesses a finite input on which outputs eventually differ. For example, A and B are distinguished by 000, producing 111 and 110 respectively; H and C are distinguished by 100, producing 111 and 110. Conversely, a stable equal-output partition guarantees equal output sequences by induction on input length. This proves both directions, rather than guessing equivalent states from one-step transitions alone.
The Mealy state table gives (next state,output) for inputs 0 and 1: A: 0→(B,1), 1→(H,1) B: 0→(F,1), 1→(D,1) C: 0→(D,0), 1→(E,1) D: 0→(C,0), 1→(F,1) E: 0→(D,1), 1→(C,1) F: 0→(C,1), 1→(C,1) G: 0→(C,1), 1→(D,1) H: 0→(C,0), 1→(A,1). No initial state is specified. Give the minimal equivalent state table, naming merged states by their members.
Answer & solution
Answer: Five quotient states A,B,CD,EFG,H with the transition/output table below. (no official key was published)
The equivalence blocks are {A},{B},{C,D},{E,F,G},{H}. Replace every original destination by its block name, keeping the original output. The reduced table is:
Present state input 0: next/output input 1: next/output
A B/1 H/1
B EFG/1 CD/1
CD CD/0 EFG/1
EFG CD/1 CD/1
H CD/0 A/1
For example, C goes to D/0 and E/1, whereas D goes to C/0 and F/1. Once C,D are both named CD and E,F,G are all named EFG, those two rows become identical. Similarly, E,F,G all reduce to the row CD/1, CD/1. Therefore the choice of a representative inside a merged block does not affect the quotient table.
Why is this minimal rather than merely smaller? Output-based refinement begins with {ABEFG,CDH}, refines to {AB,EFG,CDH}, and then to the five displayed blocks, which are stable. Distinct resulting blocks have some finite distinguishing input, so no further merger preserves all output behavior. Five states are necessary to represent the behavior of all states in the given table.
No start state is printed, so the table does not justify inventing one or removing states as unreachable from it. This is minimization of the supplied machine's state behaviors. If a separate initial-state specification were supplied, one would additionally check reachability before reporting the size of a recognizer from that particular start. The table remains a Mealy table: outputs label transitions, not states, and a Moore-machine reinterpretation would be a different problem.
f=(¬w+y)(¬x+y)(w+¬x+z)(¬w+z)(¬x+z), where + is Boolean OR, juxtaposition is AND, and ¬ is complement. Express f in minimal sum-of-products form. The source requests only the answer; the derivation is included for learning.
Answer & solution
Answer: f=¬w¬x+yz. (no official key was published)
Group the two factors sharing ¬w and the two sharing ¬x. The Boolean identity (a+b)(a+c)=a+bc gives (¬w+y)(¬w+z)=¬w+yz, (¬x+y)(¬x+z)=¬x+yz. Applying the same identity with the common term yz gives (¬w+yz)(¬x+yz)=¬w¬x+yz. The original function is therefore (¬w¬x+yz)(w+¬x+z).
The remaining factor is redundant. Whenever ¬w¬x=1, its term ¬x makes w+¬x+z true. Whenever yz=1, its term z makes that factor true. Thus multiplying by it changes neither product term and f=¬w¬x+yz.
To justify minimality, not just equivalence, consider the true input 0000 in variable order wxyz. Any implicant covering it must require w=0 and x=0: changing w alone gives 1000, which is false, and changing x alone gives 0100, which is false. Its largest covering cube is therefore ¬w¬x. At 1111, changing y alone or z alone makes f false, so an implicant covering that point must require y=z=1. Its largest covering cube is yz. A single product cannot cover both 0000 and 1111 without allowing false inputs, since they disagree on every variable. Hence at least two terms and at least four literals are needed. The expression above uses exactly two two-literal terms and is minimal.
As a separate finite check, its 1-minterms are 0,1,2,3,7,11,15. Evaluating all 16 assignments agrees with the visually read five-factor source formula.
f=(¬w+y)(¬x+y)(w+¬x+z)(¬w+z)(¬x+z), where + is Boolean OR, juxtaposition is AND, and ¬ is complement. If the output line is stuck at 0, for how many input combinations is the output incorrect?
Answer & solution
Answer: 7 of the 16 input combinations. (no official key was published)
A stuck-at-zero output differs from the correct circuit exactly on inputs for which f should be 1. Inputs where f=0 still produce the correct visible output even though the circuit is faulty. First simplify the function to f=¬w¬x+yz using Boolean algebra.
Count the satisfying assignments by inclusion-exclusion. The term ¬w¬x fixes w=x=0 and leaves y,z free, giving four inputs. The term yz fixes y=z=1 and leaves w,x free, also giving four inputs. Their intersection fixes w=x=0,y=z=1, so that single input was counted twice. The number of distinct true inputs is 4+4−1=7.
In wxyz binary order, the erroneous inputs are 0000,0001,0010,0011,0111,1011,1111, corresponding to minterms 0,1,2,3,7,11,15. On each, the healthy output is 1 and the faulty output is 0. The other nine combinations have healthy output 0 and therefore do not expose this fault.
This count concerns one stuck-at fault on the final output line. It is not the count of faulty internal signals, nor a probability unless an input distribution is supplied. If all 16 inputs are equally likely, the observable error probability would be 7/16, but the requested answer is the integer 7.
A floating-point value is n=(f,e)=f·2^e. The fractional mantissa f has 6 bits including its sign bit, in sign-magnitude form. The exponent e has 4 bits including its sign bit, also sign-magnitude. A=54.75 and B=9.75 in decimal. No rounding mode, guard-bit convention, or normalization rule is explicitly supplied; use the conventional normalized fraction 1/2≤|f|<1 and state the rounding assumption. Represent A and B in this format.
Answer & solution
Answer: With normalized mantissas and chopping: A→(0 11011,0 110)=54; B→(0 10011,0 100)=9.5. Neither original value is exactly representable. (no official key was published)
The six mantissa bits include the sign, leaving only five fraction-magnitude bits. The four exponent bits similarly leave three bits for its magnitude, so exponents range from −7 to +7, not the biased range of IEEE formats. Use a sign bit of 0 for each positive field.
Convert the values exactly first: 54.75=110110.11₂=.11011011₂×26, 9.75=1001.11₂=.100111₂×24. Both normalized binary fractions need more than five magnitude bits. Therefore there is no exact six-bit-mantissa representation of either input under this normalization. A finite encoding requires a rounding rule; merely truncating without saying so would hide a loss of information.
Under chopping toward zero, retain the first five fraction bits: A: mantissa 0|11011, exponent 0|110; value .11011₂×64=54. B: mantissa 0|10011, exponent 0|100; value .10011₂×16=9.5. The vertical bar separates the sign from magnitude. No hidden leading bit is added; all five fraction bits are explicitly stored. The exponent fields are the sign-magnitude representations of +6 and +4.
For comparison, round-to-nearest with ties-to-even gives A=54 again but B=10, encoded as mantissa 0|10100 with exponent 0|100. B=9.75 lies exactly halfway between 9.5 and 10; the retained significand integer for 10 is even. Other tie rules may choose differently. This alternative is not an official correction: it demonstrates why the source's missing rounding policy matters. The subsequent worked addition and 3.9% error use the explicitly stated chopping model throughout.
A floating-point value is n=(f,e)=f·2^e. The fractional mantissa f has 6 bits including its sign bit, in sign-magnitude form. The exponent e has 4 bits including its sign bit, also sign-magnitude. A=54.75 and B=9.75 in decimal. No rounding mode, guard-bit convention, or normalization rule is explicitly supplied; use the conventional normalized fraction 1/2≤|f|<1 and state the rounding assumption. Show the floating-point addition of A and B.
Answer & solution
Answer: With five-bit mantissa chopping: result (0 11111,0 110)=62. Under round-to-nearest/ties-to-even throughout, result=64 instead. (no official key was published)
Use the chopping encodings A≈.11011₂×26=54 and B≈.10011₂×24=9.5. To add, align both to the larger exponent +6. Shifting B's fraction right by two places gives .0010011₂×26. With only five fraction positions and chopping on alignment, this becomes .00100₂×26=8.
The stored-width addition is
.11011 × 2^6
+ .00100 × 2^6
= .11111 × 2^6.
The mantissa is already normalized, lying between 1/2 and 1, and has five fraction bits. There is no carry that requires an exponent increment. Store mantissa 0|11111 and exponent 0|110, representing (31/32)×64=62. Both fields are within range.
Keeping guard bits changes the intermediate arithmetic but not this particular chopped final answer. With full aligned precision, the represented inputs sum to .1111111₂×26=63.5. Chopping that result to five fraction bits again yields .11111₂×26=62. Thus a final value of 62 does not establish whether guard bits were used; both stated chopping paths happen to agree here.
Under a different policy, round-to-nearest with ties-to-even encodes the inputs as 54 and 10. Their exact sum is 64=.10000₂×27, already representable, so the stored result is mantissa 0|10000, exponent 0|111. The true decimal-input sum is 64.5, which also rounds to 64 at this precision. The source does not choose between these policies. This solution therefore reports 62 only under chopping, with 64 as a clearly separate rounded alternative; it does not present an unspecified hardware behavior as an official answer.
A floating-point value is n=(f,e)=f·2^e. The fractional mantissa f has 6 bits including its sign bit, in sign-magnitude form. The exponent e has 4 bits including its sign bit, also sign-magnitude. A=54.75 and B=9.75 in decimal. No rounding mode, guard-bit convention, or normalization rule is explicitly supplied; use the conventional normalized fraction 1/2≤|f|<1 and state the rounding assumption. Find the percentage error in the addition, to one decimal place.
Answer & solution
Answer: 3.9% relative to the exact sum under chopping (computed 62 versus exact 64.5); 0.8% under the separately stated nearest-rounding model. (no official key was published)
The exact mathematical sum of the original decimal inputs is A+B=54.75+9.75=64.5. With normalized five-bit fraction magnitudes and chopping as in the worked addition, the computed result is 62. The absolute error is |62−64.5|=2.5. Percentage relative error uses the exact value as denominator:
Rounded to one decimal place, the error is 3.9%. If a signed percentage error were desired, it would be −3.9%, indicating underestimation; the usual unqualified percentage error is its nonnegative magnitude.
Do not divide by the computed 62, and do not use 63.5 as the reference merely because that is the exact sum of the already chopped input representations 54 and 9.5. The task concerns addition of the original A and B; input-representation error is part of the total discrepancy from 64.5. Relative to 63.5 alone the arithmetic-stage error would be a different quantity, 100×1.5/63.5≈2.4%.
The source's missing rounding policy persists into this part. Under round-to-nearest/ties-to-even the computed sum is 64, making the corresponding total percentage error 100×0.5/64.5≈0.77519%, or 0.8%. Accordingly 3.9% is a conditional derived answer under the declared chopping convention, not a uniquely verified official value.
Three processes use a shared resource R mutually exclusively and nonpreemptively. Each has a unique fixed priority in {1,2,3}, with 3 highest. Shared state: semaphore mutex=1; semaphores proceed[1..3]=0; Boolean R_requested[1..3]=false; Boolean busy=false. Each process repeats request_R(my_priority); P(proceed[my_priority]); use R; release_R(my_priority). The supplied request_R(p) performs P(mutex); if busy then R_requested[p]:=true else begin V(proceed[p]); busy:=true end; V(mutex). Give release_R so each allocation goes to the highest-priority current requester. The shared-data declaration is printed as process[3] in the reproduction, while uses consistently say proceed; normalize that apparent naming typo explicitly.
Answer & solution
Answer: Under mutex, select the highest set request flag, clear it and signal that process while retaining busy=true; set busy=false only if no process waits. (no official key was published)
The release operation must inspect request flags and either transfer ownership or mark the resource free as one atomic critical section. Otherwise a new requester could take R between checking the flags and waking a waiting process. This code uses the same proceed array as the process and request routines; the source's isolated process spelling is treated as a declaration typo.
procedure release_R(my_priority):
P(mutex)
chosen := 0
for p := 3 downto 1 do
if R_requested[p] then
chosen := p
break
if chosen = 0 then
busy := false
else
R_requested[chosen] := false
busy := true
V(proceed[chosen])
V(mutex)
The parameter my_priority identifies the releasing owner but is not needed to select the next one. Preconditions are that only the current owner calls release_R, each process has at most one outstanding request, and P/V have standard semaphore semantics. The no-waiter branch does not signal a semaphore: the next arriving requester will signal its own proceed entry in request_R before doing P on it.
Why keep busy true during handoff? A signaled process may not run immediately. The resource is nevertheless reserved for it; setting busy false would let a newcomer receive a second grant. Clearing the chosen flag prevents a later release from treating the same already-granted request as still waiting. Lower-priority flags remain set, preserving their requests.
Since priorities are unique and the loop scans 3,2,1, it chooses the highest pending priority at the moment of allocation. A higher-priority process arriving after that atomic choice must wait: the resource is nonpreemptive, so priority does not revoke an existing grant. At most one grant exists at a time, maintaining mutual exclusion. This scheme can starve a low-priority requester if higher-priority requests keep arriving; starvation freedom was not requested and does not follow from strict priority allocation.
A program processes 1000 consecutive records of a sequential file on a device, without file-system facilities. Each record is 3200 bytes. Device access time is 10 ms per read; transfer rate is 800×10^3 bytes/s; CPU processing time is 3 ms per record. Copying a record from a buffer to a local variable takes negligible CPU time. Ignore additional overhead, and include startup and final processing time. Records are unblocked and the program uses no buffering. Find elapsed time.
Answer & solution
Answer: 17,000 ms = 17 s. (no official key was published)
One record's transfer time is its byte count divided by the byte rate: 3200/(800×103) seconds = 0.004 seconds = 4 ms. The 10 ms access time is a separate per-read cost, so reading one unblocked record takes 10+4=14 ms. With no buffering, the program reads a record, waits for that read to finish, processes it for 3 ms, and only then starts the next record's read.
The per-record serial schedule is therefore [10 ms access][4 ms transfer][3 ms processing], lasting 17 ms. Repeating it for 1000 records gives 1000×17=17,000 ms=17 seconds. The first record's access and the last record's processing are already included, so no extra startup or drain term should be appended.
The word consecutive does not by itself remove the explicitly supplied access cost. The usual model of this question charges one access for each unblocked read; a continuous streaming device model that pays access only once would be a different assumption. Likewise, the rate is in bytes per second, so no factor of eight belongs in the calculation. The result uses the decimal rate 800×103 exactly as printed.
Without read-ahead storage there is no valid overlap between reading the next record and processing the current one in this model. Using max(14,3) per record would silently introduce buffering, which is the separate next part of the question.
A program processes 1000 consecutive records of a sequential file on a device, without file-system facilities. Each record is 3200 bytes. Device access time is 10 ms per read; transfer rate is 800×10^3 bytes/s; CPU processing time is 3 ms per record. Copying a record from a buffer to a local variable takes negligible CPU time. Ignore additional overhead, and include startup and final processing time. Records are unblocked and the program uses one buffer, always reading ahead into it. Find elapsed time.
Answer & solution
Answer: 14,003 ms = 14.003 s, under the stated ideal one-buffer read-ahead model. (no official key was published)
A record read takes 10 ms access plus 3200/(800×103) seconds transfer, or 14 ms total. The first read fills the buffer at t=14 ms. Copy record 1 into the program's local record variable at negligible cost, freeing the buffer immediately. The device can now read record 2 while the CPU processes record 1.
The timeline begins: 0–14 ms: read record 1; CPU has no record yet. 14–17 ms: process local record 1; read record 2 during 14–28 ms. 28–31 ms: process local record 2; read record 3 during 28–42 ms.
Because each read lasts 14 ms and each computation only 3 ms, the CPU finishes before the next record arrives. Record k is available at 14k ms. The final record, number 1000, arrives at 14,000 ms and must still be processed for 3 ms. Total elapsed time is 14,000+3=14,003 ms.
Equivalently, for N records, read time I and compute time C, this ideal single-record-buffer/local-variable pipeline takes I+(N−1)max(I,C)+C. Here it becomes 14+999×14+3. This formula includes the initial fill and final drain. The common shortcut N×max(I,C) would miss the last 3 ms.
One buffer is enough because the current record is moved out of that buffer before processing; CPU work uses the local copy while the device writes the next record to the buffer. This is not the same as processing in place in the sole buffer, which would prevent safe read-ahead. The source's negligible-copy assumption is what permits the overlap.
A program processes 1000 consecutive records of a sequential file on a device, without file-system facilities. Each record is 3200 bytes. Device access time is 10 ms per read; transfer rate is 800×10^3 bytes/s; CPU processing time is 3 ms per record. Copying a record from a buffer to a local variable takes negligible CPU time. Ignore additional overhead, and include startup and final processing time. The file uses blocking factor 2: each device block contains two records. The program uses one buffer. Find elapsed time, explicitly stating when the next read may begin and whether the program can retain a whole block outside the buffer.
Answer & solution
Answer: 10.503 s with one-record local storage and reads starting only after the whole buffer is free; 9.006 s with whole-block staging or early overlap (no official key was published)
There are 1000/2=500 blocks. Each block holds 6400 bytes, so its transfer takes 6400/(800×103)=0.008 s=8 ms. Including the 10 ms access, one block read takes I=18 ms. Processing its two records takes 6 ms total. The words one buffer do not alone determine how the unread second record is protected while another read is started.
Model 1: one block buffer, one-record local variable, and a new block-read operation starts only after the buffer is entirely free. The first block arrives at t=18 ms. Copy record 1 locally and process it during 18–21. Record 2 must remain in the buffer during that computation. At 21, copy record 2 locally; the buffer is now free, so start the second block read during 21–39 while processing record 2 during 21–24. Thus each block arrival is 21 ms after the preceding one, not 18 ms: three CPU milliseconds are needed before the unread second record can leave the buffer.
The kth block arrives at 18+(k−1)×21 ms. For block 500 this is 10,497 ms. After it arrives, both final records still require 6 ms, giving 18+499×21+6=10,503 ms=10.503 s. Only the last record of each nonfinal block overlaps the following read. This schedule never overwrites a record that has not been copied out.
Model 2: copy the whole two-record block into separate local staging at negligible cost, releasing the input buffer immediately. Then all 6 ms of computation can overlap the following 18 ms read. The pipeline time is 18+499×max(18,6)+6=9006 ms=9.006 s. This model needs enough staging for two records, not just the single local record explicitly used in Model 1.
A second way to attain 9.006 s is to allow the next device access phase to begin before the buffer is free, while delaying actual writes until it is safe. Start the next 10 ms access immediately when the prior block arrives. The buffer's remaining record is copied out after 3 ms, well before the subsequent 8 ms transfer begins. Block arrivals can then remain 18 ms apart even with one-record local storage. That requires an I/O interface/scheduler that supports this early access, which the question does not explicitly describe.
Accordingly 9.006 s is the conventional whole-block-pipeline result, and 10.503 s is the stricter one-record/cannot-start-until-free result. Neither should be presented as unconditionally forced by the supplied wording. The distinction is about storage and I/O scheduling, not the arithmetic of the 18 ms block read.
Each process receives a unique timestamp when it starts, increasing with time; smaller means older. On requesting a resource: if it is free, the OS grants it; if holder Q is older than requester P (TS(Q)<TS(P)), P waits; if Q is younger (TS(Q)>TS(P)), the OS restarts Q and grants the resource to P. Restarting takes back all Q's resources, kills Q, and starts it again with the same timestamp. When a resource is released, the waiting process with smallest timestamp receives it. A process asks for resources, uses them for some time, then exits. Can deadlock ever arise? Prove your answer.
Answer & solution
Answer: No resource deadlock: every wait-for edge points from a younger process to an older process, so a cycle is impossible. (no official key was published)
Form a wait-for graph whose vertices are active processes. Add an edge P→Q when P is blocked waiting for a resource currently held by Q. The rules allow that wait only when TS(Q)<TS(P). If the holder is younger, the requester does not wait; it wounds the holder, whose resources are released on restart. Therefore timestamps strictly decrease along every wait-for edge.
Suppose a resource deadlock existed. For ordinary exclusive resources, a finite set of processes each blocked on resources held within the set contains a directed cycle P1→P2→…→Pk→P1. The edge rule would imply TS(P1)>TS(P2)>…>TS(Pk)>TS(P1), which is impossible for distinct ordered timestamps. Thus the wait-for graph is acyclic and the stated resource protocol cannot create deadlock.
For intuition, an older process can force a younger holder to release its resources rather than becoming dependent on it. A younger process may depend on an older one, but dependencies can never turn back toward a younger timestamp to close a cycle. This is the wound-wait scheme, not wait-die: the older requester survives and restarts the younger holder.
The restart must release all resources of the victim, as the source explicitly states; retaining them while the victim cannot proceed would not implement this proof's protocol. Resource grants, victim removal and wait-queue updates are assumed to be performed consistently by the OS. The argument rules out resource deadlock, not every possible lack of progress. An unfair CPU scheduler or a process that never finishes could still delay other processes indefinitely; those are separate starvation/liveness issues addressed under additional assumptions in the next part.
Each process receives a unique timestamp when it starts, increasing with time; smaller means older. On requesting a resource: if it is free, the OS grants it; if holder Q is older than requester P (TS(Q)<TS(P)), P waits; if Q is younger (TS(Q)>TS(P)), the OS restarts Q and grants the resource to P. Restarting takes back all Q's resources, kills Q, and starts it again with the same timestamp. When a resource is released, the waiting process with smallest timestamp receives it. A process asks for resources, uses them for some time, then exits. Can a process be starved? Prove or qualify your answer.
Answer & solution
Answer: No protocol-induced starvation under finite older predecessors, finite terminating work, and fair execution; an unconditional guarantee without these progress assumptions is not justified. (no official key was published)
Fix a process P. When it begins there are only finitely many older processes in the usual finite-system model, and every later arrival has a larger timestamp. Because a restarted process keeps its original timestamp, repeated restarts do not move P behind newcomers. Only processes older than P can wound it or outrank it on a waiting queue.
First consider the oldest active process. It cannot be wounded, and it cannot be forced to wait for a younger holder: it wounds that holder and obtains the resource. Under fair CPU execution and the stated assumption that a process does finite work and exits, this oldest process eventually completes and releases its resources. Apply the same argument successively to the remaining older processes. Since P has finitely many older predecessors, eventually they have all completed.
P is then the oldest remaining process. New arrivals remain younger and cannot wound P. A resource held by a younger process is obtained by wounding that holder; if P is already waiting when a resource is released, smallest-timestamp selection gives it precedence over younger waiters. With finite resource requests/work and fair execution, P therefore finishes. This proves absence of starvation caused by the allocation protocol under the usual progress assumptions.
Retaining timestamps is crucial. Assigning a fresh, ever-larger timestamp after every restart would destroy the fixed finite-predecessor argument. Conversely, deadlock freedom by itself would not prove starvation freedom: an acyclic system could still repeatedly favor newcomers under a different queue rule.
The question's finite-use-and-exit wording motivates the normal no-starvation answer, but scheduler fairness is not explicitly specified. If the CPU never schedules P, or an older process never finishes, P may wait indefinitely despite the timestamp rules. Those countermodels violate the progress assumptions used in the proof; they do not exhibit a starvation defect in wound-wait itself. State the assumptions rather than claiming unconditional termination from timestamp ordering alone.
Relations are EMP(eno,name,age), PROJ(pno,name), and INVOLVED(eno,pno). The underlined primary keys are EMP.eno, PROJ.pno, and the composite key (eno,pno) of INVOLVED. EMP describes employees, PROJ projects, and INVOLVED employee–project participation. Use ordinary set relational algebra unless a different model is explicitly stated. Translate the supplied SQL using relational-algebra operators: SELECT eno FROM EMP, INVOLVED WHERE EMP.eno = INVOLVED.eno AND INVOLVED.pno = 3; The SELECT column is unqualified in the reproduction.
Answer & solution
Answer: After qualifying SELECT EMP.eno, the set-algebra answer is π_EMP.eno(σ_EMP.eno=INVOLVED.eno ∧ INVOLVED.pno=3(EMP×INVOLVED)). Literal SQL has an ambiguous column reference. (no official key was published)
First distinguish the printed query from its evident intention. Both EMP and INVOLVED have a column named eno, and an explicit FROM EMP,INVOLVED cross join retains both column names. The equality in WHERE does not make the unqualified SELECT eno syntactically unambiguous in standard SQL. The literal query therefore requires qualification. Taking the intended target as EMP.eno gives:
The Cartesian product produces all employee/participation row pairs. Selection keeps only pairs referring to the same employee and project number 3. Projection then retains the requested employee number. One may push the project filter down before the product, obtaining π_EMP.eno(σ_EMP.eno=INVOLVED.eno(EMP × σ_pno=3(INVOLVED))), which is set-equivalent and usually more efficient.
Attribute qualification in the first formula prevents confusion between the two eno fields and the two relations. A natural join EMP ⋈ INVOLVED followed by σ_pno=3 and π_eno is also valid here because eno is their only shared attribute name. PROJ is not used: the SQL never checks whether project 3 exists in PROJ, and adding that join would impose an extra condition not present in the query.
The displayed composite primary key (eno,pno) of INVOLVED rules out duplicate employee–project pairs, and EMP.eno is also a primary key. After restricting INVOLVED.pno to 3, there is at most one qualifying involvement row for each employee, and the join matches at most one EMP row. Therefore the qualified SELECT returns each selected employee number at most once. Although SQL SELECT normally uses bag semantics and ordinary relational algebra uses sets, that difference does not change this query’s result under the stated keys. No added DISTINCT or extra uniqueness assumption is needed. The printed unqualified SELECT eno still requires the column-name repair explained above.
Relations are EMP(eno,name,age), PROJ(pno,name), and INVOLVED(eno,pno). The underlined primary keys are EMP.eno, PROJ.pno, and the composite key (eno,pno) of INVOLVED. EMP describes employees, PROJ projects, and INVOLVED employee–project participation. Use ordinary set relational algebra unless a different model is explicitly stated. In at most 15 words state what this relational-algebra expression determines: π_eno(INVOLVED) − π_eno((π_eno(INVOLVED) × π_pno(PROJ)) − INVOLVED). The two b-subparts together carry 4 marks; their individual marks are not printed.
Answer & solution
Answer: Employee numbers of involved employees who participate in every project. (no official key was published)
Requested short answer: Employee numbers of involved employees who participate in every project.
This is 10 words, within the requested limit. The wording involved employees preserves the candidate domain actually used by the expression. For the derivation, let C=π_eno(INVOLVED) be the employee numbers appearing in at least one involvement row, let P=π_pno(PROJ) be all project numbers, and let R=INVOLVED.
The product C×P enumerates every employee–project pair that would be required if each candidate participated in every project. Subtracting R leaves missing pairs: a pair (e,p) remains exactly when e is a candidate, p is a project, and the participation (e,p) is absent. Projecting those missing pairs onto eno produces the candidates who fail to participate in at least one project. Finally, subtracting that set from C leaves the candidates with no missing project.
Formally, the result is {e∈C: for every p∈P, (e,p)∈R}. This is the usual division construction R÷P with its candidate universe drawn from R. For example, if P={1,2}, candidate 7 appears with both projects and candidate 8 only with project 1, the missing-pair set contains (8,2), so only 7 remains.
Two boundary details matter. EMP is not referenced, so the expression does not independently check that every eno is a valid employee if referential integrity is absent. If PROJ is empty, C×P is empty, the missing-candidate set is empty, and the result is C by vacuous truth. It is not automatically all rows of EMP; employees absent from INVOLVED are outside the candidate universe even in that empty-project case. The short answer is therefore narrower and more faithful than an unconditional claim that all employees participating in every project are returned.
Relations are EMP(eno,name,age), PROJ(pno,name), and INVOLVED(eno,pno). The underlined primary keys are EMP.eno, PROJ.pno, and the composite key (eno,pno) of INVOLVED. EMP describes employees, PROJ projects, and INVOLVED employee–project participation. Use ordinary set relational algebra unless a different model is explicitly stated. In at most 15 words explain the second expression in GFG76(b). The available reproduction visibly reads approximately π_age(EMP) − π_{E.age<EMP.age}(ρ_E(EMP) × EMP). The second operator is printed as a projection symbol whose subscript is a comparison, rather than a projection of an attribute followed by a selection. A note describes ρ as renaming a copy of EMP, but uses an inconsistent alias in its prose. State the literal defect, and separately explain the likely intended well-typed maximum-age query. The two b-subparts jointly carry 4 marks; individual allocations are unavailable.
Answer & solution
Answer: Literal expression: not well-typed standard relational algebra. Under the separately stated repair: “Ages of the oldest employees.” (no official key was published)
Literal reading first: in standard relational algebra, π takes an attribute list, not a Boolean comparison predicate. The printed subscript E.age<EMP.age therefore does not define an ordinary projection. Simply changing that π into σ is insufficient: it would produce tuples of the two-relation product, which cannot be subtracted from the unary relation π_age(EMP). Set difference requires compatible schemas. Consequently the paper, as read, does not have a defined standard relational-algebra result. No verified original or alternate complete tail is available to establish the missing symbols.
A plausible intended repair is π_age(EMP) − ρ_age←E.age(π_E.age(σ_E.age<EMP.age(ρ_E(EMP) × EMP))). Here ρ_E(EMP) is a distinct copy whose attributes are qualified E. The inner selection finds each pair where the copied employee is younger than the other employee. Projecting E.age collects ages that have a strictly greater age somewhere in EMP. The explicit attribute rename makes the right-hand unary age relation union-compatible with the left-hand one. Subtract those nonmaximum ages from all ages and only the maximum age remains.
Under this repair, the requested short English answer is: Ages of the oldest employees. This is five words. For ages {25,40,40}, the Cartesian comparison finds that 25 has an older witness, while 40 does not. Set projection removes duplicate 40s, and the final result is {40}, an age value rather than employee names or employee records. With an empty EMP, the result is empty. Equal ages do not eliminate each other because the comparison is strict.
This maximum-age interpretation is conditional on projecting the younger copy's age. Projecting EMP.age instead would remove ages that have a smaller witness and leave the minimum, a different query. Thus the damaged expression cannot safely be repaired silently. The literal defect and the proposed older-witness interpretation must remain separate until a better source establishes the exact original notation.