Rows are B=0, 1 and columns C=0, 1. The four entries are 1, 0, ¬A, A respectively. Give a sum of products.
Answer & solution
Answer: ¬B¬C+¬A¬C+ABC (no official key was published)
The B=0, C=0 cell is one for either A, giving ¬B¬C. At B=1, C=0 the output is ¬A, which joins the A=0 portion of the first cell to give ¬A¬C. The remaining one occurs at A=B=C=1 and is isolated, giving ABC. Thus the SOP is ¬B¬C+¬A¬C+ABC. Alternatively the direct unsimplified expansion ¬B¬C+¬AB¬C+ABC is equivalent. The letter entries in the map are functions of the third variable, not literal binary cells.
A code carries four data bits and is to detect up to three bit errors and correct one. Give extra parity bits and minimum distance.
Answer & solution
Answer: 4 parity bits; minimum distance 4 for the extended Hamming code (no official key was published)
Ordinary Hamming(7, 4) uses three parity bits and has distance three, enough for single-error correction but only two-error detection as a code-distance property. Adding one overall parity bit produces extended Hamming(8, 4), with four redundancy bits and distance four. Distance d detects up to d−1 errors and corrects floor((d−1)/2), giving three and one here. These are separate guarantees: a decoder that automatically corrects a one-bit-looking syndrome can miscorrect some triple errors. Guaranteed simultaneous classification of every one-bit versus three-bit error requires a stronger distance condition than this standard detect-or-correct interpretation.
Why do some microprocessors specify a minimum as well as maximum clock frequency?
Answer & solution
Answer: Dynamic internal storage must be refreshed before charge leaks away (no official key was published)
Some processors use dynamic nodes or storage circuits that retain information as charge rather than static feedback. Clocked transitions periodically refresh or transfer that charge. If the clock is slowed excessively or stopped, leakage can corrupt stored state, imposing a minimum rate. This is an implementation property, not a universal law for every processor; a fully static design can often stop its clock while preserving state. The maximum clock rate instead arises from propagation and setup/hold timing constraints.
Why does prefetching instructions into a buffer improve processing speed?
Answer & solution
Answer: It overlaps instruction fetch with execution and reduces fetch waiting (no official key was published)
While the execution unit works on one instruction, a fetch unit can use available bus cycles to obtain later instructions into a queue. When execution needs the next instruction, it may already be present, hiding some memory latency rather than performing fetch and execution strictly serially. The gain is conditional on resources and a sufficiently predictable instruction stream. Branches can invalidate prefetched instructions, and a saturated shared memory bus can limit overlap, so prefetch is not a guarantee of speedup for every program.
Fill in why a handshake protocol provides reliable transfer for each data item sent.
Answer & solution
Answer: The receiver acknowledges acceptance before the sender proceeds (no official key was published)
A request or data-valid signal tells the receiver that a transfer is available. The receiver responds with an acknowledgment after accepting the item, allowing the sender to withdraw it or send the next one. This coordinates devices with different or variable speeds without assuming a fixed delay is always sufficient. The basic handshake prevents loss from timing mismatch; it does not alone detect arbitrary corruption of data bits. Error-detecting codes or retransmission rules would be separate protocol features.
An 11-bit instruction with 4-bit address fields allegedly supports five two-address instructions and 32 two-address instructions. How many zero-address instructions remain?
Answer & solution
Answer: Literal premise impossible; 256 if the second group was intended to be one-address (no official key was published)
A two-address instruction uses eight operand bits, leaving only three opcode bits, hence at most eight distinct two-address operations. The literal total of 37 is impossible. If the second phrase is repaired to 32 one-address instructions, five primary opcodes are consumed, leaving three. Expanding each by four bits gives 48 one-address opcode patterns. After using 32, the remaining 16 patterns can each expand by another four bits into 16 zero-address patterns, yielding 256. Both copies repeat “two-address, ” so 256 is explicitly a conditional reconstruction, not a solution to the literal inconsistent specification.
Why expand macros in pass one rather than pass two?
Answer & solution
Answer: Expansion changes code size and the addresses needed for the symbol table (no official key was published)
A macro invocation can expand into several instructions, data definitions and labels. Pass one must account for their sizes to advance the location counter correctly and assign addresses to all later symbols. Deferring expansion until after that layout would invalidate those addresses or require another layout pass. Thus the standard macro assembler expands before or during its first layout pass. A separately implemented macro preprocessor can perform the same work before the nominal assembler passes; the essential requirement is expansion before final address assignment.
What is the purpose of an assembler’s instruction location counter?
Answer & solution
Answer: Track the address assigned to the next instruction or data item (no official key was published)
The location counter starts from the selected origin and advances by each assembled instruction or reserved data size. A label encountered at a statement is assigned the current location, enabling the symbol table to record its address. Directives such as ORG can change the counter explicitly. This is a compile/assembly-time layout variable, not the processor’s runtime program counter. Its final difference from the origin can also help determine section length, subject to separate sections and origin changes.
For n vertices and m presorted edges, state Kruskal’s running time and the union-find model.
Answer & solution
Answer: O(m α(n)+n) with optimized union-find; O(m log n+n) with balanced-tree bounds (no official key was published)
Initialize n singleton components, scan edges in the given order and use two find operations to test whether each edge crosses components. Accepted edges trigger a union, at most n−1 times. With path compression and union by rank, the total is O(m α(n)+n), since sorting has already been removed. A simpler union-find implementation with logarithmic operations gives O(m log n+n). Reporting only the usual O(m log m) sorting bound would ignore the supplied sorted order. The exact implementation must be stated rather than treating one data-structure bound as universal.
What is the maximum number of edges of a planar graph with n vertices?
Answer & solution
Answer: 3n−6 for simple planar graphs with n≥3 (no official key was published)
For a connected simple planar embedding, Euler gives n−m+f=2. Every face boundary has length at least three, while each edge contributes two boundary incidences, so 3f≤2m. Combining gives m≤3n−6, attained by triangulations. Disconnected simple graphs cannot exceed that maximum. Simplicity and n≥3 are necessary qualifications: parallel edges can make edge count unbounded for fixed n, and the small cases n=1, 2 have maxima 0, 1. The familiar formula is therefore a conditional standard answer, not valid for every use of the word graph.
Similar questions3 more → · asked again: GATE 1998, Q2.8
Commutative but nonassociative gate
Boolean Algebra & Logic Gates
Tap to enlarge
Which operation is commutative but not associative: AND, OR, XOR, NAND?
Select all that apply
Answer & solution
Answer: D: NAND (no official key was published)
NAND(a, b)=¬(ab), unchanged when a and b are exchanged, so it is commutative. To refute associativity choose a=0, b=1, c=1. Then NAND(NAND(0, 1), 1)=NAND(1, 1)=0, whereas NAND(0, NAND(1, 1))=NAND(0, 0)=1. AND, OR and XOR are associative as well as commutative. A single counterexample suffices to disprove the NAND associativity identity for all triples.
Which can realize arbitrary digital Boolean functions: XOR gates, multiplexers, half adders, OR gates? State constant-input assumptions.
Select all that apply
Answer & solution
Answer: B, C for combinational functions with constants available (no official key was published)
A multiplexer implements Shannon expansion f=¬s f0+s f1, so recursively selecting cofactors realizes any Boolean function with constant leaves. A half adder supplies XOR and AND; tying one XOR input to 1 gives NOT, and AND plus NOT is functionally complete. XOR-only networks remain affine, while OR-only networks cannot implement negation. Thus B, C follow when constants, especially 1, are available. Without a supplied 1, mux and half-adder networks are zero-preserving and cannot realize every function. Also sequential circuits require state/feedback assumptions beyond combinational functional completeness; the source’s “all digital circuits” is broader than the standard intended claim.
Which bit-slice claims hold: cascade for word length; speed independent of width; no standalone program counter; only the CPU datapath?
Select all that apply
Answer & solution
Answer: A, C, D for conventional ALU/register slices (no official key was published)
A bit-slice component implements a small-width arithmetic/register datapath. Cascading slices constructs a wider datapath, so A holds. Control sequencing and program-counter functions are normally supplied externally to the datapath slice, motivating C and D. Speed is not generally width-independent: carry propagation and inter-slice wiring can increase delay unless additional carry-lookahead structures are used. These claims refer to conventional datapath slices rather than every chip ever marketed in a bit-slice family; specialized sequencer components can supply the omitted control functions.
8085 PCHL copies HL to PC. Which construct is it especially useful for: if/then/else, while, case, call?
Select all that apply
Answer & solution
Answer: C: case dispatch through a jump table (no official key was published)
A case statement can compute an index, retrieve the selected branch address from a table into HL, then use PCHL to jump directly there. This is an indirect/computed branch rather than a fixed immediate target. Ordinary if and while control are usually implemented with conditional direct branches. PCHL also does not save a return address, so it is not a complete CALL instruction. With auxiliary code an indirect jump can participate in many constructs; C identifies the characteristic direct application, not an impossibility theorem for every other use.
Similar questions2 more → · asked again: GATE 2002, Q1.11
Purpose of start and stop bits
Data Link, Framing, Error Control & ARQ
Tap to enlarge
Are start/stop bits used for error detection, correction, synchronization, or slowing communication?
Select all that apply
Answer & solution
Answer: C: synchronization (no official key was published)
In asynchronous serial communication, the start transition establishes the beginning of a character frame and lets the receiver align its sampling clock. Stop bits return the line to an idle state and separate frames. They are framing overhead rather than payload. A receiver may report a framing error when an expected stop bit is absent, but these bits are not a general error-correcting code. Slowing the payload rate is a consequence of overhead, not their purpose.
Which is the polynomial-time exception among Hamiltonian circuit, 0/1 knapsack, biconnected components, and graph coloring?
Select all that apply
Answer & solution
Answer: C: biconnected components, under the conventional P≠NP interpretation (no official key was published)
A DFS computes discovery times and low-link values, identifying articulation points and biconnected components in O(V+E). General Hamiltonian-cycle and coloring decision variants are NP-complete, and 0/1 knapsack is NP-hard in its optimization form, with NP-complete decision form. Thus C is the standard intended answer to “not NP-hard.” Strictly, proving a nontrivial polynomial decision problem is not NP-hard would require separating P from NP; the classification here uses the conventional complexity distinction rather than claiming that open separation has been proved.
A 2–3 tree has nine leaves, all at equal depth, and every internal node has two or three children. Which internal counts 4, 5, 6, 7 are possible?
Select all that apply
Answer & solution
Answer: A, D: 4 and 7 (no official key was published)
At height two, the root must have three children and each must have three leaves, giving 1+3=4 internal nodes and nine leaves. At height three, nine leaves require four parents at the deepest internal level, since five would already require ten leaves. The preceding level must therefore have two nodes with two children each, and the root has those two children. Internal count is 1+2+4=7; give one deepest node three leaves and the others two to get nine. Greater height needs at least sixteen leaves. Thus counts 5 and 6 cannot fit the equal-depth constraint.
Which listed vertex/edge counts describe a nonplanar simple graph with the fewest vertices:9 edges 6 vertices, 6 edges 4 vertices, 10 edges 5 vertices, 9 edges 5 vertices?
Select all that apply
Answer & solution
Answer: C: K5 with 10 edges and 5 vertices (no official key was published)
Every simple graph on at most four vertices is a subgraph of planar K4, so nonplanarity requires at least five vertices. On five vertices, K5 is nonplanar and has 10 edges. Removing any edge from K5 gives a planar graph, so a five-vertex graph with only nine edges does not supply the required example. K3, 3 has nine edges but six vertices, so it minimizes a different quantity. The question asks for fewest vertices, not fewest edges.
Which listed method sorts n integers in [1, n³] in O(n): heapsort, quicksort, mergesort, radix sort?
Select all that apply
Answer & solution
Answer: D: radix sort (no official key was published)
Subtract one to put keys in [0, n³−1], then represent each in base n using three digits. Stable counting sort of one digit takes O(n+n)=O(n) time and O(n) auxiliary storage, so three least-significant-digit passes remain linear. Comparison sorts retain their general Ω(n log n) worst-case comparison barrier on arbitrary distinct keys; the integer representation lets radix sorting escape that model. The bound assumes word operations and digit extraction on these O(log n)-bit keys take constant time.
Similar questions1 more → · asked again: GATE 1998, Q1.31
Counting completed semaphore operations
Synchronization & Concurrency
Tap to enlarge
A counting semaphore starts at 7. Twenty P and fifteen V operations complete. What is its final value?
Select all that apply
Answer & solution
Answer: B: 2 (no official key was published)
Each completed P consumes one permit, decreasing the value by one; each V adds one. The net change is −20+15=−5, so the final value is 7−5=2. The word completed matters: blocked, uncompleted waits cannot simply be counted as successful acquisitions in a nonnegative semaphore convention. The stated totals permit an interleaving with enough signals before later waits, so no contradiction is implied by having twenty waits after an initial value of only seven.
Similar questions7 more → · asked again: GATE 1998, Q1.32
Maximum process count with six drives
Deadlocks
Tap to enlarge
Six identical tape drives are shared by n processes, each possibly needing three. What maximum n guarantees no resource deadlock without restrictive allocation?
Select all that apply
Answer & solution
Answer: A: n=2 (no official key was published)
A worst-case deadlock can have every process hold two drives and wait for its third. To rule that out for n processes, at least 2n+1 drives suffice under the standard completion model. With six drives, this requires n≤2. For three processes, each can hold two, exhausting all six and waiting forever. For two processes, their combined maximum demand is six, so both can be fully satisfied. The guarantee assumes eventual completion after required resources are granted and no additional resource types or faulty nontermination.
Similar questions2 more → · asked again: GATE 1998, Q1.29
A spooled device
I/O & Disk Scheduling
Tap to enlarge
Which is a spooled-device example: interactive input terminal, virtual-memory backing store, line printer serving jobs, or none?
Select all that apply
Answer & solution
Answer: C: line printer (no official key was published)
Spooling places jobs in a queue, usually on disk, and lets a dedicated service feed an exclusive sequential device at its own speed. A printer serving several jobs is the standard example: applications finish depositing their output without waiting for physical printing, and each job can be kept separate. A terminal’s interactive input and demand paging have different purposes, even though they may involve buffers or secondary storage. The presence of a buffer alone does not make an operation spooling.
FOLLOW(A) uses arbitrary sentential forms; LFOLLOW/RFOLLOW restrict to leftmost/rightmost forms. Both sources lose the L/R prefixes in choices A/B. Determine valid semantic relationships.
Select all that apply
Answer & solution
Answer: Option letters unresolved; LFOLLOW may differ, and RFOLLOW=FOLLOW under a productive-grammar convention (no official key was published)
Restricted derivations yield subsets of the ordinary FOLLOW set. For S→AB, A→a, B→b, ordinary and rightmost derivations expose Ab, so b belongs to FOLLOW(A) and RFOLLOW(A). Leftmost derivations must expand A before B, so LFOLLOW(A) is empty. This refutes the choices asserting all three always identical or all three always different. For productive grammars, rightmost derivations can realize the needed right context, giving RFOLLOW=FOLLOW. Without that convention, S→XB, X→Ab, B→B gives FOLLOW(A) containing b but no rightmost occurrence of A. Since A/B repeat the unqualified name FOLLOW in both copies, their intended exact comparisons and letters are not reconstructed silently.
For one CFG, compare SLR(1) and LALR(1) tables: goto parts may differ; shifts identical; reductions may differ; errors may differ.
Select all that apply
Answer & solution
Answer: B, C, D under aligned LR(0)-core state numbering (no official key was published)
Both constructions use the same LR(0) cores for transitions, so terminal shifts and nonterminal gotos coincide when corresponding states are identified. SLR places a completed A production on every token in FOLLOW(A). LALR instead uses the lookaheads propagated to that completed item, often a smaller set. Thus a cell that is a reduction or conflict in SLR may be an error or a different action set in LALR. Therefore shifts are identical but reduction/error entries may differ. Renaming state numbers does not count as a structural goto difference; conflict-resolution policies are separate from raw table construction.
Assess A [(∀xP)∨(∀xQ)]→∀x(P∨Q); B [(∃xP)∧(∃xQ)]→∃x(P∧Q); C ∀x(P∨Q)→[(∀xP)∨(∀xQ)]; D ∃x(P∨Q)→[¬∀xP∨∃xQ].
Select all that apply
Answer & solution
Answer: A only (no official key was published)
For A, if P holds everywhere or Q holds everywhere, their disjunction holds everywhere, so the implication is valid. B fails on a two-element domain where only the first element has P and only the second has Q: both existentials hold but no common witness does. The same interpretation refutes C because every element satisfies the disjunction while neither predicate holds universally. D fails on a one-element nonempty domain with P true and Q false. Its existential antecedent is true, but both ¬∀xP and ∃xQ are false. Thus only A is valid as printed; the negation in D applies to ∀xP, not to a universal conjunction of negated predicates.
Assess A (a∨b)→(b∧c); B (a∧b)→(b∨c); C (a∨b)→(b→c); D a→b→(b→c), whose association is unmarked.
Select all that apply
Answer & solution
Answer: B (no official key was published)
Whenever a∧b is true, b is true and therefore b∨c is true, so B is a tautology. A fails at a=1, b=0, c=0. C fails at a=0, b=1, c=0. D is not a tautology under either common association: right association fails at a=b=1, c=0; left association fails, for example, at a=0, b=1, c=0. The unmarked implication chain is disclosed, but it does not change the selection of B. These are propositional evaluations, not deductions assuming any extra premises.
The copies print A r(*)=r* and B (r*s*)=(r+s)*, plus C (r+s)*=r*+s* and D r*s*=r*+s*. Which identities are justified?
Select all that apply
Answer & solution
Answer: Literal A malformed, B/C/D false; intended A/B would need missing outer stars (no official key was published)
A standard true identity is (r*)*=r*, but the source’s r(*) is not that well-formed expression. Another true identity is (r*s*)*=(r+s)*, which requires an outer star absent from printed B. For literal B, take r=a, s=b: ba belongs to (a+b)* but not a*b*. For C, ab belongs to the left but neither a* nor b*. For D, ab belongs to a*b* but not a*+b*. Thus the often-intended answers A, B are conditional repairs, not identities established by the literal printed notation. The missing-star issue is retained as a source discrepancy.
Similar questions2 more → · asked again: GATE 1994, Q20
Length of a CNF derivation
Context-Free Grammars & Languages
Tap to enlarge
For a nonempty word w of length ℓ in a Chomsky-normal-form grammar, how many production applications derive it?
Select all that apply
Answer & solution
Answer: C: 2ℓ−1 (no official key was published)
A CNF parse tree uses binary nonterminal productions A→BC and terminal productions A→a. There are ℓ terminal-producing leaves. A full binary tree with ℓ leaves has ℓ−1 binary internal nodes, so the total applications are ℓ+(ℓ−1)=2ℓ−1. The order of expanding variables does not change that count. The special ε-production sometimes allowed for the start symbol is outside this nonempty-word case; substituting ℓ=0 into the formula would not count its derivation correctly.
Which closures hold for CFLs: union, complement, intersection, Kleene star?
Select all that apply
Answer & solution
Answer: A, D (no official key was published)
For union, introduce a new start symbol choosing either original grammar. For star, use a new start that produces ε or concatenates one original-language word with another repetition. Hence both operations preserve context-freeness. Intersection does not: {an bn cm} intersected with {am bn cn} gives the non-CFL equal-three-block language. If CFLs were also closed under complement, De Morgan together with union closure would imply intersection closure, contradicting that example. Thus complement and arbitrary intersection fail.
For which machine models does every nondeterministic machine have an equivalent deterministic machine: finite automata, PDAs, TMs, or none?
Select all that apply
Answer & solution
Answer: A, C (no official key was published)
The subset construction converts an NFA to a DFA recognizing the same language. A deterministic TM can explore the finitely branching computation tree breadth-first or by dovetailing, accepting whenever some nondeterministic branch accepts. Thus nondeterministic TMs recognize no additional languages, though complexity can change. NPDAs recognize all CFLs, while DPDAs recognize only deterministic CFLs, a strict subclass. Consequently the universal equivalence holds for finite automata and Turing machines, but not pushdown automata.
M1 calls M1(X+1) when X=0 and otherwise emits WORD X; M2 calls M2(X) when X=0 and otherwise emits WORD X+1. Which loops forever, and give a call.
Answer & solution
Answer: M2 0 (no official key was published)
For M1 0, the recursive invocation receives 1. Its zero test fails, so it emits a word and stops; a nonzero initial argument likewise stops directly. In M2 0, the recursive call receives exactly 0 again, so every expansion repeats the same zero test and invocation with no progress. This causes unbounded expansion until a practical processor limit intervenes. The nonzero WORD branch cannot rescue that call because it is never reached. The analysis assumes expansion-time arithmetic and equality tests on X as intended.
In a conventional two-pass assembler, in which pass is object code generated?
Answer & solution
Answer: Pass2 (no official key was published)
Pass1 establishes layout and collects symbol addresses, including forward definitions not yet known at their first use. Pass2 revisits instructions with those tables available and encodes opcodes, addresses and relocation information into object output. Thus final object generation is assigned to pass2. An implementation could emit some provisional bytes earlier, but that optimization does not change the conventional two-pass division asked here. The answer concerns final object code, not the intermediate source representation.
In a conventional two-pass assembler, in which pass are literals added to the literal table?
Answer & solution
Answer: Pass1 (no official key was published)
When pass1 encounters a literal operand, it records its value and storage needs in the literal table. Literal-pool directives or the end of a section determine placement, which must be included in layout before addresses are finalized. Pass2 can then use the assigned literal addresses while emitting instructions and literal data. Adding the literals only after computing all addresses would require revising the layout. Thus entry into the table is a first-pass activity, distinct from outputting its bytes.
In a conventional two-pass assembler, in which pass is the final listing printed?
Answer & solution
Answer: Pass2 (no official key was published)
A useful final assembly listing combines source statements with assigned addresses and generated machine code, plus diagnostics. Since those final encodings are produced in pass2, the conventional listing is printed there as well. Pass1 may produce temporary listings or diagnostics, but that is not the standard final annotated listing meant in this matching task. The answer therefore follows the output artifact’s dependencies rather than assuming any printed text must wait until pass2 in every implementation.
In a conventional two-pass assembler, in which pass are local-symbol addresses established?
Answer & solution
Answer: Pass1 for defining addresses; pass2 for substituting them into uses (no official key was published)
Pass1 advances the location counter and associates each defined label with its address, thereby resolving the address values stored in the symbol table. Pass2 looks up those values when encoding references, especially forward references. Hence the standard matching answer is pass1 when “address resolution” means establishing the local symbol’s address. If it instead means replacing a symbolic operand at a use site with that address, the operation is pass2. The two meanings are explicitly distinguished because the printed wording does not name the phase’s exact suboperation.
Similar questions1 more → · asked again: GATE 2014 Set 3, Q51
Edges in a forest
Trees & Connectivity
Tap to enlarge
A forest has n vertices and p connected components. How many edges?
Answer & solution
Answer: n−p (no official key was published)
Every component of a forest is a tree. If component i has ni vertices, it has ni−1 edges. Summing over the p components gives Σ(ni−1)=Σni−p=n−p. Isolated vertices count as one-vertex components with zero edges, so the formula handles them automatically. The acyclicity assumption is essential: a graph with cycles can have more edges with the same n and p. The empty forest gives zero with n=p=0.
Quicksort always uses the final element as pivot. Give a worst-case permutation of distinct keys 1, …, n.
Answer & solution
Answer: Ascending order 1, 2, …, n under the standard partition implementation (no official key was published)
On ascending input, the last pivot is the maximum. Partitioning places every other element on one side, creating subproblem sizes n−1 and 0. If the standard partition preserves the ascending order of that remaining region, the same imbalance repeats. Comparisons sum to (n−1)+(n−2)+…+1=n(n−1)/2, which is Θ(n²). Reverse order is another common worst-case input. The statement concerns ordinary end-pivot partitioning, not a modified algorithm that deliberately rearranges or selects pivots differently after inspecting the data.
Which page-replacement policy can have more faults when memory size increases?
Answer & solution
Answer: FIFO: Belady’s anomaly (no official key was published)
FIFO evicts the page loaded earliest, not necessarily the least useful page. With different frame counts, the order of subsequent evictions can change so that the larger memory performs worse. For example the reference string 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 has nine FIFO faults with three frames but ten with four. LRU and optimal replacement have the stack-inclusion property and avoid this anomaly. The question asks for a policy that sometimes exhibits it, not a claim that adding frames always hurts FIFO.
Explain when addition in fixed-width two’s-complement arithmetic overflows, and why carry out of the most significant bit is not sufficient.
Answer & solution
Answer: Overflow iff equal-sign operands produce the opposite-sign result; V = carry into sign bit XOR carry out. (no official key was published)
For a w-bit two’s-complement word the representable interval is −2w−1 through 2w−1−1. Hardware retains the low w bits of the mathematical sum. Overflow means the mathematical signed sum lies outside this interval, not merely that an unsigned carry was discarded.
Let a,b be the operand sign bits and s the retained result sign bit. The overflow flag is V=(¬a∧¬b∧s)∨(a∧b∧¬s). Two nonnegative numbers overflow only by producing a sign bit of 1; two negative numbers overflow only by producing a sign bit of 0. Opposite-sign operands cannot overflow: their sum lies between the operands and hence within the representable interval.
Equivalently, if c_in is the carry into the sign-bit adder and c_out its outgoing carry, V=c_in XOR c_out. This follows by considering the sign-bit full-adder cases: for equal operand signs an incorrect result sign occurs precisely when these carries differ; for unequal signs they agree.
For four bits, 0111+0001=1000 represents 7+1 as −8: overflow occurs despite no outgoing carry. Conversely 1111+0001=0000 with carry 1 represents −1+1=0 correctly: carry occurs without overflow. Finally 1000+1111=0111 with carry 1 is −8+(−1), which really does overflow. These examples separate the unsigned carry flag from the signed overflow flag.
Design a three-input priority encoder with A>B>C using 4:1 multiplexers. Output X1X0 identifies the highest-priority active input, and is 00 if none is active.
Answer & solution
Answer: Choose A→11, B→10, C→01. Use two 4:1 MUXes, selects A,B; X1 inputs (0,1,1,1), X0 inputs (C,0,1,1). (no official key was published)
The statement does not assign binary labels to A, B, C, so explicitly choose A→11, B→10 and C→01, reserving 00 for no request. Any distinct nonzero assignment is valid if stated and implemented consistently.
The compressed truth table is: A B C | X1 X0 1 – – | 1 1 0 1 – | 1 0 0 0 1 | 0 1 0 0 0 | 0 0 A higher-priority 1 hides all lower-priority inputs. The resulting functions are X1=A∨B and X0=A∨(¬B∧C).
For both 4:1 multiplexers use select S1=A, S0=B, with D0,D1,D2,D3 selected by 00,01,10,11 respectively. Evaluate each function at these four selector values:
D0 D1 D2 D3
MUX for output X1: 0 1 1 1
MUX for output X0: C 0 1 1
Wiring diagram
A,B ──selects──>[4:1 MUX, data 0,1,1,1]──>X1
A,B ──selects──>[4:1 MUX, data C,0,1,1]──>X0
Tie 0 and 1 inputs to valid logic rails and enable both multiplexers. No inverter is needed in this realization. For example A=0,B=1,C=1 selects D1 and gives 10, correctly ignoring C. A=1 selects either D2 or D3 and always gives 11.
Design a 3-bit counter with D flip-flops such that at most one flip-flop changes between consecutive states.
Answer & solution
Answer: Use cyclic Gray sequence 000,001,011,010,110,111,101,100; D2=Q2Q0+Q1¬Q0, D1=Q1¬Q0+¬Q2Q0, D0=Q2Q1+¬Q2¬Q1. (no official key was published)
Use all eight states in the reflected Gray-code order, including a one-bit wraparound: 000 → 001 → 011 → 010 → 110 → 111 → 101 → 100 → 000. A binary counter would fail at transitions such as 011→100, where three bits change. In this Gray cycle every adjacent pair, including 100→000, differs in exactly one bit.
For a D flip-flop, next Q equals current D at the active clock edge. Thus the state table directly gives the needed excitation table: Q2Q1Q0 | D2D1D0 000 | 001 001 | 011 010 | 110 011 | 010 100 | 000 101 | 100 110 | 111 111 | 101
Grouping the 1s of each next-state column on a three-variable Karnaugh map gives: D2=(Q2∧Q0)∨(Q1∧¬Q0) D1=(Q1∧¬Q0)∨(¬Q2∧Q0) D0=(Q2∧Q1)∨(¬Q2∧¬Q1).
One common clock drives all three DFFs; clear inputs initialize Q2Q1Q0=000. Feedback connects each Q to the combinational network. All states belong to the cycle, so there are no unused lockout states. The guarantee concerns stable states at clock edges, assuming setup/hold and propagation constraints; glitches within combinational logic are not extra counter states.
Main memory takes 500 ns and cache 50 ns. Requests are 80% reads and 20% writes; read hit ratio is 0.9. Writes update cache and main memory simultaneously. Find average access time.
Answer & solution
Answer: 180 ns for sequential cache lookup then main-memory read on a miss; 176 ns if miss latency already includes lookup or reads begin in parallel. (no official key was published)
Separate access types before averaging. A read hit costs 50 ns. Under the usual serial lookup model, a read miss first spends 50 ns discovering the miss and then 500 ns accessing main memory, for 550 ns. Therefore E[read]=0.9(50)+0.1(550)=100 ns.
The statement explicitly says write-through updates are simultaneous, so the write completes when the slower device completes: E[write]=max(50,500)=500 ns. Adding 50+500 for a write would contradict this parallel-update stipulation. No write buffer or early processor release is stated.
Weighting by request mix gives E[access]=0.8(100)+0.2(500)=180 ns. Equivalently, the overall probabilities are 0.72 read hit, 0.08 read miss and 0.20 write, giving 0.72(50)+0.08(550)+0.20(500).
There is a timing-model ambiguity: if main-memory access starts in parallel with cache lookup, or a quoted 500 ns miss time is interpreted as total latency including lookup, then a miss costs 500 rather than 550 ns. That model gives E[read]=95 ns and overall 176 ns. The text establishes simultaneous writes but does not explicitly establish read overlap; 180 ns is the serial-read result, while 176 ns requires the alternative convention. This is effective time per processor memory request, not a change to the physical 500 ns main-memory device latency.
Three devices A,B,C use interrupt request lines INTR1>INTR2>INTR3. Draw priority logic with an interrupt mask register so A>B>C.
Answer & solution
Answer: Gate each request with its mask enable and assign A to INTR1, B to INTR2, C to INTR3; optional explicit priority gating suppresses lower requests. (no official key was published)
Define mask-register bits MA,MB,MC with 1 meaning masked (disabled). Let RA,RB,RC be pending request signals. Form eligible requests a=RA∧¬MA, b=RB∧¬MB, c=RC∧¬MC.
Schematic using the processor’s specified priority mechanism:
RA ──AND(¬MA)──> INTR1 [highest]
RB ──AND(¬MB)──> INTR2
RC ──AND(¬MC)──> INTR3 [lowest]
↑ three-bit interrupt mask register
Because the processor already prioritizes the three lines, this wiring suffices. If an explicit one-hot external priority network is desired, use instead:
INTR1=a
INTR2=b∧¬a
INTR3=c∧¬a∧¬b.
These equations are also a gate-level schematic: invert a and b as needed and AND the shown eligible inputs. They ensure that only the highest-priority eligible device is presented at a time.
Priority must depend on eligible requests, not raw requests: a masked A must not suppress an unmasked B or C. With all requests asserted and masks 000, A wins; with MA=1 and others 0, B wins; with MA=MB=1, C wins. With every mask bit set, no interrupt is raised.
Assume a device holds its request until acknowledged, or use pending-request latches before these gates, so a lower request survives service of a higher one. Service clears only the acknowledged source’s pending request. Mask-register writes are controlled by the processor. If the hardware convention defines 1 as enabled, replace each ¬M by M; the priority relation itself is unchanged.
A byte-addressed processor has 20 address bits (1 MiB). It needs 256 KiB RAM, 256 KiB EPROM, 16 memory-mapped I/O devices and 1 KiB EERAM. Available chips are printed as RAM 6K×8 at 140 ns, EPROM 256K×8 at 150 ns, and EERAM 256×8 at 500 ns read/3 μs write. Design a memory map minimizing decoding complexity and show its decoding logic.
Answer & solution
Answer: Map RAM 00000–3FFFF, EPROM 40000–7FFFF, EERAM 80000–803FF, I/O C0000–C000F. Literal 6K chips can be used as 64 banks of 4K; a conditional 64K-chip interpretation needs four banks. (no official key was published)
Use K=1024 and hexadecimal byte addresses. The following aligned allocation permits a top-level 2-to-4 decoder on A19,A18: 00: 00000–3FFFF, 256 KiB RAM 01: 40000–7FFFF, 256 KiB EPROM 10: 80000–803FF, 1 KiB EERAM (remaining quadrant reserved) 11: C0000–C000F, 16 one-byte I/O registers (remaining quadrant reserved). The I/O allocation assumes one addressed register per device; a device with multiple registers needs a correspondingly larger aligned subrange. Reset-vector placement is not specified.
Let R=¬A19∧¬A18, P=¬A19∧A18, E=A19∧¬A18, I=A19∧A18. These are active-high bank selections. EPROM has CS=P, internal address A17..A0 and output enable qualified by memory read; it is not written during normal operation.
The paper really print 6K×8 RAM, not 64K×8. A simple literal implementation uses 64 such chips, exposing only their lowest 4 KiB. Connect chip address A11..A0 to processor A11..A0 and hold its extra address bit at zero. A 6-to-64 decoder on A17..A12, enabled by R, selects exactly one chip. CS_RAM[j]=R∧(A17..A12=j), 0≤j<64. This deliberately sacrifices 2 KiB per chip to obtain regular power-of-two decoding. It implements all 256 KiB without assuming an undocumented capacity. The capacity lower bound is ceil(256/6)=43 chips; packing 42 full chips plus 4 KiB of a final chip needs non-power-of-two block selection/address translation, so minimum chip count and simplest decoder are different objectives.
For EERAM form E_exact=E∧(A17..A10=0). A 2-to-4 decoder on A9,A8 selects four 256-byte chips; connect A7..A0 to each. CS_E[k]=E_exact∧(A9A8=k), 0≤k<4. For I/O form I_exact=I∧(A17..A4=0); decode A3..A0 into 16 selects. Qualify all reads/writes with the processor’s memory-cycle control, since these are memory-mapped devices. An 8085-style IO/M signal is low for these cycles. Device-specific active-low chip selects are the complements of the active-high equations.
A shared 8-bit data bus serves selected devices only. For a multiplexed address/data bus, latch the low address using ALE first.
If 6K was intended to be 64K, an explicitly corrected alternative replaces the RAM arrangement by four 64K×8 chips selected by A17,A16, with A15..A0 internal. This common four-chip design must not be presented as using the literal printed components. Partial decoding can omit reserved-region zero tests but creates address aliases; the exact map above avoids them.
A byte-addressed processor has 20 address bits (1 MiB). It needs 256 KiB RAM, 256 KiB EPROM, 16 memory-mapped I/O devices and 1 KiB EERAM. Available chips are printed as RAM 6K×8 at 140 ns, EPROM 256K×8 at 150 ns, and EERAM 256×8 at 500 ns read/3 μs write. The processor clock is printed as 12.5 mHz and a memory transfer allows two clocks. Assuming 8085-like control signals, design extra EERAM interface logic.
Answer & solution
Answer: Literal 12.5 mHz needs no speed wait states. If intended 12.5 MHz, add 5 read wait clocks or 36 write wait clocks in the stated two-clock timing model. (no official key was published)
The printed unit matters: lowercase mHz means millihertz. At literal 12.5 mHz, f=0.0125 Hz, T=80 seconds and two clocks provide 160 seconds. Neither a 500 ns read nor a 3 μs write needs any speed-extension wait states. The extraordinary slowness strongly suggests a unit error, but the paper prints mHz and an official correction is unavailable.
For the conventional intended interpretation 12.5 MHz, T=80 ns and the specified ordinary memory interval is 2T=160 ns. RAM 140 ns and EPROM 150 ns fit this idealized interval; EERAM does not. With W additional whole clocks: Read: (2+W)80≥500 ⇒ W≥4.25 ⇒ W_read=5. Write: (2+W)80≥3000 ⇒ W≥35.5 ⇒ W_write=36. Total durations are 7 clocks=560 ns and 38 clocks=3040 ns. Rounding down would violate the specified device timing.
Interface block diagram
latched address→EERAM decoder→SEL_E SEL_E + memory RD/WR + cycle-start→operation latch / wait controller clock→6-bit elapsed-clock counter→threshold comparators→READY latched address + data bus + held RD/WR→four EERAM chips. READY is high for ordinary accesses. At the beginning of a selected EERAM transfer, latch read versus write, clear the counter and assert READY low before its processor sampling point. Hold address, chip select and the applicable read/write strobe stable as the bus is stretched. At the release sampling point choose READY high only when completion will occur no earlier than 7 clocks after transfer start for a read or 38 for a write. End-of-cycle resets the controller. Equivalently, count five or 36 inserted wait clocks after the nominal two-clock interval. Gate initialization with a single cycle-start pulse so held strobes do not repeatedly reset the counter. A six-bit counter accommodates the longest interval.
These counts follow the problem’s simplified timing model. Actual 8085 READY sampling, decoder delay, setup/hold margins, write-pulse width and whether 3 μs denotes strobe time or internal programming time require the particular EERAM/processor data sheets. If writes are internally timed, latch the write data/address and wait on a busy signal rather than blindly holding a programming pulse. No exact pin waveform or additional nanosecond margin can be inferred from the supplied numbers.
The printed function initializes F1←1, tests n=1 and assigns F←3 in that case; otherwise it repeats i=1..n, setting C←0, incrementing C once for each j=1..F(n−1), then setting F1←F1*C. A final F←F1 appears after the loop, with ambiguous if/else grouping. n is positive. Derive a recurrence for the returned value F(n).
Answer & solution
Answer: Intended base-case-preserving reading: F(1)=3, F(n)=F(n−1)^n for n>1. Literal unconditional final assignment instead gives F(n)=1 for all n. (no official key was published)
First distinguish the function’s returned numerical value from its running time. In one outer iteration the inner loop increments C exactly F(n−1) times, so C=F(n−1). Starting from F1=1, the outer loop multiplies by that same value n times. Hence for n>1 the returned value is F(n)=∏[i=1..n] F(n−1)=[F(n−1)]n. The base is F(1)=3 if the base-case assignment is returned without being overwritten.
A block-explicit rendition of this intended reading is:
function F(n):
if n=1 then return 3;
F1:=1;
for i:=1 to n do begin
C:=0;
for j:=1 to F(n−1) do C:=C+1;
F1:=F1*C
end;
return F1.
This explains why neither n·F(n−1) (a sum) nor a runtime recurrence answers the value question. For instance F(2)=3²=9 and F(3)=9³=729.
The paper places a final F=F1 after the if/else loop without clearly enclosing it in the else branch. Under a literal Pascal-like reading with that assignment executed unconditionally, n=1 first sets F=3 but then overwrites it with the initial F1=1. The recurrence becomes F(1)=1, F(n)=F(n−1)n and all values are 1. The intended nontrivial recurrence therefore requires treating the final assignment as part of the else computation or returning immediately from the n=1 case.
The printed function initializes F1←1, tests n=1 and assigns F←3 in that case; otherwise it repeats i=1..n, setting C←0, incrementing C once for each j=1..F(n−1), then setting F1←F1*C. A final F←F1 appears after the loop, with ambiguous if/else grouping. n is positive. Solve the recurrence for a closed form.
Answer & solution
Answer: Under intended base F(1)=3, F(n)=3^(n!). Under unconditional final-assignment reading, F(n)=1. (no official key was published)
Using the base-case-preserving reading, F(1)=3 and F(n)=[F(n−1)]n for n≥2. All values are positive, so define an=log₃F(n). Exponentiation becomes multiplication: a1=1 and an=n an−1. Repeated substitution gives an=n(n−1)…2·1=n!, hence F(n)=3n!.
An induction verifies the expression without logarithms. At n=1, 31!=3 equals the base value. If F(n−1)=3^((n−1)!), then F(n)=(3^((n−1)!))n=3^(n·(n−1)!)=3n!. This completes the proof for every positive integer n. Checks at n=2 and n=3 give 9 and 729; n=4 yields 324=282429536481. Confusing 3n! with (3n)! or with 3n would lose the repeated multiplication of exponents.
This formula describes the function’s value under unbounded-integer arithmetic, not the execution time or the size of a machine integer. The return value grows much faster than an ordinary exponential, and practical fixed-width implementations overflow quickly.
The source ambiguity remains material here. If the final F=F1 executes even after n=1 assigns F=3, the true base is 1. Induction on the same recurrence then gives F(n)=1 for all positive n. Thus 3n! is an explicitly conditional intended solution; 1 is the literal unconditional-assignment solution. No verified official key resolves that control-flow formatting.
T is a depth-first tree of an undirected graph G. Only a parent array P is given, with the root its own parent. For non-tree edge (u,v), give Pascal-like code printing its unique cycle after addition to T, in time proportional to cycle length.
Answer & solution
Answer: Climb from both endpoints in parallel until one reaches the other original endpoint; print the successful parent path and the added closing edge. (no official key was published)
In an undirected DFS tree, every non-tree edge joins an ancestor and a descendant. To see why, suppose an edge joined distinct DFS subtrees: while its first endpoint’s subtree was explored, the still-undiscovered other endpoint would be reached by that edge and placed in the same subtree, a contradiction. Thus the tree path between u and v is a single upward parent chain from the descendant. Which endpoint is deeper is not given, so climbing just one chosen endpoint can waste time or stick at the root.
Climb both parent chains in lockstep, saving both traversals, and stop as soon as one reaches the other original endpoint:
procedure PrintCycle(u,v);
begin
a:=u; b:=v; lenA:=1; lenB:=1;
pathA[1]:=u; pathB[1]:=v;
while (a<>v) and (b<>u) do begin
a:=P[a]; lenA:=lenA+1; pathA[lenA]:=a;
b:=P[b]; lenB:=lenB+1; pathB[lenB]:=b
end;
if a=v then begin
for k:=1 to lenA do write(pathA[k]);
write(u)
end else begin
for k:=1 to lenB do write(pathB[k]);
write(v)
end
end.
Assume arrays can hold the tree height plus one and append/write are constant-time operations. Storage can instead be growable linked lists with constant-time append. Arrays need no initial clearing; only positions written above are read.
Let the ancestor–descendant distance be d. The descendant walk reaches the ancestor after exactly d rounds, even if the other walk has already reached the root and is repeating its self-parent. The algorithm performs at most 2d parent moves and prints d+1 distinct cycle vertices plus the repeated start: Θ(d+1), proportional to the cycle’s d+1 edges, with O(d+1) temporary storage. For example a parent chain 7→5→2 and new edge (2,7) prints 7,5,2,7.
No full-tree traversal, depth computation or global visited-array clearing is required. The argument assumes the usual simple undirected graph; a self-loop can be handled immediately by printing u,u. For an arbitrary spanning tree the ancestor property is false, so this algorithm is specifically justified by the DFS premise.
Represent S⊆{1,…,n} so MEMBER, FIND-ONE, ADD and DELETE each take worst-case constant time independent of |S|. Give pictorial examples and routines, and state initialization assumptions. Give MEMBER(x) using the common representation.
Answer & solution
Answer: Use inverse-position array: MEMBER(x) returns pos[x]≠0. (no official key was published)
Use two length-n arrays: dense[1..m] stores precisely the current set in arbitrary order; pos[x] is x’s dense position if present, otherwise 0. The invariant is pos[dense[j]]=j for 1≤j≤m, and pos[x]=0 exactly for absent elements. Initialize m:=0 and pos[1..n]:=0, which takes Θ(n) time once. dense need not be initialized because only its active prefix is read. Space is Θ(n). Array indexing, integer comparison and assignment are constant-time in the word-RAM model, with words large enough for 0..n. Operations assume 1≤x≤n or reject out-of-range x before indexing.
m=3; arrows are 2→1, 5→2, 7→3. A plain Boolean array gives easy membership but could require Θ(n) scanning to FIND-ONE; the dense prefix supplies an immediate element. Set order is deliberately not preserved, which enables constant-time deletion.
MEMBER(x):
if x<1 or x>n then return false;
return pos[x]<>0.
The initialization and update invariant make a nonzero position an exact certificate of membership. In the pictured set MEMBER(5)=true because pos[5]=2, whereas MEMBER(4)=false because pos[4]=0. The routine performs only a fixed number of comparisons and one array access, so its worst-case cost is O(1), regardless of the number of stored elements. All later ADD and DELETE operations must preserve the inverse links; membership must not read uninitialized pos entries. The stipulated one-time Θ(n) initialization is not being hidden as an O(1) operation.
Represent S⊆{1,…,n} so MEMBER, FIND-ONE, ADD and DELETE each take worst-case constant time independent of |S|. Give pictorial examples and routines, and state initialization assumptions. Give FIND-ONE(S) using the common representation.
Answer & solution
Answer: If m=0 return EMPTY; otherwise return dense[1]. (no official key was published)
Use two length-n arrays: dense[1..m] stores precisely the current set in arbitrary order; pos[x] is x’s dense position if present, otherwise 0. The invariant is pos[dense[j]]=j for 1≤j≤m, and pos[x]=0 exactly for absent elements. Initialize m:=0 and pos[1..n]:=0, which takes Θ(n) time once. dense need not be initialized because only its active prefix is read. Space is Θ(n). Array indexing, integer comparison and assignment are constant-time in the word-RAM model, with words large enough for 0..n. Operations assume 1≤x≤n or reject out-of-range x before indexing.
m=3; arrows are 2→1, 5→2, 7→3. A plain Boolean array gives easy membership but could require Θ(n) scanning to FIND-ONE; the dense prefix supplies an immediate element. Set order is deliberately not preserved, which enables constant-time deletion.
FIND-ONE():
if m=0 then return EMPTY;
return dense[1].
EMPTY is a distinguished failure result, for example 0 because the universe is 1..n. In the displayed example the answer is 2. Returning dense[m]=7 would be equally valid; the question does not require the minimum, maximum or any particular order.
The dense-prefix invariant says every entry between 1 and m is a member, and m=0 exactly characterizes the empty set. Hence the result is valid when nonempty and the routine never reads an inactive or uninitialized cell. It requires one test and at most one array lookup, yielding worst-case O(1). Returning a remembered arbitrary element without maintaining its validity on DELETE would not suffice; the companion deletion routine keeps the prefix compact and therefore maintains this guarantee.
Represent S⊆{1,…,n} so MEMBER, FIND-ONE, ADD and DELETE each take worst-case constant time independent of |S|. Give pictorial examples and routines, and state initialization assumptions. Give ADD(x) using the common representation.
Answer & solution
Answer: If pos[x]=0, append x to dense and set pos[x] to the new m; otherwise do nothing. (no official key was published)
Use two length-n arrays: dense[1..m] stores precisely the current set in arbitrary order; pos[x] is x’s dense position if present, otherwise 0. The invariant is pos[dense[j]]=j for 1≤j≤m, and pos[x]=0 exactly for absent elements. Initialize m:=0 and pos[1..n]:=0, which takes Θ(n) time once. dense need not be initialized because only its active prefix is read. Space is Θ(n). Array indexing, integer comparison and assignment are constant-time in the word-RAM model, with words large enough for 0..n. Operations assume 1≤x≤n or reject out-of-range x before indexing.
m=3; arrows are 2→1, 5→2, 7→3. A plain Boolean array gives easy membership but could require Θ(n) scanning to FIND-ONE; the dense prefix supplies an immediate element. Set order is deliberately not preserved, which enables constant-time deletion.
ADD(x):
require 1<=x<=n;
if pos[x]=0 then begin
m:=m+1;
dense[m]:=x;
pos[x]:=m
end.
Sets do not contain duplicate elements, so the initial presence test is essential. If x is already present, returning without changes preserves the representation. If it is absent, adding a new dense entry and its inverse position establishes the invariant for x without changing any existing entry. Since an absent x exists in a universe of size n, m<n before the increment; the append cannot exceed capacity.
For example ADD(4) changes dense [2,5,7] to [2,5,7,4], changes pos[4] from 0 to 4, and changes m from 3 to 4; all other positions stay fixed. ADD(5) thereafter changes nothing. There is no search, shifting or allocation during an operation because storage was reserved at initialization. The fixed number of reads/writes gives worst-case O(1), not merely amortized O(1).
Represent S⊆{1,…,n} so MEMBER, FIND-ONE, ADD and DELETE each take worst-case constant time independent of |S|. Give pictorial examples and routines, and state initialization assumptions. Give DELETE(x) using the common representation.
Answer & solution
Answer: Replace x in dense by its last element, repair that element’s inverse position, shorten m and clear pos[x]. (no official key was published)
Use two length-n arrays: dense[1..m] stores precisely the current set in arbitrary order; pos[x] is x’s dense position if present, otherwise 0. The invariant is pos[dense[j]]=j for 1≤j≤m, and pos[x]=0 exactly for absent elements. Initialize m:=0 and pos[1..n]:=0, which takes Θ(n) time once. dense need not be initialized because only its active prefix is read. Space is Θ(n). Array indexing, integer comparison and assignment are constant-time in the word-RAM model, with words large enough for 0..n. Operations assume 1≤x≤n or reject out-of-range x before indexing.
m=3; arrows are 2→1, 5→2, 7→3. A plain Boolean array gives easy membership but could require Θ(n) scanning to FIND-ONE; the dense prefix supplies an immediate element. Set order is deliberately not preserved, which enables constant-time deletion.
DELETE(x):
require 1<=x<=n;
k:=pos[x];
if k=0 then return;
y:=dense[m];
dense[k]:=y;
pos[y]:=k;
m:=m-1;
pos[x]:=0.
The position array directly locates x, avoiding a search. Moving the final member into x’s slot avoids shifting the remaining members. Updating pos[y] repairs the one inverse link affected by the move. The shortened prefix contains all old members except x, and clearing pos[x] makes future membership queries false.
Example DELETE(5) on dense [2,5,7] moves 7 from position 3 to position 2. The new active prefix is [2,7], m=2, pos[7]=2 and pos[5]=0. The old dense[3] value is irrelevant because it lies outside the prefix. If x already is the final element, then y=x; the self-assignment is harmless and the last assignment pos[x]:=0 is essential. The same code safely empties a singleton set. Deleting an absent element leaves everything unchanged. Only a fixed number of assignments and lookups are performed, proving worst-case O(1).
For P(A[i]), where P has an integer formal parameter, a proposed implementation creates local z, sets z:=A[i], runs P’s body using z, then writes A[i]:=z. Identify the parameter-passing mechanism, judge correctness and give a small correction.
Answer & solution
Answer: Call by value-result (copy-in/copy-out); capture the actual argument’s location at call time and copy back to that same location. (no official key was published)
The separate local variable receives the initial value and is copied back on return, so the intended mechanism is call by value-result, also called copy-in/copy-out. It is not call by reference, which uses the actual storage throughout execution, nor call by value, which never copies a final value back. Call by name re-evaluates an actual-argument expression in its caller environment on each use rather than using one private copied value.
The proposed copy-back re-evaluates A[i]. If the caller’s index changes during execution, it can select a different element from the one used at entry. For example initially i=2 and A[2]=10. Suppose the body changes the caller-visible index to 3 through a global reference and leaves the formal’s local value as 99. Re-evaluating A[i] on exit writes A[3]=99 instead of copying back into A[2]. An implementation must preserve the original actual location under the usual location-fixed value-result convention.
Small correction
p:=address_of(A[i]); {evaluate actual location in caller environment once}
z:=value_at(p); {copy in}
execute P body with every occurrence of its formal bound to z;
value_at(p):=z; {copy out to saved location}
If A is known not to change identity or base address, saving k:=i and using A[k] for both transfers is sufficient; saving the address is the general correction. Normal return is assumed, and with one parameter there is no multiple-copy-back ordering issue.
There is also a naming issue in the printed wording: P’s formal is named i, while the actual A[i] contains the caller’s i. They are different bindings. The body must substitute z for the formal, not literally search for the caller expression A[i] in the body. Merely assigning the formal does not itself change the caller’s separate index; the failure requires that the caller-visible index or array location can otherwise change. If that cannot happen, the original sequence happens to produce the right result.
For the following lexically scoped Pascal-like skeleton, draw activation records and the display just after the procedures invoked at labels x and y begin. Distinguish the two A declarations. program Test; procedure A; {outer A} procedure B; procedure A; {inner A} begin ... end; begin y: A; end; begin B; end; begin x: A; end.
Answer & solution
Answer: At x: Test→A_outer with display [Test,A_outer]. At y: Test→A_outer→B→A_inner with display [Test,A_outer,B,A_inner]. (no official key was published)
Assign lexical levels Test=0, A_outer=1, B=2 and A_inner=3. The declarations, not the dynamic call order, determine these levels. The call x:A in Test resolves to A_outer. The call y:A in B resolves to the nearest enclosing declaration of A, namely B’s own nested A_inner; it does not recursively invoke A_outer.
Immediately after x’s callee starts, before A_outer executes B, the stack and display are: Stack bottom→top: [Test frame: caller/runtime link] [A_outer frame: dynamic link→Test; static link→Test; return continuation→after x:A; saved previous display[1]] Display: D[0]→Test, D[1]→A_outer. D[2] and D[3] have no active corresponding frames and are undefined/unused. Do not invent B or A_inner frames at this first instant.
A_outer then calls B, whose body calls A_inner at y. Immediately after y’s callee starts:
Stack bottom→top:
[Test]
[A_outer: DL→Test, SL→Test, return→after x:A, saved old D[1]]
[B: DL→A_outer, SL→A_outer, return→after B call, saved old D[2]]
[A_inner: DL→B, SL→B, return→after y:A, saved old D[3]]
Display diagram:
D[0] ──> Test
D[1] ──> A_outer
D[2] ──> B
D[3] ──> A_inner
The dynamic link names the calling activation, while the static link names the activation of the lexical parent. They happen to coincide throughout this simple nested call chain; their meanings remain different. A display-based implementation can replace static-chain access entirely, so the static links shown are explanatory rather than required additional storage. On entry at lexical level ℓ, save old D[ℓ] in the frame and set D[ℓ] to that frame; on return restore the saved value. Return addresses, saved registers and local-storage slots are conventional frame fields, but no particular byte sizes or actual locals are specified. The omitted body of A_inner has not yet executed at the requested second snapshot, so no additional calls or frames may be assumed.
Add syntax-directed semantic rules to the ends of productions, without changing the grammar, so each identifier gets its declared type in the symbol table: D → T L ; T → int | real L → L , id | id
Answer & solution
Answer: Collect identifier-entry references in synthesized L.entries; assign T.type to them at D → T L ;. (no official key was published)
A synthesized list of symbol-table references solves the end-only restriction without needing to pass an inherited type into L before parsing it. Give T a synthesized attribute type and L a synthesized attribute entries. The lexical token id.entry is a reference to that identifier's symbol-table entry (or the declaration entry created for it in the current scope).
Attach precisely these actions at production ends: D → T L ; { for each p in L.entries: p.type := T.type } T → int { T.type := integer } T → real { T.type := real } L₀ → L₁ , id { L₀.entries := append(L₁.entries, id.entry) } L → id { L.entries := [id.entry] }
The subscripts distinguish the two occurrences of L; they are attribute notation, not new grammar symbols. append constructs or extends a list of references, not copies of symbol-table records. On reduction of L → id, the one-element list is available. Each reduction of the recursive production adds one further identifier. By induction on the list length, the final L.entries contains exactly the identifiers in this declaration. At the D reduction both T.type and the complete list are available, so every listed entry receives the same type.
For real x,y,z;, T.type becomes real, the L lists successively become [x], [x,y], [x,y,z], and the final action assigns real to x, y, and z. All actions are at the right ends, and the original productions are untouched. Redeclaration detection and nested-scope lookup are separate symbol-table concerns. With a tail pointer or linked-list concatenation, building and processing a k-identifier list costs O(k) time and O(k) references.
Generate three-address quadruples in compiler generation order for (a+b) > (c+d) or a > c and b < d. Use usual precedence; partial/short-circuit evaluation is forbidden.
Answer & solution
Answer: Seven quadruples, ending in t7 = t3 or (t4 and t5); all operands are evaluated. (no official key was published)
The parse is ((a+b)>(c+d)) or ((a>c) and (b<d)), because arithmetic binds before comparison and and binds before or. Generate code in a left-to-right postorder traversal, storing each intermediate value in a fresh temporary. A quadruple is (operator, argument1, argument2, result):
Thus t1=a+b, t2=c+d, and t3 is the first Boolean comparison. Independently t4 and t5 compute both comparisons in the second arm; t6 combines them, and t7 is the final Boolean value. All comparison and Boolean results are represented as Boolean values (or conventional 0/1 encodings), not jump destinations. Every operation executes even if t3 is already true or t4 is false. A jump-based short-circuit sequence would violate the explicit prohibition on partial evaluation.
There are seven internal nodes in the expression tree and one quadruple per node. Temporary names and the order of independent child computations can differ in valid implementations; this is one conventional compiler generation order, not a uniquely mandated register allocation.
Draw the precedence graph for this concurrent program. Within begin/end statements are sequential; parbegin/parend runs its components concurrently and joins them: S1; parbegin begin S2; S4 end; begin S3; parbegin S5; begin S6; S8 end parend end; S7 parend; S9
Answer & solution
Answer: Edges: 1→2,3,7; 2→4; 3→5,6; 6→8; 4,5,8,7→9. (no official key was published)
S1 executes before the outer fork. Its three branches start with S2, S3, and S7. In the first branch S2 precedes S4. In the second branch S3 precedes a nested fork: S5 runs in parallel with the sequential pair S6 then S8. The outer join waits for S4, both S5 and S8, and S7 before permitting S9.
The precedence graph (arrows are immediate dependencies) is:
Its exact edge set is {(S1,S2),(S1,S3),(S1,S7),(S2,S4),(S3,S5),(S3,S6),(S6,S8),(S4,S9),(S5,S9),(S8,S9),(S7,S9)}. This is a transitive reduction: edges such as S1→S9 are implied and need not be drawn. It uses only statement vertices; explicit fork/join vertices would be an equivalent representation.
Do not add S4→S3, S5→S6, or S8→S7: textual order among separate parallel branches does not force execution order. Conversely, S9 must not start after just one branch finishes. The structure imposes control dependencies only; no extra read/write data dependencies are supplied.
With working-set window Δ=4, process the page references c c d b c e c e a d. Initially W(0)={a,d,e}; the latest initial references are a at t=0, d at t=−1, and e at t=−2. Find each working set, the total faults, and average frames used.
Answer & solution
Answer: 5 page faults; average |W(t)| for t=1…10 is 3.2 frames. (no official key was published)
Use the standard discrete-reference window W(t) containing pages referenced at times t−3 through t, i.e. the last four references including the current one. Immediately before reference t, resident pages are W(t−1); a fault occurs exactly when the requested page is absent there. After serving the request, remove pages no longer in the new window. The specified W(0) fixes initial residency; any unspecified t=−3 reference expires at t=1 and does not affect the trace.
t page W(t) size fault?
0 a {a,d,e} 3 initial state
1 c {a,c,d,e} 4 yes
2 c {a,c,d} 3 no
3 d {a,c,d} 3 no
4 b {b,c,d} 3 yes
5 c {b,c,d} 3 no
6 e {b,c,d,e} 4 yes
7 c {b,c,e} 3 no
8 e {c,e} 2 no
9 a {a,c,e} 3 yes
10 d {a,c,d,e} 4 yes
For example at t=6 the four references are d,b,c,e, whereas at t=8 they are c,e,c,e, using only two distinct frames. The last d reference at t=3 has expired by t=7, so d faults again at t=10. Fault times are 1,4,6,9,10: five faults.
The frame sum over the ten requested-reference instants is 4+3+3+3+3+4+3+2+3+4=32, so the conventional post-reference average is 32/10=3.2 frames. If one instead includes the supplied initial snapshot as an eleventh sample, the average is 35/11; if averaging pre-reference residency W(0)…W(9), it is 31/10. These are different sampling conventions, not different working-set traces. The reported 3.2 explicitly averages W(1)…W(10).
Give a one-line answer: how is redundancy reduced in the hierarchical database model?
Answer & solution
Answer: Store shared parent information once above its children; systems supporting logical/virtual child links can reference a shared record rather than duplicate it. (no official key was published)
One-line answer: Store shared parent information once above its children; systems supporting logical/virtual child links can reference a shared record rather than duplicate it.
Why this works: A parent such as a department need not have its name and address copied into every employee child. A pure tree, however, gives each child one parent and does not automatically remove duplication for many-to-many relationships. Logical relationships or virtual/pointer records are implementation extensions, not a universal property of every hierarchical model.
Redundancy means repeatedly storing the same fact, not merely having repeated key values. Keys or links may legitimately recur to express relationships. These are design mechanisms rather than a claim that the model makes every possible database free of redundancy.
Give a one-line answer: how is redundancy reduced in the network database model?
Answer & solution
Answer: Store an entity record once and represent its multiple owner/member relationships by links instead of repeating its data. (no official key was published)
One-line answer: Store an entity record once and represent its multiple owner/member relationships by links instead of repeating its data.
Why this works: A network model allows a record to participate in multiple set relationships. A course shared by several student relationships can be stored as one course record with relationship links or connector records, rather than duplicating the course attributes for each student. The relationships still occupy space; the reduction is in repeated entity facts.
Redundancy means repeatedly storing the same fact, not merely having repeated key values. Keys or links may legitimately recur to express relationships. These are design mechanisms rather than a claim that the model makes every possible database free of redundancy.
Give a one-line answer: how is redundancy reduced in the relational database model?
Answer & solution
Answer: Normalize relations using their dependencies, decomposing repeated facts into linked relations with keys. (no official key was published)
One-line answer: Normalize relations using their dependencies, decomposing repeated facts into linked relations with keys.
Why this works: For example, a relation Employee(emp,dept,deptName) repeats deptName for every employee in a department when dept→deptName. Decompose it into Employee(emp,dept) and Department(dept,deptName), with dept as the latter key. The department fact is then stored once. Decomposition should preserve information through a lossless join, and dependency preservation is desirable. Being relational alone does not guarantee a normalized schema.
Redundancy means repeatedly storing the same fact, not merely having repeated key values. Keys or links may legitimately recur to express relationships. These are design mechanisms rather than a claim that the model makes every possible database free of redundancy.
Relations are FREQUENTS(CUSTOMER,HOTEL), SERVES(HOTEL,SNACKS), LIKES(CUSTOMER,SNACKS). They record visits, available snacks, and preferences respectively. Express in relational algebra the query: list hotels that serve a snack customer Rama likes.
Answer & solution
Answer: π_HOTEL(SERVES ⋈ σ_CUSTOMER='Rama'(LIKES)). (no official key was published)
First select Rama's preferences: R = σ_CUSTOMER='Rama'(LIKES). Next match those snack names with served snacks by a natural join on their common attribute SNACKS. Finally discard the customer and snack columns, retaining only hotels:
π_HOTEL(SERVES ⋈ σ_CUSTOMER='Rama'(LIKES)).
An equivalent expression first projects preferences to snack names: π_HOTEL(SERVES ⋈ π_SNACKS(σ_CUSTOMER='Rama'(LIKES))).
For any hotel h in this result, the join supplies some snack s with SERVES(h,s) and LIKES('Rama',s), exactly the requested existential condition. Conversely, every such pair joins and projects to h, so no qualifying hotel is omitted. Under ordinary set relational algebra projection removes duplicates when a hotel serves several liked snacks.
FREQUENTS is deliberately unused: the query does not require Rama to visit the hotel. Joining it and filtering Rama would incorrectly exclude unvisited hotels. Nor is division appropriate: division would express serving every liked snack, whereas the wording asks for at least one. If Rama likes no snacks, the result is empty.
Let G be a group of even order with identity e. Show that some a≠e satisfies a²=e.
Answer & solution
Answer: True: inverse pairing leaves a nonidentity self-inverse element. (no official key was published)
Here “even order” means finite order |G|=2m. Consider inversion g↦g⁻¹. Every element whose inverse is different forms a two-element pair {g,g⁻¹}; these pairs are disjoint because taking the inverse twice returns g. The remaining elements are fixed points of inversion, satisfying g=g⁻¹, equivalently g²=e.
The paired elements account for an even number of elements. Subtracting this number from the even total |G| shows that the number of fixed points is even. Identity e is one fixed point, so there cannot be exactly one: another fixed point a≠e exists. Multiplying a=a⁻¹ by a gives a²=e, as required. Since a≠e, its order is exactly two.
Equivalently, G\{e} has odd size and cannot be completely partitioned into distinct inverse pairs; one nonidentity self-inverse element must remain. This proof uses neither commutativity nor any assumption that G is cyclic. It proves existence, not uniqueness: some groups have several nonidentity involutions. The finite-even-order qualification matters; an infinite group is not classified as even merely by an informal pairing argument.
On D={1,2,3,4,6,8,12,24}, use the binary operations LCM and GCD. Which structures apply: (i) group, (ii) ring, (iii) field, (iv) lattice?
Select all that apply
Answer & solution
Answer: Only (iv), lattice. (no official key was published)
D is exactly the positive divisors of 24=2³·3. Order D by divisibility, not by the ordinary numerical ≤ relation. Every d is uniquely 2i3j with 0≤i≤3 and 0≤j≤1. GCD takes the coordinatewise minimum of exponent pairs, and LCM takes their coordinatewise maximum. Both outputs are again divisors of 24, proving closure.
For x,y∈D, gcd(x,y) divides both and every common divisor divides it, so it is their greatest lower bound (meet). Likewise lcm(x,y) is their least upper bound (join). Thus every pair has a meet and join: (D,gcd,lcm) is a lattice, option (iv). In fact it is a bounded distributive lattice, with bottom 1 and top 24. For example gcd(8,12)=4 and lcm(8,12)=24.
Neither operation makes this nontrivial set a group. Both are idempotent: x⋆x=x. In a group, cancellation would force every idempotent x to equal the identity, impossible for eight distinct elements. More concretely, LCM has identity 1 but 2 has no inverse giving LCM(2,y)=1; GCD has identity 24 but 2 has no inverse giving GCD(2,y)=24. Consequently these operations cannot provide the additive group required for a ring, in either assignment of addition and multiplication, and cannot form a field. Do not classify it as a group merely because the operations are closed and associative.
The reproduction asks to show inconsistency using modus ponens or resolution: (1) ∀x [Q(x) → (P(x) ∨ ¬R(a))] (2) R(a) [missing connective] ¬Q(a) (3) Q(a) (4) ∀y ¬P(y). Here a is a constant and P,Q,R are unary predicates. Both surviving copies omit the connective in (2). Give an explicitly conditional derivation rather than silently repairing the source.
Answer & solution
Answer: Formula (2) is malformed as printed. With (2)=R(a)∨¬Q(a), resolution yields □; with ∧ it also contradicts Q(a), whereas with → there is a countermodel. (no official key was published)
Literally (2) is not a well-formed formula, so the printed set has no uniquely defined satisfiability question. A natural repair is R(a)∨¬Q(a); the following resolution proof is conditional on that repair, not an assertion about a verified original.
Convert (1) to the universally quantified clause ¬Q(x)∨P(x)∨¬R(a). Instantiate x=a and resolve with (3), Q(a), to obtain P(a)∨¬R(a). Instantiate (4) at y=a, obtaining ¬P(a); resolve to get ¬R(a). The repaired (2), R(a)∨¬Q(a), resolves with Q(a) to give R(a). Resolving R(a) and ¬R(a) yields the empty clause □. Hence the disjunction repair is inconsistent.
The same reasoning can be written with modus ponens: Q(a) and (1) imply P(a)∨¬R(a); ¬P(a) forces ¬R(a). Under the disjunction repair, (2) is Q(a)→R(a), so Q(a) forces R(a), a contradiction.
If the missing connective were ∧, (2) would directly include ¬Q(a), contradicting (3), so that repair is also inconsistent. But if it were →, the set would be consistent: take a singleton domain {a}, Q(a)=true, P(a)=false, and R(a)=false. Then (1) is true because ¬R(a) is true, (2) R(a)→¬Q(a) is vacuously true, (3) is true, and (4) is true. The requested unconditional proof is blocked by the defective premise, while the explicitly labeled repaired proof is complete.
On S=ℤ fix n>1 and define aRb iff a−b is a multiple of n. Prove that R is an equivalence relation and find its classes when n=5.
Answer & solution
Answer: R is congruence modulo n; for n=5 the classes are 5ℤ,5ℤ+1,5ℤ+2,5ℤ+3,5ℤ+4. (no official key was published)
Prove all three defining properties using divisibility.
Reflexivity: for each a, a−a=0=n·0, so aRa. Symmetry: if aRb, then a−b=nk for an integer k. Hence b−a=n(−k), so bRa. Transitivity: if aRb and bRc, write a−b=nk and b−c=nℓ. Adding gives a−c=n(k+ℓ), so aRc. Thus R is an equivalence relation.
For n=5, the division algorithm gives every integer z a unique remainder r∈{0,1,2,3,4}, including negative integers. Two integers are related exactly when these remainders agree. The five distinct classes are: [0]={5k:k∈ℤ}={…,−10,−5,0,5,10,…} [1]={5k+1:k∈ℤ}={…,−9,−4,1,6,11,…} [2]={5k+2:k∈ℤ}={…,−8,−3,2,7,12,…} [3]={5k+3:k∈ℤ}={…,−7,−2,3,8,13,…} [4]={5k+4:k∈ℤ}={…,−6,−1,4,9,14,…}.
They cover ℤ by existence of remainders. They are disjoint because equality 5k+r=5ℓ+s implies 5 divides r−s, and for r,s in 0…4 this forces r=s. Representatives are not unique: for example [−1]=[4], but these are the same class, not a sixth class.
True or false? The union of two recursive languages is recursive. Prove your answer.
Answer & solution
Answer: True; run the two total deciders and accept iff either accepts. (no official key was published)
True. A recursive language has a decider: a machine that halts on every input and answers membership correctly. Let M1 decide L1 and M2 decide L2, taking a common ambient alphabet (the union of their alphabets if necessary). A machine for L1∪L2 operates as follows:
On input w:
run M1(w) to completion;
if M1 accepts, accept;
run M2(w) to completion;
if M2 accepts, accept;
otherwise reject.
If w belongs to the union, at least one decider accepts. Acceptance by M1 immediately suffices; otherwise M2 accepts. If w is outside the union, both deciders reject, and the constructed machine rejects. It always halts because M1 always halts and, when run, M2 always halts. Correctness together with total termination proves recursiveness.
Sequential simulation is adequate here. For merely recursively enumerable languages the first recognizer might loop forever on a nonmember, so a union recognizer generally needs dovetailing instead. The stronger halting promise for recursive languages is the precise reason the simpler proof works. This establishes closure under finite union by induction; it does not establish closure under arbitrary infinite union.
True or false? L={0ⁿ : n is prime} is not regular. Prove your answer.
Answer & solution
Answer: True. Pump a prime-length q word with i=q+1 to obtain composite length q(1+|y|). (no official key was published)
True. Suppose for contradiction that L is regular, and let p≥1 be its pumping length. There is a prime q≥p, because primes are unbounded. Choose w=0q∈L. For any pumping-lemma decomposition w=xyz with |xy|≤p and |y|≥1, let d=|y|, so 1≤d≤p.
The pumping lemma requires xyi z∈L for every integer i≥0. Choose i=q+1. This word has length |xz|+(q+1)|y| = (q−d)+(q+1)d = q+qd = q(1+d). Both factors exceed one: q is prime and therefore q≥2, while d≥1 gives 1+d≥2. The length is composite. Consequently xyq+1z∉L, contradicting the pumping lemma.
The contradiction holds for every valid decomposition, because the same choice i=q+1 works for every positive d. We therefore refute the existence of a pumping length, and L is nonregular. Choosing an arbitrary fixed pump such as i=2 would not suffice: q+d might itself be prime for some decompositions. The deliberately selected exponent makes the resulting length a multiple of q larger than q.
True or false? Regular languages are closed under infinite union. Prove your answer.
Answer & solution
Answer: False; ⋃_{n≥0}{0ⁿ1ⁿ} is nonregular although each singleton is regular. (no official key was published)
False. For every n≥0 define Ln={0n1n}. Each Ln contains one fixed finite word and is regular: a finite chain of states accepts exactly that word, or the word itself is a regular expression. However, the infinite union ⋃_{n≥0}Ln={0n1n:n≥0} is not regular.
For completeness, suppose this union has pumping length p. The word w=0p1p belongs to it. Every legal decomposition w=xyz with |xy|≤p and |y|≥1 puts y entirely in the first block of zeros, say y=0d with d≥1. Pump down to i=0. The resulting xz=0p−d1p has unequal numbers of zeros and ones and is not in the union, contradicting the pumping lemma.
This is a countably infinite family of regular languages with a nonregular union, enough to disprove arbitrary infinite-union closure. Closure under two-way union, and hence any finite union, is not in conflict: the usual product/NFA constructions use finitely many component automata, whereas this family requires unboundedly many distinct word lengths. Some infinite unions do happen to be regular, for example ⋃_{n≥0}{0n}=0*. The statement fails because not every infinite union is regular.