Why did the historical FORTRAN implementations described not permit recursion: static allocation, dynamic allocation, absent hardware stacks, or impossibility on some machines?
Your answer
Answer & solution
Answer: A: static allocation in the historical implementation model (no official key was published)
A single statically allocated location for each local variable provides only one activation’s storage. A recursive call would overwrite values still needed by its caller, so that implementation cannot support general recursion without changing its storage scheme. A stack of activation records is the usual solution; a hardware stack is not essential because software can implement one. Thus A explains the historical restriction. It is not a claim about all modern Fortran: later standards and implementations support recursive procedures with appropriate activation storage.
For real symmetric n×n matrices A,B, which identity is guaranteed: AAᵀ=I, A=A⁻¹, AB=BA, or (AB)ᵀ=BA?
Your answer
Answer & solution
Answer: D (no official key was published)
Transpose reverses product order: (AB)ᵀ=BᵀAᵀ. Symmetry gives Bᵀ=B and Aᵀ=A, so the product transpose is BA. Symmetry alone does not imply orthogonality or self-inverse behavior; for example 2I refutes both. Two symmetric matrices also need not commute, as unequal diagonal scaling and a coordinate-swap matrix demonstrate. Hence only D follows for all such A and B, including singular matrices for which A⁻¹ may not exist.
Answer: B: y_(n+1)=y_n+h f(x_(n+1),y_(n+1)) (no official key was published)
Integrating the derivative over one step gives the change in y. Backward Euler approximates that derivative using the right endpoint of the step, so yn+1−yn≈h f(xn+1,yn+1). This produces the stated implicit equation, which may require solving for the new y. Forward Euler instead evaluates f at the known left endpoint (xn,yn). A formula with two-step values or an unrelated scaling is not the first-order backward Euler method.
For arbitrary events A,B, choose the universal statement: product formula for intersection, equality of union to the sum, a multiplied conditional formula, or P(A∪B)≤P(A)+P(B).
Your answer
Answer & solution
Answer: D (no official key was published)
Inclusion–exclusion gives P(A∪B)=P(A)+P(B)−P(A∩B). The intersection probability is nonnegative, so the union is at most the sum. Equality needs disjointness, which is not stated. The product formula for the intersection needs independence. Conditional probability, when P(B)>0, is P(A|B)=P(A∩B)/P(B), not multiplication by P(B). Thus D is the only unconditional assertion among the listed alternatives.
Is unrestricted goto harmful because verification is harder, runtime rises, memory rises, or generated code is necessarily longer?
Your answer
Answer & solution
Answer: A (no official key was published)
Arbitrary jumps can create tangled control flow with many entry points and difficult-to-track invariants. This makes local reasoning about a block’s preconditions and postconditions harder, so program verification and maintenance suffer. A jump itself need not increase runtime, data storage or machine-code length; those effects depend on the program and compiler. The objection is therefore structural reasoning, not a universal performance penalty. Structured conditionals and loops make control-flow boundaries more explicit.
How many distinct simple graphs have up to three nodes, among 15,10,7,9?
Your answer
Answer & solution
Answer: C: 7, for nonempty unlabeled graphs (no official key was published)
Count graph isomorphism classes by vertex count. With one vertex there is one graph. With two vertices there are two: no edge or one edge. With three vertices the possible edge counts 0,1,2,3 each determine one class: empty, one edge plus isolated vertex, a two-edge path, or triangle. Total 1+2+4=7. This uses unlabeled graphs and excludes the zero-vertex graph. Including that graph gives eight, while labeled fixed vertex sets yield 1+2+8=11, so the interpretation must be stated.
Which recurrence models worst-case binary search: T(n)=T(n/2)+k, 2T(n/2)+k, T(n/2)+log n, or T(n/2)+n?
Your answer
Answer & solution
Answer: A (no official key was published)
A binary-search step compares the target with the middle key and discards one half. Only the surviving half is searched recursively, so there is one T(n/2) term, not two. Selecting and comparing the middle item takes constant time in an indexed array, represented by k. Repeated halving reaches a constant-size range after Θ(log n) steps. The recurrence presupposes constant-time midpoint access; a linked-list implementation has different access costs.
The circuit forms t=NAND(A,B), u=NAND(t,C), v=NAND(C,D), then f=NAND(u,v). Find its Boolean expression.
Your answer
Answer & solution
Answer: A: ¬A·C+¬B·C+CD (no official key was published)
Write t=¬(AB), u=¬(tC), and v=¬(CD). The final NAND gives f=¬(uv)=¬u+¬v=tC+CD by De Morgan’s law. Substituting t=¬A+¬B yields f=¬A·C+¬B·C+CD. Following the intermediate nets prevents accidentally treating the first NAND as AND or distributing a complement across a sum without changing the operator. This algebra uses the input fan-out of C to both middle gates as shown in the figure.
The first column is three times the second, so at most two columns are independent and rank is at most two. The second and third columns are independent: their first coordinates are 0 and 3, respectively, while the second column is nonzero. Alternatively the minor from rows 1,3 and columns 2,3 is 0·1−3·1=−3, nonzero. Thus rank is at least two as well, proving rank exactly two.
For an abelian group G, is g=g⁻¹, g=g², (gh)²=g²h², or finiteness guaranteed?
Your answer
Answer & solution
Answer: C (no official key was published)
Expand (gh)² as ghgh. Commutativity lets the middle h and g exchange places, producing gghh=g²h². The other properties do not follow: the additive group of integers is abelian but infinite, and most elements are neither their own inverse nor idempotent. In multiplicative notation, g=g² would force g to be the identity after cancellation. Thus C captures the actual use of the abelian assumption.
Rows of a lower triangular n×n matrix, including their diagonal, are stored consecutively. With one-based indices, where is entry (i,j), j≤i?
Your answer
Answer & solution
Answer: C: i(i−1)/2+j (no official key was published)
Before row i, the stored rows have lengths 1,2,…,i−1, totaling i(i−1)/2 entries. Entry j in the next row is j positions beyond that prefix under one-based indexing. Therefore its packed index is i(i−1)/2+j. A zero-based packed offset would subtract one from this result. The formula stores every position in the lower triangle, even if a particular value happens to be zero; omitting actual zeros would require additional sparse-matrix metadata.
Why generate intermediate code for an abstract machine: easier lexing, availability of syntax-directed rules, frontend portability, or inability to generate real machine code directly?
Your answer
Answer & solution
Answer: C: frontend portability (no official key was published)
An intermediate representation separates language analysis from target-machine details. The same frontend can translate a source language into that representation, while different backends generate code for different processors. This improves portability and reuse. Direct generation of machine code is possible, so D is false. Syntax-directed translation can generate an IR, but its existence is not the main abstract-machine benefit, and lexical analysis does not become fundamentally easier merely because an IR is chosen.
A heavily used page was loaded early and remains in constant use. Which listed policy can evict it because of its age: LRU, FIFO, generic replacement, or none?
Your answer
Answer & solution
Answer: B: FIFO (no official key was published)
FIFO orders resident pages by when they entered memory, ignoring later references. A page loaded early can therefore reach the front of the eviction queue even while frequently accessed. LRU updates recency information when the page is used, so constant recent use protects it relative to less recently referenced pages. The question contrasts these policy criteria, not an absolute guarantee that a page can never be evicted under any workload. FIFO’s load-age rule is the specific explanation.
Input 1,2,3,4,5 arrives in order. Which output is possible with one stack: 34512,34521,15234,54312?
Your answer
Answer & solution
Answer: B: 34521 (no official key was published)
Step through it (4 options)
Push 1,2,3 and pop 3; push 4 and pop 4; push 5 and pop 5; then pop 2 and 1. This constructs 34521. For 34512, after producing 345 the stack has 2 above 1, so 1 cannot come next. For 15234, after popping 1 then pushing through 5, the next available value is 4, not 2. For 54312, after popping 5,4,3, value 2 still blocks 1. Thus only B is feasible.
For a character string of length n, how many nonempty contiguous substrings are there when counted by position?
Your answer
Answer & solution
Answer: D: n(n+1)/2 (no official key was published)
A substring of length k can start in n−k+1 positions. Summing for k=1 through n gives n+(n−1)+…+1=n(n+1)/2. Equivalently choose its two boundaries among n+1 boundary positions. This counts occurrences, not necessarily distinct string values: repeated characters can make different positions yield the same word. It also excludes ε. If “substrings of all lengths” includes the empty word or means distinct values, the answer needs that additional convention.
Which equivalent-machine conversion is impossible in general: regular grammar→CFG, NFA→DFA, NPDA→DPDA, or nondeterministic TM→deterministic TM?
Your answer
Answer & solution
Answer: C (no official key was published)
Every regular grammar is already a restricted CFG, and the subset construction converts NFAs to equivalent DFAs. A deterministic TM can simulate all branches of a nondeterministic TM by dovetailing, preserving recognition power. But deterministic context-free languages are strictly fewer than context-free languages. For example unmarked palindromes over a two-letter alphabet are context-free but not deterministic context-free. Hence some NPDAs have no equivalent DPDA at all, so a general conversion cannot exist.
Among insertion sort, binary search, radix sort and polynomial manipulation, which is poorly supported by a plain linked list?
Your answer
Answer & solution
Answer: B: binary search (no official key was published)
Binary search repeatedly accesses a midpoint by index. An array provides that access in constant time, but a plain linked list must traverse links to locate it, losing the logarithmic-access advantage. Linked lists can support insertion-sort splicing, bucket chains in radix sorting and sparse polynomial terms naturally. The issue is not that binary-search comparisons are impossible on a list, but that the necessary positional access is inefficient without additional indexing structures.
Which feature cannot generally be enforced by a CFG alone: if-then-else syntax, recursive-procedure syntax, declaration before variable use, or arbitrary-length variable names?
Your answer
Answer & solution
Answer: C (no official key was published)
A CFG can describe nested statements, recursive syntactic structures and identifier shapes of unbounded length. Checking that a particular identifier was previously declared requires matching that name against the declarations valid in its scope, not merely recognizing a syntactic category. Compilers therefore use symbol tables and semantic analysis for this context-sensitive condition. The claim concerns unrestricted identifiers and general programs; a finite fixed universe could be encoded into a much larger grammar, but that is not the usual language model.
Does quicksort use dynamic programming, backtracking, divide and conquer, or greedy design?
Your answer
Answer & solution
Answer: C (no official key was published)
Quicksort chooses a pivot, partitions the input into regions ordered relative to it, and recursively sorts those smaller regions. The resulting subproblem solutions combine to give the sorted whole, so the design is divide and conquer. It does not cache overlapping subproblems as dynamic programming does, and it does not search and undo candidate solutions as backtracking does. Good or bad pivot choices affect the balance and complexity, not this classification.
Which argument can expose different results between call-by-name and call-by-reference: constant, array address, whole array, or an array element?
Your answer
Answer & solution
Answer: D (array element) (no official key was published)
For an actual argument a[i], call-by-reference fixes the target location at call time. Call-by-name reevaluates the argument expression each time the formal is used. For example start i=1 and call a procedure whose body sets i:=2 then assigns 9 to the formal. Reference modifies a[1], while name modifies a[2]. Thus an array element whose index can change demonstrates the difference.
Which is true: nested macro definitions are impossible; overlays allow a program larger than address space; virtual memory exceeds address space; or high-level interrupt routines are impossible?
Your answer
Answer & solution
Answer: B under the total-program-overlay interpretation (no official key was published)
An overlay design keeps only selected mutually exclusive program portions resident at once and loads others into reused addresses. Its total stored program can therefore exceed the simultaneously addressable space, provided each active configuration fits. Virtual memory can exceed installed physical RAM, but it does not by itself enlarge the architecture’s virtual address space. Nested macros and high-level interrupt routines are possible in suitable tools, so the blanket impossibility claims fail.
Which is false: optimal BST via dynamic programming; BFS cannot find connected components; preorder/postorder do not generally uniquely determine a binary tree; DFS can find components?
Your answer
Answer & solution
Answer: B (no official key was published)
Start BFS from an unvisited vertex and mark everything reachable. In an undirected graph this is exactly its connected component. Repeating from remaining unvisited vertices finds every component in O(V+E), disproving B. DFS works similarly. Optimal BST construction has a dynamic-programming formulation. Preorder and postorder alone do not generally distinguish a node’s sole left child from its sole right child, so nonuniqueness is possible. That last statement is a general insufficiency, not a claim that every traversal pair is ambiguous.
Eventually g1(n)=n² and g2(n)=n³; below fixed cutoffs the formulas differ. Assess A g1=O(g2), B g1=O(n³), C g2=O(g1) in GateForum but g2=O(g2) in GFG, D g2=O(n).
Your answer
Answer & solution
Answer: A, B, C (no official key was published)
Big-O ignores any fixed finite prefix, so only the eventual n² and n³ behavior matters. Since n²≤n³ for n≥1, both A and B are true. C instead compares g2 with itself and is trivially true. Thus the paper supports a unique single-choice answer.
The pictured heap has allocated lengths 50,300,600 separating free holes of lengths 150 and 350. Can requests 300,25,125,50 be satisfied by first fit, best fit, both or neither?
Your answer
Answer & solution
Answer: B: first fit but not best fit (no official key was published)
Both policies allocate the first request in the 350 hole, leaving free lengths [150,50]. First fit places 25 in the first hole, leaving [125,50], then 125 there, leaving [0,50], and finally fits 50. Best fit places 25 in the 50 hole, leaving [150,25], then 125 in the 150 hole, leaving [25,25]. The final 50 fits neither hole, though total free space is 50. Hence only first fit succeeds.
Similar questions1 more → · asked again: GATE 2011, Q15
Flip-flops for a modulo counter
Counters & Timing
Tap to enlarge
Fill in the minimum number of flip-flops required for a binary modulo-N counter.
Answer & solution
Answer: ceil(log₂N), for N≥2 (no official key was published)
With k flip-flops, the state register has at most 2^k distinct binary states. A modulo-N counter must distinguish N positions before repeating, so 2^k≥N and k≥ceil(log₂N). This many bits are sufficient: use N of the available states and arrange the transition after N−1 to return to zero. Non-power-of-two counters leave unused codes, whose recovery behavior should be designed separately. The degenerate N=1 counter can be a constant output with no state bits in the abstract model.
Give a binary operation on nonnegative integers that is associative but not commutative.
Answer & solution
Answer: x⋆y=x (left projection) (no official key was published)
Define x⋆y to return its first operand. The result is always a nonnegative integer, establishing closure. Then (x⋆y)⋆z=x⋆z=x, while x⋆(y⋆z)=x⋆y=x, so associativity holds for all triples. But 0⋆1=0 and 1⋆0=1, proving noncommutativity. This constructed example avoids subtraction, which is not closed on the nonnegative integers and is not associative. The question asks for an example, not a unique familiar arithmetic operation.
On N, R={(x,y):x≠y}. Which of reflexivity,symmetry,antisymmetry,transitivity hold?
Answer & solution
Answer: Symmetry only (no official key was published)
If x≠y then y≠x, so R is symmetric. It is not reflexive because x≠x never holds. It is not antisymmetric: 0R1 and 1R0 hold despite 0≠1. It is not transitive: 0R1 and 1R0 hold but 0R0 fails. These explicit counterexamples distinguish the three failed properties. In addition the relation is irreflexive, though that property is not among the requested choices.
Answer: 2^(n−1), for n≥1 (no official key was published)
Toggle whether element 1 belongs to a subset. This maps every even-cardinality subset to a unique odd-cardinality subset and reverses itself, so the two classes are equally large. Since there are 2n total subsets, each class has 2n−1. The argument does not require summing individual binomial coefficients. If n=0 is allowed, the only subset is empty and the odd count is zero; the usual displayed formula assumes the nonempty base set n≥1.
A graph has n vertices each of degree d. Fill in its number of edges.
Answer & solution
Answer: nd/2 (no official key was published)
Summing vertex degrees gives nd. Each undirected edge contributes two to that sum, one at each endpoint, so the handshaking lemma yields 2|E|=nd. Therefore |E|=nd/2. In particular nd must be even for such a finite graph to exist. This is the standard undirected interpretation of a regular graph; a directed graph would require stating whether d denotes indegree, outdegree or total degree.
Given P(B)=P1, P(A∩B)=P2 and P(A∩Bᶜ)=P3, find P(A). The clearer alternate supplies these premises.
Answer & solution
Answer: P2+P3 (no official key was published)
Every outcome in A either lies in B or in its complement. Therefore A=(A∩B)∪(A∩Bᶜ), and the two pieces are disjoint. Additivity gives P(A)=P2+P3. P1 is not needed for this result, though consistency requires P2≤P1 and P3≤1−P1.
Give the representable integer range of an n-bit two’s-complement word, including the sign bit.
Answer & solution
Answer: −2^(n−1) ≤ N ≤ 2^(n−1)−1 (no official key was published)
The most significant bit has weight −2n−1; the remaining bits have positive weights 1,2,…,2n−2. The smallest value sets only the sign bit, giving −2n−1. The largest clears it and sets all remaining bits, whose sum is 2n−1−1. Thus the range has one more negative value than positive value. Zero uses one of the 2n codes, and there is no separate negative-zero representation.
Independent A,B,C have probabilities 0.8,0.5,0.3. Find the probability that at least one occurs.
Answer & solution
Answer: 0.93 (no official key was published)
The complement is that none occurs. Mutual independence gives P(Aᶜ∩Bᶜ∩Cᶜ)=(1−0.8)(1−0.5)(1−0.3)=0.2·0.5·0.7=0.07. Therefore the requested probability is 1−0.07=0.93. Adding 0.8+0.5+0.3 would overcount overlapping outcomes. The multiplication needs mutual independence as stated; pairwise independence alone would not determine the three-way complement probability.
Give Hasse diagrams for every lattice of up to four elements, up to isomorphism.
Answer & solution
Answer: Five nonempty lattices: chains of sizes 1,2,3,4, and the four-element diamond (no official key was published)
A finite nonempty lattice has a least and greatest element. With one or two elements only the corresponding chains are possible. With three elements, the remaining element must lie between bottom and top, again a chain. With four elements, the two interior elements are either comparable, giving a four-element chain, or incomparable, giving a diamond. Exact cover-edge descriptions are: size 1 no edges; size 2 0<1; size 3 0<a<1; size 4 chain 0<a<b<1; diamond edges 0<a,0<b,a<1,b<1. These cover lists specify all five Hasse diagrams without relying on a rough drawing. The empty structure is excluded by the usual nonempty-lattice convention.
Start/accept state A loops on 0 and goes to accept B on 1. B loops on 1 and goes to nonaccepting trap C on 0; C loops on both. Give a regex.
Answer & solution
Answer: 0*1* (no official key was published)
While in A the machine reads any number of zeros, possibly none. The first one moves it to B, where further ones are allowed. A zero after that moves to the trap and cannot be recovered. Thus accepted words are exactly a block of zeros followed by a block of ones, with either block allowed empty: 0*1*. The empty word is accepted because the start state A is accepting. The accepting mark on B permits words ending after one or more ones.
True or false: multiplexing address/data lines in the 8085 reduces instruction execution time.
Answer & solution
Answer: False (no official key was published)
The same AD0–AD7 pins carry low address bits during the address phase and data during later transfer phases. This saves package pins and wiring, not instruction time. An external latch controlled by ALE preserves the address while the pins are reused for data. Sharing lines can require additional timing constraints rather than making access intrinsically faster. Therefore the asserted speed benefit is false; the principal design tradeoff is interface cost and pin count.
True or false: expanding-opcode instruction formats are commonly employed in RISC machines.
Answer & solution
Answer: False in the conventional RISC/CISC distinction (no official key was published)
An expanding opcode reuses bits otherwise needed for operands to distinguish more operations in formats with fewer operands. This increases encoding flexibility but complicates decoding and produces less uniform formats. Conventional RISC emphasizes regular, often fixed-length instructions and straightforward decoding, so expanding opcodes are associated more with complex instruction-format designs. The statement is a textbook architectural tendency, not a prohibition: real instruction sets may mix features, and “RISC” is not a formal theorem excluding every variable-format encoding.
Finite-state addition of arbitrarily long integers
Finite-State Machine Design
Tap to enlarge
True or false: a finite-state machine can add two integers of arbitrary digit length. State the input/output convention.
Answer & solution
Answer: True for an LSB-first synchronous serial adder (no official key was published)
Feed the two numbers one bit pair at a time from least significant to most significant, padding the shorter with zeros. The machine needs only the carry bit c, hence two states. For input bits a,b it emits (a+b+c) mod 2 and changes state to floor((a+b+c)/2). After the final pair, emit the remaining carry. This works for any finite length with constant internal state. The convention matters: it is a transducer with paired LSB-first input, not a DFA expected to store both complete unbounded integers or emit an MSB-first sum before future carries are known.
Match Newton–Raphson, Runge–Kutta, Gauss–Seidel, Simpson’s rule with root finding, ODEs, linear systems and integration.
Answer & solution
Answer: i–b,ii–c,iii–d,iv–a (no official key was published)
Newton–Raphson updates a root estimate using a function and its derivative. Runge–Kutta methods advance an ODE solution by combining several slope evaluations. Gauss–Seidel iteratively solves a linear system using newly updated components within each sweep. Simpson’s rule approximates a definite integral by fitting quadratic interpolants. Therefore the respective matches are root finding, ordinary differential equations, systems of linear equations and integration. These identify the methods’ standard purposes, not claims that each is the only available method for that task.
Match BNF, lexical analysis, YACC and recursive-descent parsing with general CFGs, regular expressions, LALR(1), LL(1).
Answer & solution
Answer: i–d,ii–a,iii–b,iv–c (no official key was published)
Backus–Naur form is a notation for context-free grammar productions. Lexical token patterns are commonly specified by regular expressions and recognized by finite automata. Traditional YACC constructs an LALR(1) parser. A predictive recursive-descent parser uses LL(1) choices, with one-token lookahead selecting a production. Thus the requested mapping is d,a,b,c. General recursive descent can also use backtracking or more lookahead, so the LL(1) match refers to its standard nonbacktracking predictive form.
True or false: every schema has a BCNF decomposition that is both lossless and dependency preserving.
Answer & solution
Answer: False (no official key was published)
Take R(A,B,C) with F={AB→C,C→B}. Its candidate keys are AB and AC. The dependency C→B violates BCNF because C is not a superkey. Decomposing into CB and AC is lossless, since the common C determines CB, and both components are BCNF. But their projected dependencies do not imply AB→C: from AB one cannot derive C. More generally every proper subrelation here supplies no dependency producing C from AB, so no decomposition into proper BCNF components can preserve that FD. BCNF can guarantee losslessness, not simultaneous dependency preservation in every case.
One instance of R(A,B,C) has distinct values for A. Can A be concluded to be a candidate key for the schema?
Answer & solution
Answer: No (no official key was published)
A candidate key is a schema-level guarantee: it must uniquely identify rows in every legal instance and be minimal among such attribute sets. Distinct A values in one observed instance show only that A happens to be unique there. For example rows (1,x,u),(2,y,v) are consistent with no uniqueness constraint on A; a later legal row (1,z,w) could repeat it. Therefore one instance does not establish the functional dependency A→BC or candidate-key status.
Give an expression equivalent to R∩S using the minimum number of operators from {∪,−}.
Answer & solution
Answer: R−(R−S), using two differences (no official key was published)
The inner R−S contains exactly the R tuples absent from S. Removing those from R leaves the tuples present in both, namely R∩S. This uses two operators. One operator cannot work for arbitrary R,S: R∪S includes exclusive tuples, R−S and S−R keep exclusives rather than common tuples, and applying an operator to a relation twice yields either that relation or the empty relation. Thus two is minimal under set semantics with only R,S and the listed binary operators, assuming union-compatible schemas.
True or false: every subset of a countable set is countable.
Answer & solution
Answer: True, with countable meaning finite or countably infinite (no official key was published)
A countable set A has an injection into the natural numbers. Restrict that injection to any subset B⊆A; it remains injective, so B is at most countable. Equivalently, an enumeration of A can be filtered to retain only B, possibly producing a finite list. The empty subset is included. If a text uses “countable” to mean strictly countably infinite, finite subsets require a terminology qualification; the standard at-most-countable convention makes the statement true.
Match ECL,GaAs,TTL,CMOS with: (a) unipolar very fast radiation-resistant/difficult fabrication; (b) unipolar low power; (c) fast bipolar silicon/low density; (d) inexpensive bipolar.
Answer & solution
Answer: i–c,ii–a,iii–d,iv–b (no official key was published)
ECL uses bipolar transistors operated without deep saturation for high switching speed, matching c. GaAs technologies historically offered high speed and radiation resistance with fabrication challenges, matching a. TTL is the familiar bipolar family associated with inexpensive standard logic, matching d. CMOS uses complementary MOS devices and low static power, matching b. These are the historical qualitative comparisons given in the question; modern fabrication nodes can substantially change absolute speed, power and density rankings.
True or false: logical data independence is easier to achieve than physical data independence.
Answer & solution
Answer: False (no official key was published)
Physical data independence hides changes such as indexes, file organization and storage placement behind an unchanged logical schema. Applications can often remain unaffected. Logical data independence must hide changes to the conceptual schema itself, such as restructuring relations or attributes, while preserving external views and application meaning. That generally requires more semantic translation and is harder. Therefore the source reverses the usual difficulty comparison. This is a database-design principle, not an assertion that every individual physical change is trivial.
Answer: [[1/2,−1/2,1/2],[0,0,1],[1/2,1/2,−1/2]] (no official key was published)
Solve Mx=b. The third row gives x2=b3. The first gives x1+x3=b1, while the second gives −x1+x3=b2−b3. Adding the last two equations gives x3=(b1+b2−b3)/2; subtracting gives x1=(b1−b2+b3)/2. Thus the coefficients of b in x are exactly the displayed inverse matrix. This also proves uniqueness for every b, hence invertibility, without relying only on a numerical inverse calculation. Multiplying M by the displayed matrix returns the identity.
Use a truth table to decide whether the claim “p↔q does not imply p→¬q” is true.
Answer & solution
Answer: True: the asserted implication fails at p=q=true (no official key was published)
List rows (p,q) as TT,TF,FT,FF. The column p↔q is T,F,F,T. The column p→¬q is F,T,T,T. For semantic implication, every row with the first column true would need the second true. The TT row instead has a true premise and false conclusion, so p↔q does not imply p→¬q. Therefore the quoted nonimplication claim is true. This is a claim about entailment across all rows, not the value of either formula under one unspecified assignment.
A 3-ary tree has exactly three children at every internal node. Use induction to prove that with n internal nodes it has 2(n−1)+3 leaves (GateForum). GFG instead prints 2(n−1).
Answer & solution
Answer: The formula as printed is false; with +3 (2n+1 leaves) it holds (no official key was published)
1. Base n=1: a root with three children has three leaves, equal to 2(1−1)+3.
2. For any full ternary tree with n+1 internal nodes, choose a deepest internal node. Its three children are leaves. Prune those three children, making their parent a leaf.
3. The smaller tree has n internal nodes and, by induction, 2n+1 leaves. Restoring the three children replaces one leaf by three, increasing the leaf count by two. Thus the original has 2n+3=2((n+1)−1)+3 leaves.
4. The single-node tree n=0 also satisfies 2n+1=1 if that case is included.
Both say interval nodes, understood as internal nodes from the definition.
What function of integer x,n is computed by this program? function what(x,n): value := 1; if n > 0 then begin if n mod 2 = 1 then value := value*x; value := value*what(x*x,n div 2); end; return value;
Answer & solution
Answer: x^n for n≥0 under exact arithmetic; 1 for n<0. (no official key was published)
1. For n≤0 the conditional is skipped and the return value is one.
2. Write positive n=2k+r, where r∈{0,1}. The function returns xr times what(x²,k).
3. Induct on n. The recursive argument k<n, and the induction hypothesis gives (x²)k. Hence the result is x2k+r=xn.
4. The recursion depth and multiplication count are O(log n). Fixed-width integer overflow can change the numerical result; no word size is specified.
A[0..n−1] contains n integers. Shift it cyclically left K places, 1≤K≤n−1, in linear time without another array. Fill the five blanks in this skeleton. min:=n; i:=0; while ___ do begin temp:=A[i]; j:=i; while ___ do begin A[j]:=___; j:=(j+K) mod n; if j<min then min:=j; end; A[(n+i-K) mod n]:=___; i:=___; end;
Answer & solution
Answer: In order: i<min; (j+K) mod n ≠ i; A[(j+K) mod n]; temp; i+1. (no official key was published)
1. The desired assignment is new A[j]=old A[(j+K) mod n]. Follow this permutation one cycle at a time.
2. Save the first value in temp, copy forward along the cycle, and stop before the next source would be the overwritten start. The last destination is (i−K) mod n, where temp belongs.
3. Let g=gcd(n,K). The first cycle contains precisely the indices divisible by g. Its smallest positive visited index is g, so min becomes g. For K in the given range the cycle has at least two positions.
4. The remaining starts 1,…,g−1 cover the other residue classes. No update makes min smaller than g. After these g cycles the outer loop ends. Each index is assigned once, so time is Θ(n), with O(1) extra storage.
Code
min := n; i := 0
while i < min:
temp = A[i]; j = i
while (j + K) % n != i:
A[j] = A[(j + K) % n]
j = (j + K) % n
if j < min: min = j
A[(n + i - K) % n] = temp
i = i + 1
A rooted tree has nodes numbered 1 to 12 in preorder. Its postorder is 3,5,4,2,7,8,6,10,11,12,9,1. Reconstruct it, give every parent, and show the tree.
Answer & solution
Answer: Parents: 1:none; 2:1; 3:2; 4:2; 5:4; 6:1; 7:6; 8:6; 9:1; 10:9; 11:9; 12:9. (no official key was published)
1. The final postorder entry 1 is the root. The next preorder value 2 starts its first child subtree; that subtree ends at 2 in postorder, so it contains {2,3,4,5}.
2. Within subtree 2, node 3 is first and is already a complete subtree. The next child 4 has postorder 5,4 and therefore child 5.
3. The next unused preorder node is 6. Its postorder block is 7,8,6, giving children 7 and 8.
4. The remaining child subtree of 1 is rooted at 9 and has leaves 10,11,12.
5. These are ordered children according to the given traversals. A general rooted tree is intended, not a binary-tree constraint.
A received seven-bit single-error-correcting Hamming word has positions 7,6,5,4,3,2,1 containing 1,0,0,0,1,1,0 respectively. Assuming at most one corrupted bit, determine correctness and, if needed, correct it.
Answer & solution
Answer: Even parity: bit 6 is wrong, corrected word 1100110. Odd parity: bit 1 is wrong, corrected word 1000111. (no official key was published)
1. Parity checks cover positions {1,3,5,7}, {2,3,6,7}, {4,5,6,7}. Their received XORs are 0,1,1.
2. For even parity each expected XOR is zero. The failure vector (s4,s2,s1)=110₂=6 locates bit 6; flip its 0 to 1 to obtain 1100110 in position order 7 through 1. All three checks then equal zero.
3. For odd parity each expected XOR is one. The failure vector is 001₂=1, so flip bit 1 from 0 to 1 to obtain 1000111 in position order 7 through 1. All three checks then equal one.
4. Because the source does not specify the parity convention, one cannot select a unique corrected word without stating an assumption.
Diagram / structural description
Position: 7 6 5 4 3 2 1 Received: 1 0 0 0 1 1 0
Neither the paper explicitly specifies even or odd parity.
Write 8085 assembly to add two unsigned 16-bit packed 8-4-2-1 BCD operands in register pairs BC and DE. Place the result in BC; the higher register contains the higher-order decimal digits.
Answer & solution
Answer: Use ADD/DAA for the low byte and ADC/DAA for the high byte; final CY is decimal overflow. (no official key was published)
1. Each packed byte holds two decimal digits. First add C and E in A; DAA adjusts the binary sum into valid packed BCD and supplies the carry into the next two digits.
2. MOV C,A saves the low result without changing flags. MOV A,B also preserves the carry, allowing ADC D to add high bytes plus the low-byte decimal carry.
3. A second DAA adjusts the upper digits. MOV B,A preserves the final carry flag. BC now contains the lowest four decimal digits.
4. A sum above 9999 cannot fit in BC. The fifth digit is final CY (0 or 1); the question supplies no separate overflow destination. This limitation must not be concealed.
Code
MOV A,C ADD E DAA MOV C,A MOV A,B ADC D DAA MOV B,A
For the shown common-clock circuit, initial Q2Q1Q0=000. Find the state after four clock pulses. The Q2 flip-flop is JK with J=Q̅0,K=1; Q1 is D with D=Q2; Q0 is T with T=Q1.
Answer & solution
Answer: 011 (no official key was published)
1. All flip-flops sample their inputs from the same pre-edge state. JK gives Q2(next)=J·Q̅2+K̅·Q2=Q̅0·Q̅2. D gives Q1(next)=Q2. T gives Q0(next)=Q0 XOR Q1.
2. Starting at 000, the first pulse gives 100. The second gives 010. The third gives 101. The fourth gives 011.
3. Do not propagate a freshly changed Q2 into Q1 during the same edge; that would model a different asynchronous circuit.
Diagram / structural description
Common clock to JK(Q2), D(Q1), T(Q0). Q2→D; Q1→T; inverted Q0 feedback→J; K tied to logic 1.
COURSES(cno,cname), primary key cno; STUDENTS(rollno,sname,age,year), primary key rollno; REGISTERED_FOR(cno,rollno), composite primary key (cno,rollno). year denotes the student’s current year of study. GateForum asks for a relational algebra query printing roll numbers of students who HAVE registered for cno 322. GFG instead asks for those who HAVE NOT registered.
Answer & solution
Answer: Registered: π_rollno(σ_cno=322(REGISTERED_FOR)). Not registered: π_rollno(STUDENTS) − π_rollno(σ_cno=322(REGISTERED_FOR)). (no official key was published)
1. Select registrations for course 322 before projecting rollno, so registrations in other courses do not count.
2. For the registered variant, projection directly returns the wanted roll numbers under the usual valid student-reference assumption. Without that assumption, intersect with π_rollno(STUDENTS).
3. For the not-registered variant, subtract the selected roll-number set from all student roll numbers. Selecting registrations where cno≠322 would be wrong because a student may register for both 322 and another course, or for no course.
COURSES(cno,cname), primary key cno; STUDENTS(rollno,sname,age,year), primary key rollno; REGISTERED_FOR(cno,rollno), composite primary key (cno,rollno). year denotes the student’s current year of study. Write SQL to print the age and year of the youngest student in each year.
Answer & solution
Answer: SELECT MIN(age) AS age, year FROM STUDENTS GROUP BY year; (no official key was published)
1. Group rows by year so each year is processed independently.
2. MIN(age) computes the youngest age within that group. Output just age and year, as requested, rather than an arbitrary student name or roll number.
3. Ties need no extra rows because the requested attributes are identical for tied youngest students. Standard SQL ignores NULL ages; if all ages in a year are NULL, the result is NULL.
Consider the B+ tree: The root has separators [25,38,69,93] and five linked leaves, left to right: [10,15], [25,36], [39,41,47], [69,71,75,83], [95,99,101,105]. Each node holds d to 2d keys, subject to the usual root exception. GFG asks for the tree after inserting 100; GateForum omits the insertion key.
Answer & solution
Answer: For insertion of 100 with d=2 and splitting rather than redistribution: new root [69], internal children [25,38] and [93,100], with six leaves listed in the diagram. (no official key was published)
1. The four-key leaf requires 2d≥4, so d≥2. The two-key leaves require d≤2. Together these bounds establish d=2 and capacity 2d=4. Insert 100 into [95,99,101,105] to get five sorted keys [95,99,100,101,105].
2. Choose the legal split [95,99] and [100,101,105]. Copy separator 100 into the parent, which becomes [25,38,69,93,100] with six children.
3. The overflowing internal root splits around its middle separator 69. Promote 69 into a new root, leaving internal nodes [25,38] and [93,100], each with three children.
4. All six leaves remain at equal depth and hold between two and four keys. Keys in internal nodes are routing separators, not additional data records.
5. A 3/2 leaf split with separator 101 is also legal if that split convention is used. The problem does not state a tie-breaking split policy; present the selected valid construction rather than claim uniqueness.
Diagram / structural description
Root [69]
Left internal [25,38] → [10,15] | [25,36] | [39,41,47]
Right internal [93,100] → [69,71,75,83] | [95,99] | [100,101,105]
All six leaves are linked in the displayed order.
The source root contains 38 and 93, although the corresponding right leaves start with 39 and 95. These are valid lower routing boundaries under a separator-range convention; an exact-minimum convention would require 39 and 95 instead. Preserve the source and disclose the convention.
A B+ tree of order d holds d to 2d keys per node. For n leaf nodes, fill the order of the number of nodes accessed during a search.
Answer & solution
Answer: O(1+log_(d+1) n); commonly written O(log_d n) for d≥2 and nontrivial trees. (no official key was published)
1. An internal non-root node has at least d+1 children because keys separate child ranges. A root that is internal has at least two children.
2. If the root-to-leaf distance is h≥1, there are at least 2(d+1)h−1 leaves. Rearranging bounds h by 1+logd+1(n/2).
3. Search follows a single child at each internal level and accesses the leaf, for h+1 node accesses. The extra constant handles n=1.
4. For d≥2, changing the logarithm base from d+1 to d changes only a bounded factor; logd n is the conventional blank. When d=1, logd n is undefined, so the d+1 expression is safer.
Every element a of a ring (R,+,∘) satisfies a∘a=a. Decide whether the ring is commutative.
Answer & solution
Answer: Yes, multiplication is commutative. (no official key was published)
1. Write multiplication by juxtaposition. Apply idempotence to a+a: (a+a)²=a+a. Distributivity and a²=a give 4a=2a, hence 2a=0 by additive cancellation. Thus −a=a for every a.
2. For arbitrary a,b, idempotence of a+b gives (a+b)²=a+b. Expanding yields a²+ab+ba+b²=a+b. Cancel a²=a and b²=b to get ab+ba=0.
3. Since every element is its own additive inverse, −ba=ba. Therefore ab=−ba=ba. No multiplicative identity is needed.
State true or false with reason: A coroutine is just another name for a subroutine.
Answer & solution
Answer: False. (no official key was published)
1. An ordinary subroutine is entered by a call and returns control to its caller; a fresh call normally begins execution at its entry point.
2. A coroutine can suspend at a yield/resume point, preserve its execution context, and later continue from that point. Control may transfer cooperatively between peer coroutines.
3. One can implement coroutines using lower-level mechanisms, but the two terms do not name the same control-flow abstraction.
State true or false with reason: A two-pass assembler uses its machine opcode table in the first pass of assembly.
Answer & solution
Answer: True for the conventional two-pass assembler. (no official key was published)
1. Pass one assigns addresses and builds the symbol table. To advance the location counter correctly, it must recognize instructions and determine their lengths.
2. The machine opcode table supplies instruction classification and length information, so it is consulted before final code generation in pass two.
3. Using the table does not mean final object code or unresolved operand addresses must already be emitted during pass one.
State true or false with reason: A subroutine cannot always be used to replace a macro in an assembly-language program.
Answer & solution
Answer: True. (no official key was published)
1. A macro performs assembly-time text expansion. Its parameters may select register names, opcodes, labels, data declarations or conditional assembly. Such choices can alter the generated instruction sequence itself.
2. A subroutine is runtime code reached by a call; it has call/return and argument conventions rather than general assembly-time substitution. A macro that declares a label or storage at each expansion point cannot be replaced simply by calling one fixed subroutine.
3. Some computational macros can be rewritten as subroutines, but that limited case does not justify the universal replacement claim.
State true or false with reason: A symbol declared external in assembly language is assigned an address outside the program by the assembler itself.
Answer & solution
Answer: False. (no official key was published)
1. External means the definition is supplied by another object module or library, not defined in this assembly unit.
2. The assembler records an unresolved external reference and the necessary relocation/linkage information.
3. The linker, or a loader performing dynamic resolution, combines definitions and assigns/resolves the final address. The assembler alone generally lacks the required placement and definition information.
Let S be the set of positive integers x for which the decimal expansion of π contains a maximal consecutive run of exactly x digits equal to 5. Which classification is warranted: (i) regular, (ii) recursively enumerable, (iii) not recursively enumerable, (iv) recursive?
Your answer
Answer & solution
Answer: The justified choice is (ii): recursively enumerable. No claim of nonrecursiveness follows. (no official key was published)
π is a computable real, and any finite initial segment of its decimal digits can be calculated effectively. Scan these digits from left to right, keeping the length of the current run of 5s. When a non-5 follows a nonempty run, output its length and reset the counter. Because a completed run has a non-5 immediately on each side (or begins at the start of the fractional digit stream), it is maximal rather than merely a substring of a longer run. Repeated lengths may be printed repeatedly; enumeration does not require uniqueness.
Equivalently, on input x, keep scanning until a completed run of length exactly x appears, then accept. Every positive instance eventually has a finite witness and is accepted. For an absent length the scan may never halt. This establishes recursive enumerability, the warranted answer (ii).
It does not establish that S is nonrecursive. In particular, a hypothetical proof that all finite digit blocks occur in π would make S all positive integers, which is recursive (and regular under customary encodings). Normality of π is not a given and must not be assumed. Nor does failure of this particular search to halt on negative instances prove that no different decision procedure exists. Options (i) and (iv) therefore cannot be inferred merely from the stated computability facts; describing (ii) as the only possible mathematical property would overstate the argument. A regular-language claim additionally needs an encoding of integers.
Similar questions1 more → · asked again: GATE 1999, Q6(a)
A regular union does not determine its operand
Regular Expressions & Languages
Tap to enlarge
If L1 and L1∪L2 are regular, must L2 be regular? Prove the answer.
Answer & solution
Answer: No. Take L1={a,b}* and L2={a^n b^n:n≥0}. (no official key was published)
Choose the common alphabet Σ={a,b}, let L1=Σ*, and let L2={an bn:n≥0}. L1 is recognized by a single accepting state with a loop on each alphabet symbol. Since L2⊆L1, their union is Σ*, also regular. Nevertheless L2 is not regular.
To verify the last assertion, suppose a pumping length p exists. The word ap bp must have a decomposition xyz with |xy|≤p and |y|>0. Consequently y consists of k≥1 copies of a. Pumping y zero times gives ap−kbp, which is not in L2 because the numbers of a and b differ. This contradicts the pumping lemma.
The tempting subtraction argument is invalid: (L1∪L2) minus L1 equals L2 minus L1, not necessarily L2. Regularity of the union controls the portion of L2 outside L1, but places no constraint on its arbitrary portion inside L1. Our counterexample puts all of L2 inside L1, making that gap explicit.
Similar questions2 more → · asked again: GATE 1992, Q2(xviii)
Length of a strict CNF derivation
Context-Free Grammars & Languages
Tap to enlarge
A CFG has only productions A→BC and A→a. For a generated terminal word of length ℓ, how many production applications occur in its derivation? GateForum omits the symbol after “length”; GFG supplies ℓ.
Answer & solution
Answer: 2ℓ−1 production applications for ℓ≥1. (no official key was published)
Each terminal of the final word is introduced by exactly one A→a production: no other production introduces terminals, and no production subsequently removes them. Hence there are exactly ℓ terminal-producing steps. Start with one nonterminal. Each A→BC application increases the number of nonterminals by one, whereas each A→a decreases it by one. If b is the number of binary applications, the final nonterminal count is 1+b−ℓ=0, so b=ℓ−1. The total number of applications is b+ℓ=2ℓ−1.
The same result follows by viewing the nonterminal portion of the parse tree as a full binary tree: ℓ terminal-producing leaves require ℓ−1 binary internal nodes. The count is independent of which nonterminal is expanded first, of leftmost versus rightmost derivation, and of ambiguity of the grammar. For ℓ=1 there is just the single terminal production, agreeing with the formula.
This is a count of steps, not a count of sentential forms: including both the initial symbol and final word gives 2ℓ sentential forms. Under the strict production forms stated here ε cannot be generated. If a different CNF convention permits S→ε, its ε derivation is a separate one-step exception, not an application of the formula at ℓ=0.
fib(n)=1 for n=0 or 1; otherwise fib(n)=fib(n−1)+fib(n−2). The available stack is 64 bytes. Each activation stores only a 2-byte return address and a 2-byte integer parameter. Estimate the largest nonnegative n without overflow. GateForum prints parameter “1” in the header but uses n in the body; GFG uses n.
Answer & solution
Answer: n=16 under the stipulated 4-byte-per-activation model, counting the initial fib call. (no official key was published)
Each active invocation occupies 2+2=4 bytes, so the stack can hold 64/4=16 simultaneously active invocations. The relevant quantity is peak recursion depth, not the exponentially growing total number of calls: completed calls return and free their space before their siblings finish.
Let D(n) be the largest number of simultaneously active fib frames, including the current frame. D(0)=D(1)=1, and for n≥2, D(n)=1+max(D(n−1),D(n−2)). It follows that D(n)=n for n≥1. For example fib(3)→fib(2)→fib(1) contains three active frames; the longest chain from fib(n) descends through n−1,n−2,…,1. The alternative final call at zero has no extra level, because fib(1) is a base case and does not call fib(0).
Therefore n=16 uses exactly 64 bytes, while n=17 needs 68 bytes. Both base cases need just four bytes. This estimate assumes the full 64 bytes are available to fib, its initial activation is stack-resident, and intermediate results, frame links, saved registers and runtime bookkeeping incur no further stack charge, exactly as stipulated. A real implementation may need more storage. Excluding the initial activation would shift the numerical bound to 17, but that is a different accounting convention, not the model used here.
main declares global integer r. Procedure two, declared directly inside main, executes write(r). Sibling procedure one declares its own local r, assigns it 5, then calls two. main assigns its r=2 and executes two; one; two. What values are printed under static scoping?
Answer & solution
Answer: 2, 2, 2 (without separators, 222). (no official key was published)
Static, or lexical, scoping resolves a name by the nesting of declarations in the program text, not by whichever procedure happened to call the current procedure. Procedure two has no local declaration of r. Its immediately enclosing lexical scope is main, so every reference to r in two denotes main's r. Procedure one's local r is in a sibling procedure's scope and is not visible inside two.
After main assigns r=2, its first call to two prints 2. Next main calls one, which creates a separate local r and sets that local variable to 5. The call from one to two still resolves two's r to main's unchanged variable and therefore prints 2. Returning from one removes its local activation without changing main's r. The final direct call to two again prints 2.
Thus the sequence of values is 2,2,2. The pseudocode uses write rather than writeln and requests no separators, so a literal output stream would commonly appear as 222. Formatting conventions do not change the three values.
main declares global integer r. Procedure two, declared directly inside main, executes write(r). Sibling procedure one declares its own local r, assigns it 5, then calls two. main assigns its r=2 and executes two; one; two. What values are printed under dynamic scoping?
Answer & solution
Answer: 2, 5, 2 (without separators, 252). (no official key was published)
Under dynamic scoping, resolve an unbound local name by searching active callers, nearest first. Procedure two itself has no r. In the first call main→two, the closest active declaration is main's r, already set to 2, so two prints 2.
The second relevant call chain is main→one→two. Procedure one has an active local r initialized to 5. The search from two finds that declaration before reaching main, so this invocation prints 5. Procedure two merely reads the variable; it does not copy the value into main's r or assign to either declaration.
After one returns, its local r is no longer in the active call chain. The last main→two call therefore finds main's original r=2 and prints 2. The resulting sequence is 2,5,2, or 252 if ordinary write operations introduce no spaces. The key distinction is lifetime plus dynamic caller order: the same body of two can access different storage on different calls under dynamic scoping, whereas static scoping would always bind its r to main's lexical declaration. This result concerns the hypothetical dynamic-scoping interpretation requested, not the default rules of Pascal.
Generate code for A→id:=E; E→E+T | T; T→(E) | id. The target has one accumulator R and only LOAD x (R:=mem[x]), STORE x (mem[x]:=R), ADD x (R:=R+mem[x]). Provide a syntax-directed translation.
Answer & solution
Answer: Use synthesized code/place attributes and a fresh memory temporary for each addition; assign by LOAD expression.place; STORE target. (no official key was published)
Give every E and T synthesized attributes code (an instruction list) and place (a memory address containing its value). An identifier token has its declared address id.addr. Let newtemp() allocate a fresh, non-aliasing memory cell and || concatenate instruction lists. The following bottom-up semantic rules form a complete syntax-directed definition.
The invariant is that executing a subtree's code leaves its value in its designated memory cell. Identifier leaves already satisfy this. Parentheses and E→T preserve it. In an addition, both operands are available in memory after their code has run; LOAD fetches the left one and ADD combines the right one without needing a second register. STORE preserves the result for enclosing expressions. Fresh temporaries prevent a right subtree from overwriting the saved left value. The final assignment changes the target only after the whole expression has been evaluated, so x:=x+y also works.
For x:=a+(b+c), first emit LOAD b; ADD c; STORE t1. Then LOAD a; ADD t1; STORE t2. Finally LOAD t2; STORE x. This deliberately simple scheme may contain redundant loads/stores, but optimization is not required. It uses exactly the three allowed instruction types and handles arbitrary nesting, unlike a scheme that leaves an unprotected partial result only in R.
Complete this scheme for a tree: V is its vertex set, I=∅; while V≠∅ choose u∈V satisfying blank 1, set V:=V−{u}, and if u satisfies blank 2 set I:=I∪{u}; output I. Fill both properties to obtain a maximum independent set.
Answer & solution
Answer: Choose u of degree at most one in the current induced forest; add u iff no original neighbor of u is already in I. (no official key was published)
Fill the first blank with: u is a leaf or isolated vertex in the forest induced by the current V. Fill the second with: u has no neighbor already in I, where adjacency is measured in the original tree. The removal changes the working forest only; it must not erase the adjacency information needed to test membership conflicts. Because every nonempty forest has a vertex of degree at most one, selection is always possible.
Independence is immediate: a vertex enters I only after checking that it is nonadjacent to every earlier selected vertex. To prove maximum size, maintain the stronger invariant that some maximum independent set of the original tree contains I and uses no previously rejected vertex. Consider a selected leaf u of the working forest. If u already has a neighbor in I, no independent set extending I can use u; rejecting it preserves the invariant. Otherwise u is eligible. In the remaining eligible graph it has at most one neighbor. If it has none, every maximum extension includes it. If it has one neighbor v, take a maximum extension: when it omits u, it must contain v (otherwise u could be added). Replace v by u. This preserves cardinality and independence, since u has no other eligible neighbor and none in I. Thus some maximum extension contains u, so adding u is safe.
At termination no undecided vertices remain; the invariant makes I itself maximum. “Choose any vertex and add it if possible” would guarantee only maximality, not maximum size: choosing the center of a star first is a counterexample. The leaf condition is essential.
For the tree independent-set algorithm that repeatedly removes a current leaf or isolated vertex and adds it if it has no selected neighbor, determine the time complexity and necessary implementation assumptions.
Answer & solution
Answer: Θ(n) time and O(n) working space with adjacency lists, degree counters and a leaf queue; naïve rescanning may take Θ(n²). (no official key was published)
A tree with n vertices has n−1 edges. Store its original adjacency lists, each vertex's current degree, a removed flag, a selected-neighbor (blocked) flag, and a queue of vertices whose current degree is at most one. Initializing these structures takes O(n+|E|)=O(n) time.
Pop a still-unremoved queue entry u, mark it removed, and add it to I exactly when its blocked flag is false. If added, mark its neighbors blocked. For each still-present neighbor, decrement the neighbor's degree; enqueue it when its degree first falls to one. Isolated initial vertices are queued from the start. Any harmless duplicate or stale entries can be skipped with the removed flag; alternatively use a queued flag.
Every vertex is removed once. Its adjacency list is scanned only a constant number of times, and the sum of degrees is 2(n−1). Hence all degree maintenance, blocking updates and queue operations total O(n). Reading all vertices and producing the result requires Ω(n) in the worst case, yielding Θ(n) time. The queue, flags, degree counts and adjacency representation require O(n) space.
The abstract scheme by itself does not force this bound: repeatedly searching all remaining vertices for a leaf or scanning I to test every candidate can take quadratic time. The linear bound is the efficient adjacency-list implementation, not a representation-independent guarantee. This distinction matters because the printed question specifies a tree and an algorithm outline but not data structures.
An integer array satisfies A[1]≤A[2]≤…≤A[n]. Give Pascal-like linear-time pseudocode to find indices i,j with A[i]+A[j]=M if a pair exists. State how equal indices are treated.
Answer & solution
Answer: Start i=1,j=n; advance i if sum<M, decrease j if sum>M, return at equality. Use i<j for distinct indices, i≤j if reuse is allowed. (no official key was published)
For distinct array positions, use: i:=1; j:=n; found:=false; while (i<j) and not found do begin s:=A[i]+A[j]; if s=M then found:=true else if s<M then i:=i+1 else j:=j−1 end; if found then output(i,j) else output('no pair'). A return statement at equality is an equivalent formulation. Use an arithmetic type wide enough to avoid overflow in the sum.
The invariant is that any still-possible pair lies entirely within the index interval [i,j]. If A[i]+A[j]<M, then A[i]+A[k]≤A[i]+A[j]<M for every k≤j in that interval. Therefore no candidate using i works, and discarding i is safe. If the sum exceeds M, then A[k]+A[j]≥A[i]+A[j]>M for all remaining k≥i, so discarding j is safe. Equality supplies a valid witness immediately. These arguments use nondecreasing order and therefore also cover duplicates and negative integers.
Each unsuccessful iteration shortens the interval by one; there are at most n−1 such iterations, giving O(n) time and O(1) auxiliary space. Empty and single-element arrays have no distinct-position pair.
The source does not explicitly require i≠j. If reusing a single position is permitted, change the loop condition to i≤j. The same elimination proof then includes the diagonal pair when 2A[i]=M. Keeping this variant explicit prevents silently rejecting a valid pair under that interpretation.
A queue Q contains n items and stack S is empty. Move all items into S so the original queue front is the stack top, with all remaining relative order preserved. Use only queue Delete/Insert and stack Push/Pop, O(n) time and O(1) extra storage.
Answer & solution
Answer: Transfer Q→S, then S→Q, then Q→S; use three n-iteration loops. (no official key was published)
Use a single item variable x and a loop counter. First repeat n times: x:=Delete(Q); Push(S,x). Next repeat n times: x:=Pop(S); Insert(Q,x). Finally repeat n times: x:=Delete(Q); Push(S,x). Here Delete removes the queue front, Insert appends at its rear, Push adds at the stack top, and Pop removes the top. No direct indexing or knowledge of either implementation is needed.
Let the original queue, from front to rear, be q1,q2,…,qn. After the first pass Q is empty and S is qn,…,q2,q1 from top to bottom, because each successive pushed item covers the previous one. The second pass pops in that reversed order and enqueues it, producing Q front-to-rear qn,…,q2,q1 and leaving S empty. The third pass reverses that queue order once more on the stack, leaving S top-to-bottom q1,q2,…,qn, exactly as required, and Q empty.
There are six primitive operations per item across the three passes, hence 6n operations and O(n) time under the usual constant-time ADT operations. Only x and counters are additional storage. The originally supplied queue and stack are reused rather than allocating another container. Recursively popping and pushing could also reverse an order but would consume O(n) call-stack storage and would violate the additional-space condition. The empty case performs no operations and already meets the postcondition.
Precedence versus control flow in conditional code
Synchronization & Concurrency
Tap to enlarge
The printed straight-line code is S1: read n; S2: i:=1; S3: if i>n goto next; S4: a(i):=i+1; S5: i:=i+1; S6: next: write a(i). No backward jump is printed. Draw its precedence graph, stating the treatment of conditional execution.
Answer & solution
Answer: Precedence 1→3, 2→3, 3→4, 4→5, 5→6, 3→6; statements 4 and 5 run only on the false branch (no official key was published)
The source calls for a precedence graph but contains a conditional jump, so an ordinary unguarded task DAG cannot by itself specify whether S4 and S5 execute. A faithful control-flow graph is S1→S2→S3, with S3 true→S6 and S3 false→S4→S5→S6. This edge list completely specifies the literal execution graph; there is no loop-back edge.
For potential parallel execution, S1 and S2 are independent initial tasks: the former writes n and the latter writes i. S3 needs both values, giving S1→S3 and S2→S3. On the false branch, keep S3→S4→S5→S6. S4 must precede S5 because it reads the old i both as an index and as the right-side operand; S5 changes i. S6 must see the incremented i on this branch. On the true branch, S6 follows S3 directly without executing S4 or S5. Thus a conservative guarded precedence description has edges 1→3,2→3,3→4,4→5,5→6,3→6, with 4 and 5 guarded by i≤n.
Do not conflate this graph with a pure data-dependence graph, which would omit some control edges and include direct uses of i. Also do not insert a guessed loop. With n≥1 the literal code assigns a(1), increments i to 2, then writes a(2), which it has not initialized. With n<1 it immediately writes a(1), also not initialized here. These are semantic concerns in the printed fragment, not permission to change its instructions. The question lacks enough conventions for a unique unqualified concurrency graph.
The printed straight-line code is S1: read n; S2: i:=1; S3: if i>n goto next; S4: a(i):=i+1; S5: i:=i+1; S6: next: write a(i). No backward jump is printed. Can its graph be converted into a concurrent program using parbegin–parend only?
Answer & solution
Answer: Not with parbegin–parend alone preserving the conditional skip. With an ordinary conditional as well, S1 and S2 can run in parallel, followed by S3-controlled work. (no official key was published)
A parbegin–parend block starts all of its component branches and waits for them all to finish. It expresses fork/join synchronization, not a data-dependent choice to omit a branch. In the printed program S4 and S5 must be skipped if i>n, and must execute in order otherwise. Therefore an unconditional composition using only sequential composition and parbegin–parend cannot represent the exact conditional semantics. This is the sense in which the answer is no.
If ordinary conditionals are allowed alongside parbegin–parend, a simple equivalent ordering is: parbegin read n; i:=1 parend; if i≤n then begin a(i):=i+1; i:=i+1 end; write a(i). The first two statements have disjoint write sets, so running them concurrently is safe; the join ensures both values are ready before the test. The remaining statements retain their branch and anti-dependence order. This transformation preserves even the original fragment's possible uninitialized-array access; it does not repair it.
One must distinguish this semantic issue from the graph-theoretic claim that every precedence DAG can be expressed by nested fork/join. That latter claim is false in general, but no particular non-series-parallel graph should be asserted here without specifying which dependence convention produced it. The conservative dependency ordering of part (a), once branch guards are disregarded, is structurally fork/join compatible. The actual obstacle under the literal word “only” is conditional execution. If the examiner intended a different dependence-only graph or omitted loop, that intent is not established by the paper.
Deadlock detection with multiple resource instances
Deadlocks
Tap to enlarge
Resource types r1,r2,r3 have respectively 2,3,2 instances. Assignments are r1→P1 and r1→P0; r2→P1, r2→P2 and r2→P3; r3→P0, leaving one r3 instance free. Outstanding requests are P1→r1; P0→r2 and P0→r3; P2→r3; P3→r1 and two P3→r2 arrows. Does the depicted resource-allocation graph represent deadlock?
Answer & solution
Answer: No, under the standard assumption that a process finishes and releases its holdings after its depicted requests are granted. (no official key was published)
Read each dot-to-process arrow as an allocated instance and each process-to-resource arrow as an outstanding request. In resource order (r1,r2,r3), total resources are (2,3,2). The allocation rows are P0=(1,0,1), P1=(1,1,0), P2=(0,1,0), P3=(0,1,0); their sum is (2,3,1), leaving Work=(0,0,1). The request rows are P0=(0,1,1), P1=(1,0,0), P2=(0,0,1), P3=(1,2,0). The two parallel P3→r2 arrows mean two requested instances, not a duplicated decorative edge.
Initially P2 is the process whose request vector is componentwise at most Work. Give it the free r3 instance. Under the standard graph-reduction model it completes, releasing that temporary grant and its held r2 instance. Consequently Work increases by its original allocation, from (0,0,1) to (0,1,1). P0 can now receive its requested r2 and r3 instances and complete, increasing Work to (1,1,2). P1 can then finish and increase Work to (2,2,2). Finally P3's request (1,2,0) is satisfiable, so it also completes.
All process nodes can be removed, so the current graph does not describe a deadlock. Cycles alone are insufficient to infer deadlock when resource types have multiple instances. This is a reduction of the displayed current requests, not a claim of Banker safety against unknown additional future maximum demands; no such maxima are supplied.
Resource types r1,r2,r3 have respectively 2,3,2 instances. Assignments are r1→P1 and r1→P0; r2→P1, r2→P2 and r2→P3; r3→P0, leaving one r3 instance free. Outstanding requests are P1→r1; P0→r2 and P0→r3; P2→r3; P3→r1 and two P3→r2 arrows. If the system is not deadlocked, give a safe completion sequence.
Answer & solution
Answer: P2 → P0 → P1 → P3. (no official key was published)
Use the available-vector test in resource order (r1,r2,r3). Initially Work=(0,0,1). P2 requests (0,0,1), so its request fits. On completion its original holding (0,1,0) returns to the available pool, giving Work=(0,1,1). It is important not to count the temporarily granted r3 twice: allocation-based reduction adds only the allocation it held before this simulated completion.
Next P0 requests (0,1,1), exactly within Work. It finishes and releases original allocation (1,0,1), making Work=(1,1,2). P1's outstanding request (1,0,0) now fits; releasing its original allocation (1,1,0) gives Work=(2,2,2). P3 can finally receive (1,2,0); releasing its original holding (0,1,0) gives Work=(2,3,2), the complete resource inventory. Thus P2,P0,P1,P3 is a valid completion sequence.
Indeed the initial choices are forced by the displayed requests: P0 initially lacks r2, while P1 and P3 lack r1. After P2, P0 is the only remaining satisfiable process. After P0, P3 still needs two free r2 instances but only one is available, forcing P1 before P3. Under simultaneous satisfaction of the displayed request vectors this order is therefore unique. As in part (a), “safe” means all these displayed requests can be satisfied and the processes finish; the graph does not state maximum possible future claims, so a stronger Banker's-algorithm safety assertion is outside the supplied data.