For n>1, T1(n)=4T1(n/2)+T2(n), and T2(n)=5T2(n/4)+Θ(log₂n). Both equal 1 for n≤1. Determine T1’s asymptotic order among n², n²log₂n, n^(log₄5), and n^(log₄5)log₂n.
Your answer
Answer & solution
Official answer: A
Our answer: Theta(n^2)
Givens and goal
For n>1, T1(n)=4T1(n/2)+T2(n), and T2(n)=5T2(n/4)+Θ(log₂n). Both equal 1 for n≤1. Determine T1’s asymptotic order among n², n²log₂n, nlog₄5, and nlog₄5log₂n.
Approach
Solve T2 first, then use its growth rate as the nonrecursive term in the recurrence for T1.
Step-by-step solution
1. In T2, the branching parameters are a=5 and b=4. The critical power is nlog₄5. Set α=log₄5≈1.161. 2. A logarithm is polynomially smaller than n^α: for example log₂n=O(nα/2). The first case of the Master theorem therefore gives T2(n)=Θ(n^α). 3. Substitute into T1: T1(n)=4T1(n/2)+Θ(n^α). Its critical power is nlog₂4=n². Because α<2, the additive term is again polynomially smaller than the critical power. 4. Applying the same Master-theorem case yields T1(n)=Θ(n²), option A. There is no extra logarithmic factor because the additive term is not Θ(n²), which would be the balanced case. 5. A recursion-tree check explains the dominance. At depth j, the T2 work totals Θ(4j(n/2j)^α)=Θ(n^α(4/2^α)j). The ratio exceeds 1, so lower levels dominate. With depth log₂n, the leaf scale is 4log₂n=n². Standard floor/ceiling handling of non-power inputs does not change this asymptotic result.
In an undirected integer-weighted graph, d_k(u) is the minimum weight of an s-to-u path with at most k edges, or infinity if none exists. S1 says d_(k+1)(u)≤d_k(u). S2 says that if edge (u,v) lies on a shortest s-to-v path, then d_k(u)≤d_k(v) for every k. Classify S1 and S2.
Your answer
Answer & solution
Official answer: A
Givens and goal
In an undirected integer-weighted graph, dk(u) is the minimum weight of an s-to-u path with at most k edges, or infinity if none exists. S1 says dk+1(u)≤dk(u). S2 says that if edge (u,v) lies on a shortest s-to-v path, then dk(u)≤dk(v) for every k. Classify S1 and S2.
Approach
Compare nested feasible path sets for S1 and use an explicit small edge-budget counterexample for S2.
Step-by-step solution
1. Every path using at most k edges also uses at most k+1 edges. The feasible set for dk(u) is therefore contained in the feasible set for dk+1(u). 2. Minimizing over a larger set cannot increase the minimum. Hence dk+1(u)≤dk(u), including the situation where an unavailable path of value infinity becomes available. S1 is true without assuming positive weights. 3. For S2, consider four vertices s,a,u,v with edges s—a of weight 1, a—u of weight 1, u—v of weight 1, and s—v of weight 10. The shortest s-to-v path is s—a—u—v, of total weight 3, and it includes (u,v). 4. Impose budget k=1. There is no one-edge s-to-u path, so d₁(u)=∞. But the direct edge s—v is permitted, giving d₁(v)=10. The asserted inequality ∞≤10 is false. 5. Thus only S1 holds, option A. Being a prefix of an unrestricted shortest path does not imply being reachable under the same smaller edge budget. The counterexample uses strictly positive integer weights, so the failure does not depend on negative cycles or an ambiguity about repeated vertices.
A simple undirected edge-weighted graph has distinct edge weights. Assess: A each cycle’s largest edge belongs to no MST; B each cycle’s smallest edge belongs to every MST; C each vertex’s largest incident edge belongs to no MST; D each vertex’s smallest incident edge belongs to every MST.
Select all that apply
Answer & solution
Official answer: A, D
Givens and goal
A simple undirected edge-weighted graph has distinct edge weights. Assess: A each cycle’s largest edge belongs to no MST; B each cycle’s smallest edge belongs to every MST; C each vertex’s largest incident edge belongs to no MST; D each vertex’s smallest incident edge belongs to every MST.
Approach
Use exchange arguments for the valid cycle/cut statements and connected counterexamples for the invalid ones.
Step-by-step solution
1. For A, suppose an MST T contains the uniquely heaviest edge e of some cycle. Removing e splits T into two components. The rest of the cycle still connects e’s endpoints, so at least one other cycle edge f crosses that cut. Distinctness makes weight(f)<weight(e). Replacing e with f produces a lighter spanning tree, a contradiction. Thus A is true. 2. For D, take the cut {v} versus all other vertices. Let e be v’s unique lightest incident edge. If an MST omitted e, adding e creates a cycle. On that cycle another edge incident to v crosses the same cut and is heavier. Removing it would reduce the tree weight. Thus e must belong to every MST and D is true. 3. B is not a valid cycle rule. Consider edges ad=1, bd=2, ab=3, bc=4, ac=5. In the cycle a—b—c—a the smallest edge is ab=3. But Kruskal’s algorithm selects ad,bd,bc, forming an MST of weight 7 and excluding ab because a and b already have the cheaper connecting path a—d—b. 4. C fails even for a graph that is itself a tree. It has only one spanning tree, so every edge must be present, including a vertex’s heaviest incident edge. A two-vertex graph with one edge is the simplest witness. 5. Select A and D. Distinct weights make these strict exchange comparisons immediate. The ordinary MST question assumes connectivity; for a disconnected graph the corresponding statements apply componentwise to a minimum spanning forest, with no incident-edge claim needed for an isolated vertex.
DFS assigns each vertex discovery time d and finish time f. The directed input graph is acyclic. For an edge u→v, which time orders are impossible? A d[u]<d[v]<f[v]<f[u]; B d[v]<d[u]<f[u]<f[v]; C d[v]<f[v]<d[u]<f[u]; D d[u]<d[v]<f[u]<f[v].
Select all that apply
Answer & solution
Official answer: B, D
Givens and goal
DFS assigns each vertex discovery time d and finish time f. The directed input graph is acyclic. For an edge u→v, which time orders are impossible? A d[u]<d[v]<f[v]<f[u]; B d[v]<d[u]<f[u]<f[v]; C d[v]<f[v]<d[u]<f[u]; D d[u]<d[v]<f[u]<f[v].
Approach
Use the parenthesis theorem for recursive DFS intervals, then use acyclicity to exclude ancestor-directed back edges.
Step-by-step solution
1. A DFS call remains active while all recursive descendants are explored. Therefore two vertices’ discovery-to-finish intervals are either nested, for an ancestor and descendant, or disjoint. Partial overlap is impossible. 2. D has d[u]<d[v]<f[u]<f[v], a partial overlap. Once v is discovered while u’s call is active, v must finish before that call can finish. Thus D is impossible in every DFS, regardless of whether the graph is acyclic. 3. In B, v’s interval strictly contains u’s, so v is a DFS ancestor of u. The DFS-tree edges give a directed path v→…→u. Together with the given edge u→v, this creates a directed cycle, forbidden in a DAG. Hence B is also impossible. 4. A is possible: take the graph with only edge u→v and begin at u. The times can be d[u]=1,d[v]=2,f[v]=3,f[u]=4, a tree-edge interval. 5. C is possible if v is explored first and finishes before u is discovered. With the same single edge u→v, choose v as the first DFS root: times can be d[v]=1,f[v]=2,d[u]=3,f[u]=4. The later edge goes to an already finished vertex and creates no cycle. 6. Select B and D. The DAG restriction is needed for excluding B; the nesting rule alone already excludes D.
With logarithms base 2, order n^(1/3), log n, log(n!), and 2^(log n) by increasing asymptotic growth. A log n,n^(1/3),2^(log n),log(n!); B n^(1/3),log n,log(n!),2^(log n); C log n,n^(1/3),log(n!),2^(log n); D 2^(log n),n^(1/3),log n,log(n!).
Your answer
Answer & solution
Official answer: A
Givens and goal
With logarithms base 2, order n1/3, log n, log(n!), and 2log n by increasing asymptotic growth. A log n,n1/3,2log n,log(n!); B n1/3,log n,log(n!),2log n; C log n,n1/3,log(n!),2log n; D 2log n,n1/3,log n,log(n!).
Approach
Simplify the exponential and bound the factorial logarithm.
Step-by-step solution
1. Because the bases match, 2log₂n=n exactly. It must therefore be compared as a linear function, not as an arbitrary exponential. 2. Write log(n!)=Σ(k=1 to n)log k. Every summand is at most log n, giving an upper bound n log n. The last at least n/2 summands are at least log(n/2), giving a lower bound (n/2)log(n/2). Thus log(n!)=Θ(n log n). 3. Any fixed positive power of n eventually dominates log n, so log n=o(n1/3). Also n1/3/n=n−2/3→0, and n/(n log n)=1/log n→0. 4. The required increasing order is log n, n1/3, n, Θ(n log n), matching A. This is an eventual growth comparison, not a claim of strict ordering at every small input.
All base cases are T(1)=1. Which recurrences give Θ(n)? A T(n)=T(n−1)+1; B T(n)=2T(n/2)+1; C T(n)=2T(n/2)+n; D T(n)=T(n−1)+n. For halving recurrences use powers of two or conventional rounding.
Select all that apply
Answer & solution
Official answer: A, B
Givens and goal
All base cases are T(1)=1. Which recurrences give Θ(n)? A T(n)=T(n−1)+1; B T(n)=2T(n/2)+1; C T(n)=2T(n/2)+n; D T(n)=T(n−1)+n. For halving recurrences use powers of two or conventional rounding.
Approach
Unroll decrement recurrences and sum levels in divide-and-conquer trees.
Step-by-step solution
1. A makes n−1 unit increments above its base: T(n)=1+(n−1)=n. It is Θ(n). 2. For B, n=2h gives a full binary recursion tree with n leaves. The leaves contribute n; its n−1 internal nodes each contribute 1. Thus T(n)=2n−1=Θ(n). 3. For C, level j has 2j subproblems of size n/2j, so its nonrecursive work is 2j(n/2j)=n. There are log₂n internal levels and n units at the leaves. Therefore T(n)=n log₂n+n=Θ(n log n). 4. D unrolls into 1+2+…+n=n(n+1)/2=Θ(n²). Unlike A, its added work grows with the current input size. 5. Only A and B are linear. Matching recursion shape alone is insufficient: B and C have the same branching but different work per node.
Merge sort sorts [10,7,8,19,41,35,25,31] using its usual balanced contiguous halves and seven merges. A merge is void if its output is the sorted left half followed directly by the sorted right half. Count void merges.
Answer & solution
Official answer: 3
Step through it (9 steps)
Givens and goal
Merge sort sorts [10,7,8,19,41,35,25,31] using its usual balanced contiguous halves and seven merges. A merge is void if its output is the sorted left half followed directly by the sorted right half. Count void merges.
Approach
List all seven merges and test max(left)≤min(right).
Step-by-step solution
1. At the lowest level the pairs are [10] with [7], [8] with [19], [41] with [35], and [25] with [31]. The second and fourth are already in concatenated sorted order; the first and third are not. This level contributes two void merges. 2. The next left merge combines [7,10] and [8,19]. Since 10>8, their elements interleave and it is not void. The next right merge combines [35,41] and [25,31]; since 41>25, it is not void either. 3. At the root the sorted halves are [7,8,10,19] and [25,31,35,41]. Because 19<25, concatenating them is already sorted. The final merge is void. 4. The count is 2+0+1=3 among the 4+2+1=7 merges. Void means the resulting ordering needs no interleaving, not that the recursive subarrays were originally sorted or that the implementation necessarily skips its merge routine.
A weighted directed acyclic graph has n vertices and m edges, with a specified source s. Find the fastest worst-case complexity to compute shortest-path distances from s to reachable vertices: A Θ(m+n); B Θ(m+n log n); C Θ(nm); D Θ(n³).
Your answer
Answer & solution
Official answer: A
Givens and goal
A weighted directed acyclic graph has n vertices and m edges, with a specified source s. Find the fastest worst-case complexity to compute shortest-path distances from s to reachable vertices: A Θ(m+n); B Θ(m+n log n); C Θ(nm); D Θ(n³).
Approach
Use an order in which every predecessor is settled before its successors.
Step-by-step solution
1. A DAG has a topological ordering: each edge u→v goes forward in that order. Compute one using indegrees or DFS in O(m+n) time with adjacency lists. 2. Initialize d[s]=0 and d[v]=∞ for all other vertices. Process vertices in topological order; for each outgoing edge u→v of weight w, set d[v]=min(d[v],d[u]+w) when d[u] is finite. 3. When u is processed, every possible final edge of a path into u comes from an earlier vertex. By induction, all those predecessor distances are final, so d[u] is the shortest distance. Negative edge weights do not break this argument because there are no cycles or backward dependencies. 4. Each vertex is initialized/processed once and each edge relaxed once, totaling O(m+n). Worst-case instances require reading relevant edge weights and producing vertex distances, giving a matching linear lower bound in the standard input model. 5. Thus A is correct. Dijkstra’s priority queue and Bellman-Ford’s repeated passes are unnecessary when acyclicity supplies the processing order.
For integer A[1…n], determine whether for every i>j in {1,…,n−1}, A[i+1]−A[i] > A[j+1]−A[j]. Choose optimal worst-case time: A Θ(n); B Θ(log n); C Θ(n log n); D Θ(n²).
Your answer
Answer & solution
Official answer: A
Givens and goal
For integer A[1…n], determine whether for every i>j in {1,…,n−1}, A[i+1]−A[i] > A[j+1]−A[j]. Choose optimal worst-case time: A Θ(n); B Θ(log n); C Θ(n log n); D Θ(n²).
Approach
Reduce all pairwise comparisons to adjacent comparisons using transitivity.
Step-by-step solution
1. Define d_i=A[i+1]−A[i]. The condition says each later difference is larger than every earlier one. This is equivalent to d_1<d_2<…<d_(n−1). 2. The forward implication includes all adjacent pairs. Conversely, if adjacent inequalities hold, chaining d_j<d_(j+1)<…<d_i proves the required inequality for every i>j. 3. Algorithm: if n≤2 return true; set previous=A[2]−A[1]; for i=2,…,n−1 set current=A[i+1]−A[i]; if current≤previous return false; otherwise set previous=current. If the loop ends return true. Only O(1) extra storage is needed. 4. The loop uses O(n) time. For a lower bound, consider a valid array such as A[i]=i², whose differences are strictly increasing. If any position is unread, an adversary can change that entry sufficiently to violate a neighboring comparison while leaving all inspected values unchanged. Thus worst-case inspection requires Ω(n) entries for n≥3. 5. The optimal bound is Θ(n), A. Use sufficiently wide arithmetic so subtraction does not overflow; the proof is in the mathematical-integer model.
T[0][k]=T[k][0]=1 for 0≤k≤n; for 1≤i,j≤n use T[i][j]=2T[i−1][j]+3T[i][j−1]. All cells initially equal 1. B1 loops i=1…n then j=1…n and updates each interior cell. B2 loops s=2…2n, then all i,j=1…n, updating only when i+j=s. Which is correct? A both; B only B1; C only B2; D neither.
Your answer
Answer & solution
Official answer: A
Givens and goal
T[0][k]=T[k][0]=1 for 0≤k≤n; for 1≤i,j≤n use T[i][j]=2T[i−1][j]+3T[i][j−1]. All cells initially equal 1. B1 loops i=1…n then j=1…n and updates each interior cell. B2 loops s=2…2n, then all i,j=1…n, updating only when i+j=s. Which is correct? A both; B only B1; C only B2; D neither.
Approach
Check whether the dependencies are ready before each update.
Step-by-step solution
1. Each interior cell depends only on its upper neighbor (i−1,j) and left neighbor (i,j−1). The coefficients 2 and 3 do not affect the ordering requirement. 2. In B1, row i−1 has already been completed when row i begins. Within row i, j increases, so the left neighbor has already been computed. Boundary neighbors retain their initialized correct values. 3. In B2, both dependencies have coordinate sum i+j−1=s−1. They were processed in the previous diagonal layer, unless they lie on a preinitialized boundary. Every interior cell has a unique sum between 2 and 2n and is updated exactly once. 4. For a small check, T[1][1]=2+3=5; T[1][2]=2×1+3×5=17; T[2][1]=2×5+3×1=13; T[2][2]=2×17+3×13=73. Either order produces these values. 5. Both are correct, A. B1 performs Θ(n²) work, whereas the stated B2 scans n² pairs for Θ(n) values of s and takes Θ(n³). Correctness does not require equal efficiency.
G is an undirected graph with positive edge weights and T is a minimum spanning tree. Let d1(u,v) be the shortest-path distance in G and d2(u,v) that in T. Which holds for all vertices and all such graphs? A d1=d2; B d1≤d2; C d1≥d2; D d1≠d2.
Your answer
Answer & solution
Official answer: B
Approach: Compare the sets of paths available in the graph and its spanning-tree subgraph. The unique u-to-v path in T uses only edges of G. Thus it is one candidate among the paths minimized over when defining d1. Minimizing over a set containing that candidate cannot give a larger value than its length: d1(u,v)≤d2(u,v). Therefore B always holds. Equality is possible, for example if G itself is a tree. Strict inequality is also possible: take a triangle with all edge weights 1 and a spanning tree consisting of two edges. Between the endpoints of the omitted edge, the graph distance is 1 but the tree distance is 2. These examples reject A and D as universal claims and reject C. An MST minimizes total chosen-edge weight, not every pairwise path distance. Indeed the inequality holds for any spanning tree; minimum total weight is unnecessary for this particular proof.
Solving an exponential recurrence by normalization
Asymptotic Analysis & Recurrences
Tap to enlarge
T(0)=1 and T(n)=2T(n−1)+n·2^n for n>0. Which asymptotic order is correct? A Θ(n²2^n); B Θ(n2^n); C Θ((log n)²2^n); D Θ(4^n).
Your answer
Answer & solution
Official answer: A
Approach: Divide out the homogeneous growth factor 2n so that the remaining recurrence becomes a simple cumulative sum. Define U(n)=T(n)/2n. Dividing the recurrence by 2n gives U(n)=T(n−1)/2n−1+n=U(n−1)+n, with U(0)=1. Repeated substitution yields U(n)=1+1+2+⋯+n=1+n(n+1)/2. Therefore T(n)=2n[1+n(n+1)/2]. The bracket is a quadratic polynomial with positive leading coefficient, so it is Θ(n²). Multiplication by 2n gives Θ(n²2n), option A. B overlooks the accumulation of n successive normalized contributions. C grows too slowly by replacing that quadratic sum with logarithms, and D is exponentially larger than the exact solution. A master theorem for T(n/b) is not the natural tool because this recurrence decreases n by one, rather than dividing it.
For i=0,…,n−2, an algorithm scans j=0,…,n−i−2 and swaps A[j],A[j+1] whenever A[j]>A[j+1]. Its input is 30 distinct integers in descending order. How many swaps occur?
Answer & solution
Official answer: 435
Approach: An adjacent out-of-order swap removes exactly one inversion, so count the input’s inversions. An inversion is a pair of positions i<j with A[i]>A[j]. In descending order every pair of distinct positions is an inversion. There are C(30,2)=30×29/2=435 such pairs. When two adjacent inverted values are swapped, their mutual inversion disappears. Their order relative to every other element contributes the same total as before, because no other element lies between the two positions. Thus each swap reduces the inversion count by exactly one. The shown bubble-sort passes finish in ascending order, with zero inversions, so exactly 435 swaps are required. A pass-by-pass check gives the same result: the largest value moves right in 29 swaps, the next in 28, and so on down to 1. Summing 29+28+⋯+1 gives 435. Comparisons and swaps are different quantities in general, even though every comparison succeeds for this descending distinct input.
An undirected unweighted graph has 100 vertices and maximum finite shortest-path distance 30 between vertices, in the usual connected-graph interpretation. T is any BFS tree. Which holds universally? A height exactly 15; B height exactly 30; C height at least 15; D height at least 30.
Your answer
Answer & solution
Official answer: C
Approach: A BFS tree preserves distance from its root; relate those root distances to two diameter endpoints. Let r be the BFS root and let h=maxv d(r,v), the tree height. Choose u,v with d(u,v)=30. A route from u to r and then from r to v has length d(u,r)+d(r,v), so the shortest u-to-v path obeys 30≤d(u,r)+d(r,v)≤h+h=2h. Therefore h≥15, giving C. Also h≤30 because no pair of vertices is farther apart than the diameter. The actual height depends on the chosen root, so neither exact value in A or B is guaranteed. A path of length 30 rooted at its centre has height 15, while rooting at an endpoint gives height 30. To meet the 100-vertex requirement, attach 69 extra leaves at the central vertex; the diameter remains 30 and the same two heights remain possible. Thus D’s stronger lower bound 30 is false. BFS preserves root distances, but it does not necessarily choose a central root.
An undirected four-vertex graph has edges AB=7, AD=6, DC=8, BC=x, BD=1, AC=3. The crossing diagonals BD and AC are edges, not an extra intersection vertex. Find the largest integer x for which BC belongs to every minimum spanning tree.
Answer & solution
Official answer: 5
Approach: Find a cut on which BC is uniquely cheapest, then test the equality boundary because “every MST” is stronger than “some MST”. Consider cut {B,D}|{A,C}. Its crossing edges have weights BC=x, DA=6, BA=7 and DC=8. If x<6, BC is the unique lightest edge of this cut. By the cut property it must occur in every MST. In detail, any spanning tree omitting BC has another crossing edge on the path connecting B to C; adding BC and removing that heavier crossing edge lowers its weight, contradicting minimality. At x=6, the tree {BD,AC,AD} has weight 1+3+6=10 and omits BC. The tree {BD,AC,BC} also has weight 10, and no spanning tree can have smaller weight than the three globally smallest edge weights, which sum to 10. Thus BC is no longer mandatory. For x>6, BC is uniquely heaviest on cycle B-D-A-C-B, whose other weights are 1,6,3, so the cycle property excludes it from an MST. Therefore the required condition is x<6, and the largest integer is 5. Equality cannot be included just because a tie allows an MST containing BC.
An unordered list contains N distinct integers. In the comparison model, what is the minimum number of element comparisons needed to find any element that is not the largest? Assume N≥2. Options: A. 1; B. N−1; C. N; D. 2N−1.
Your answer
Answer & solution
Official answer: A
Compare any two distinct list elements, say a and b. If a<b, return a; otherwise return b. Because the keys are distinct, the returned key is strictly smaller than the other compared key, which also belongs to the list. This is already a certificate that the returned key is not the maximum of the entire list. We do not need to identify the maximum or inspect the other N−2 elements.
One comparison is sufficient and, in the worst-case comparison model, necessary. With zero comparisons there is no ordering evidence about the chosen element; arbitrary distinct input values could make it the largest. N−1 is the familiar bound for finding the actual maximum, which is a stronger problem. The assumption N≥2 is necessary: for N=1 no nonmaximum element exists. Answer: A.
For BFS and DFS on an undirected simple graph G, choose all true statements. A. A DFS tree is always a shortest-path tree. B. Every DFS non-tree edge connects a vertex and an ancestor/descendant, described as a forward/back edge. C. Endpoints of a BFS non-tree edge have source distances differing by at most one. D. Either repeated BFS or repeated DFS can find all connected components.
Select all that apply
Answer & solution
Official answer: B, C, D
A is false. In a triangle with edges s–u,u–v,s–v, DFS may choose tree edges s–u and u–v. Its tree distance from s to v is then 2 even though the graph contains a length-1 path s–v. DFS prioritizes depth, not distance.
B is true for undirected DFS. If an edge from a currently explored vertex reaches an unvisited vertex, DFS follows it before finishing that subtree. Consequently an undirected non-tree edge cannot join two completely separate DFS subtrees; its endpoints have an ancestor-descendant relationship. It is usually called a back edge when oriented toward the ancestor. The question's “forward/back” wording refers to that relationship, not to a separate undirected cross-edge type.
C follows from shortest-path distances. For any edge u–v, a shortest route to u followed by that edge shows d(s,v)≤d(s,u)+1. Reversing the roles gives d(s,u)≤d(s,v)+1. BFS tree levels equal these distances, so their difference is at most one.
D is true: traverse from an unvisited vertex, mark its entire component, and repeat while any vertex remains unvisited. This works with either BFS or DFS, including isolated vertices. Select B,C,D.
In an undirected graph with positive edge weights, add the same positive constant α to every edge. How are minimum spanning trees (MSTs) and shortest paths (SPs) affected? A. Every MST and every SP remain optimal. B. MSTs may change; every SP remains optimal. C. Every MST remains optimal; SPs may change. D. Both MSTs and SPs may change. Consider components where the corresponding spanning tree/path exists.
Your answer
Answer & solution
Official answer: C
For a graph with n vertices, every spanning tree uses exactly n−1 edges. Its new weight is w'(T)=w(T)+(n−1)α. Any two trees receive exactly the same increment, so their weight difference and ordering are unchanged. In particular, every old MST is still an MST, and ties between MSTs are preserved.
Paths do not all contain the same number of edges. Consider a triangle with u–w of weight 1, w–v of weight 1, and u–v of weight 3. Initially the two-edge route from u to v costs 2, beating the direct edge's 3. Add α=2 to every edge. The two-edge route now costs 3+3=6, whereas the direct edge costs 5, so the old shortest path is no longer shortest.
Thus constant addition preserves MSTs but need not preserve shortest paths: C. The distinction is a fixed edge count across all spanning trees versus a potentially variable edge count across paths. Multiplying every edge by a positive constant would preserve both, but that is a different operation.
An array A[1…n] has distinct elements and is bitonic: for some 1≤i≤n, A[1…i] is increasing and A[i+1…n] is decreasing. The boundary comparison is not specified. Find the best possible worst-case comparison bound for searching for a supplied key. Options: A. Θ(n); B. Θ(1); C. Θ((log n)²); D. Θ(log n).
Your answer
Answer & solution
Official answer: D
Distinctness makes the two monotone parts strict. At the partition boundary, if A[i]<A[i+1], the peak is i+1; otherwise it is i. Thus the array has a single peak, including the possible endpoint peaks of a purely increasing or decreasing array.
Find that peak with binary search on adjacent values. Maintain a candidate interval [lo,hi]. For mid<hi, if A[mid]<A[mid+1], the peak lies strictly to the right of mid; otherwise it lies at mid or to its left. Each comparison discards roughly half the interval, taking O(log n) comparisons. Then binary-search the increasing part in its normal order and the decreasing part with reversed comparison direction. Each search costs O(log n), so their sum, plus peak finding, remains O(log n), not O((log n)²).
For a lower bound, sorted arrays are included among bitonic arrays. In the comparison model, exact membership among n distinct ordered keys has n possible successful positions and requires Ω(log n) comparisons in the worst case. Therefore the attainable bound is Θ(log n): D.
An algorithm runs BFS from any vertex v, picks a farthest vertex u, runs BFS from u, then reports its maximum distance d(u,z). Apply it to the unweighted tree described by these edges (labels added solely to reproduce the source figure): c–l,c–r,c–a,c–b; l–d,l–e,l–g; e–f; g–h,g–i; r–j,r–k; k–m. There are no other edges. Find the reported distance in edges. Figure orientation: c is the central branching vertex, l its upper-left junction, r its upper-right junction; a,b are the two lower leaves. The left arms end at d,f,h,i and the right arms at j,m.
Answer & solution
Official answer: 6
Step through it (12 steps)
The two-BFS method returns a diameter of an unweighted tree: a farthest vertex from any starting point is a diameter endpoint, and a BFS from that endpoint measures the full diameter. This exact guarantee uses the unique paths of a tree; it should not be assumed for every arbitrary graph.
Compute the diameter directly from the supplied edge list. From central vertex c, the farthest left-side leaves f,h,i are each three edges away: c–l–e–f or c–l–g–h/i. The farthest right-side leaf m is also three edges away: c–r–k–m. Joining a deepest left leaf to m therefore produces a path of length 3+3=6, for example f–e–l–c–r–k–m.
No longer path exists. A path crossing c uses at most two of its branch depths, whose two largest are 3 and 3. A path contained entirely in the left branch has at most 4 edges between f and h/i; a path within the right branch has at most 3 between j and m. The short lower branches of c cannot improve the maximum. Thus the diameter and algorithm's output are 6. The complete 14-vertex, 13-edge tree was reconstructed from the source figure.
An algorithm checks whether an N-element integer array is sorted in either ascending or descending order by one pass comparing adjacent elements. Its worst-case running time is: A both O(N) and Ω(N); B O(N) but not Ω(N); C Ω(N) but not O(N); D neither.
Your answer
Answer & solution
Official answer: A
Approach: Big-O and big-Omega describe upper and lower bounds on the same worst-case running-time function; they are not synonyms for worst case and best case. 1. Maintain whether any adjacent pair increases and whether any adjacent pair decreases. Each of the N−1 adjacent pairs requires only constant work. The single pass therefore takes at most cN+d operations, giving O(N). 2. On an already sorted array, no early contradiction occurs. The algorithm must examine through the final adjacent pair to certify the property. Such an input requires a number of comparisons proportional to N, giving a worst-case Ω(N) lower bound. 3. Together these bounds give Θ(N). Answer: A. Some unsorted inputs may allow early termination, but that does not remove the linear worst-case lower bound.
Normalize a square-root recurrence and flag its base case
Asymptotic Analysis & Recurrences
Tap to enlarge
The printed recurrence gives T(n)=√n·T(√n)+n for n≥1 and T(1)=1. Which asymptotic answer is intended? A Θ(n log log n); B Θ(n log n); C Θ(n² log n); D Θ(n² log log n). The recursive branch overlaps the base case, so the literal definition needs qualification.
Your answer
Answer & solution
Official answer: A
Approach: First disclose the definition's defect, then solve the intended version with a constant-size stopping threshold. 1. Literally, the n≥1 branch applies at n=1 and says T(1)=T(1)+1, contradicting T(1)=1. Merely changing ≥ to > is still insufficient over exact real arguments: repeated square roots of n>1 approach 1 but never reach it in finitely many steps. A constant threshold greater than 1, or a specified integer-rounding convention with a valid base, is needed. 2. For the intended recurrence, divide by n and set F(n)=T(n)/n. Then √n·T(√n)/n=T(√n)/√n=F(√n), so F(n)=F(√n)+1. 3. After k expansions, F(n)=F(n1/2^k)+k. Reaching a fixed threshold c>1 requires log n/2k≤log c, so k=Θ(log log n). 4. A bounded base value gives F(n)=Θ(log log n), hence T(n)=Θ(n log log n). Official intended answer: A. This derivation is conditional on the corrected stopping model; it does not solve the inconsistent recurrence exactly as printed. Existing discrepancy CS-2024-S1-Q42-BASE-CASE is preserved.
T is a DFS spanning tree of a directed graph G, rooted at v, and is also a BFS tree of G rooted at v. Which claims must hold? A G has no back edges relative to T. B G has no cross edges. C G has no forward edges. D Every edge of G belongs to T.
Select all that apply
Answer & solution
Official answer: C
Approach: A BFS tree preserves shortest-path distances from its root. Compare this constraint with the endpoint depths of each DFS edge type, using the usual simple directed-graph classification. 1. A non-tree forward edge u→w goes from a vertex to a proper descendant that is not its child. Thus depth_T(w)≥depth_T(u)+2. 2. But the edge supplies a root-to-w path of length depth_T(u)+1, shorter than its tree depth. This contradicts T being a BFS tree, so forward edges cannot exist. C is true. 3. Back edges are possible. In the directed cycle v→a→b→v, both DFS and BFS from v have the path v→a→b as their tree, and b→v is a back edge. Thus A and D are false. 4. Cross edges are also possible. Use edges v→a, v→b, b→a, with a explored before b in DFS. Both trees have a and b as root children, while b→a is a cross edge to the already completed branch. Answer: C only.
An undirected graph has 100 vertices. A complete DFS traversal produces a spanning forest containing 40 edges. How many connected components does the graph have?
Answer & solution
Official answer: 60
Approach: DFS starts a new tree exactly when it moves to a previously unvisited connected component. Each resulting tree spans that component. 1. Suppose there are c components and their vertex counts are v1,…,vc. The counts sum to 100. 2. A tree with vi vertices has exactly vi−1 edges. This includes an isolated vertex: vi=1 gives zero edges. 3. Summing over the DFS forest gives 40=Σ(vi−1)=Σvi−c=100−c. 4. Solving yields c=100−40=60. Answer: 60 connected components. The original graph may have additional nontree edges and cycles; the given 40 counts only forest edges. One can also view each of those 40 tree edges as discovering one nonroot vertex, leaving 60 roots, one for each component.
A recurrence whose larger-root coefficient vanishes
Asymptotic Analysis & Recurrences
Tap to enlarge
T(0)=1, T(1)=2, and T(n)=5T(n−1)−6T(n−2) for n≥2. Choose its tight asymptotic class. A Θ(2^n); B Θ(n2^n); C Θ(3^n); D Θ(n3^n).
Your answer
Answer & solution
Official answer: A
Approach: Solve the characteristic equation and then enforce both initial conditions.
1. Derivation. The characteristic polynomial r²−5r+6=(r−2)(r−3) gives T(n)=a 2ⁿ+b3ⁿ. T(0)=1 gives a+b=1, while T(1)=2 gives 2a+3b=2. Subtracting twice the first equation yields b=0, so a=1 and T(n)=2ⁿ exactly. Therefore A; the larger characteristic root does not contribute for these initial values.
2. Explanation and checks. A direct induction independently verifies the result: assuming T(n−1)=2n−1 and T(n−2)=2n−2, the recurrence becomes (10−6)2n−2=2n. Both base cases agree. The characteristic roots are distinct, so no factor n is introduced by repeated roots. More importantly, choosing the largest root without solving for its coefficient would give the wrong growth class here because that coefficient is zero.
Minimum replacements via a longest nondecreasing subsequence
Dynamic Programming
Tap to enlarge
The distance of an integer array is the least number of entries replaced by arbitrary integers to make it nondecreasing. Find the distance of [2,5,3,1,4,2,6].
Answer & solution
Official answer: 3
Step through it (9 steps)
Approach: Any entries kept in place must already form a nondecreasing subsequence; combine that lower bound with an explicit repair.
1. Derivation. Any unchanged elements must form a nondecreasing subsequence. Longest nondecreasing subsequence lengths ending at the seven positions are 1, 2, 2, 1, 3, 2, 4, so at most 4 elements can remain unchanged and at least 7−4=3 replacements are needed. Keep the subsequence 2, 3, 4, 6 at positions 1, 3, 5, 7; replace positions 2, 4, 6 by 2, 3, 4 respectively to obtain[2, 2, 3, 3, 4, 4, 6]. Thus3 is achievable and minimal.
2. Explanation and checks. For each position i define L[i]=1+max L[j] over j<i with A[j]≤A[i], or 1 if there is no such j. This yields [1,2,2,1,3,2,4], with maximum 4. Therefore keeping five entries is impossible. The displayed repair keeps four original entries and changes exactly three, establishing the matching upper bound. It is a replacement problem, not a sorting-by-swaps problem, and equality is allowed in the final array.
Maintain the one-run and two-value suffix invariants
Correctness, Invariants & Design
Tap to enlarge
For positive X[0..n−1], initialize first=second=len1=len2=maxlen=0. For each v=X[i]: if v==first increment both len1,len2; else if v==second increment len2, set len1=P, second=first; else set len2=Q, len1=1, second=first. Update maxlen=max(maxlen,len2), then first=v. len1 is the equal-value suffix length; len2 is the suffix length with at most two distinct values. Choose P,Q: A len1+1,len2+1; B 1,len1+1; C 1,len2+1; D len2+1,len1+1.
Your answer
Answer & solution
Official answer: B
Approach: Interpret the saved values before the current iteration updates them.
1. Derivation. first is the previous element and len1 is its final equal-value run length. If the next item equals second but differs from first, the final equal run starts anew, so P=1, while the valid two-value suffix extends by one. If a third distinct value arrives, only the previous final run can accompany it; therefore the new two-value suffix has length len1+1, giving Q=len1+1. The assignments update second to the old first. Thus B; positive input values ensure initial zero sentinels are not actual array values.
2. Explanation and checks. For the prefix [1,2,2], len1=2 and len2=3. If the next value is 1, it is the other known value: the two-value suffix grows to 4, but the same-value suffix has length 1. If instead the next value is 3, keeping all three old elements would create three distinct values; only [2,2,3] is legal, of length old len1+1=3. Updating first last preserves the old run value while second is assigned.
Undirected graph vertices a,b,c,d,e,f,g have weight-1 edges ab,af,cd,de; weight-2 edges ag,bg,fg,cg,dg,eg; weight-3 edges bc,fe; and no others. How many distinct minimum-weight spanning trees exist?
Answer & solution
Official answer: 9
Step through it (11 steps)
Approach: Force uniquely lightest cut edges, contract them, then count independent minimum connections.
1. Derivation. Each weight 1 edge (ab, af, cd, de) is uniquely lightest across the cut isolating its noncentral endpoint b, f, c, e, respectively, so all four occur in every MST. Contracting them gives components L={a, b, f}, R={c, d, e}, and{g}. There are three weight 2 choices linking L to g and three linking R to g. A minimum tree uses one of each, giving 3×3=9 distinct MSTs, each weight 4+2+2=8. Weight3 links L–R cannot improve that value.
2. Explanation and checks. After contraction only three supervertices remain, requiring exactly two additional edges. Connecting g to the left component has three distinct original choices; connecting g to the right has another three. Each pair is acyclic and connects all seven original vertices once the four forced edges are restored. Choosing a weight-3 left–right link instead would require at least one further weight-2 edge and yield total at least nine rather than eight. Therefore it cannot contribute an alternative minimum tree.
An adversary chooses k keys for m hash slots, k>m, to maximize collisions. Which strategy best counters a malicious fixed key set: A division with a fixed modulus; B multiplication with a fixed constant; C universal hashing; D choose division or multiplication based on whether k is prime?
Your answer
Answer & solution
Official answer: C
Universal hashing chooses a hash function randomly from a family with a bounded collision probability for distinct fixed keys, preventing an adversary from exploiting one known deterministic mapping. Division and multiplication with fixed constants can be targeted. Thus C under the standard model in which the selected random function is hidden or chosen independently of the adversary’s key set; unrestricted adaptive knowledge would require additional assumptions.
Teaching detail. For a universal family H, each distinct fixed pair x,y has collision probability at most 1/m when h is selected randomly from H. With chaining, the expected number of other keys colliding with a particular key is consequently bounded by (k−1)/m by linearity of expectation. Since k>m, some collisions are unavoidable by the pigeonhole principle: the goal is controlling concentrated collisions, not eliminating them. Random selection must be independent of the malicious fixed keys for this standard guarantee to apply.
For f(n)=n and g(n)=n², select true claims: A f∈O(g); B f∈Ω(g); C f∈o(g); D f∈Θ(g).
Select all that apply
Answer & solution
Official answer: A, C
f(n)/g(n)=n/n²=1/n tends to 0. Hence f=o(g), which also implies f=O(g). A positive constant lower bound proportional to n² cannot hold for all large n, so f is neither Ω(g) nor Θ(g). Answer A, C.
Teaching detail. The asymptotic definitions distinguish an upper bound from a tight bound. For n≥1, n≤n², so O(g) holds with constant 1. Little-o requires that for every ε>0, n≤εn² for all sufficiently large n; choosing n≥1/ε establishes it. An Ω(n²) lower bound would require 1/n≥c for some fixed c>0 eventually, which is impossible. Since Θ requires both O and Ω, it fails as well. A vanishing ratio is stronger evidence than a few sample comparisons.
Function 1 repeats while n>1: increment x exactly n times, then set n=floor(n/2). Function 2 increments x exactly 100n times. Let their increment counts be f1(n),f2(n) for the original n. Select true claims: A f1∈Θ(f2); B f1∈o(f2); C f1∈ω(f2); D f1∈O(n).
Select all that apply
Answer & solution
Official answer: A, D
For integer n at least 2, the first function executes at least n increments and fewer than n+n/2+n/4+...=2n increments. Therefore f1(n)=Theta(n). The second executes exactly 100n increments, also Theta(n). Their ratio stays bounded above and below by positive constants, so A and D hold, while neither little-o nor little-omega holds. The floor in the halving assignment does not change these bounds.
Teaching detail. Do not multiply the outer-loop count Θ(log n) by the original inner-loop length n: the inner length shrinks each time. For n a power of two, the exact count is n+n/2+...+2=2n−2. For arbitrary n, flooring can only reduce the geometric upper bound and the first pass alone supplies the n lower bound for n≥2. Compared with f2=100n, the ratio lies between 1/100 and 2/100. Being a smaller constant fraction is not little-o; little-o needs the ratio to vanish.
The vertices of a graph are all eight subsets of {1,2,3}. Distinct vertices are adjacent exactly when one set is a subset of the other. How many different BFS vertex-visit orders can start at ∅, allowing arbitrary neighbor ordering?
Answer & solution
Official answer: 5040
The empty set is a proper subset of every nonempty subset, so it is adjacent to each of the other seven vertices. BFS discovers all seven while scanning the start vertex. Any permutation of those neighbors can be its adjacency order; all seven are already discovered before any is expanded. Thus precisely 7!=5040 visit orders are possible.
Teaching detail. BFS uses a queue and discovers every neighbor of the start before expanding any of those neighbors. Since ∅ is contained in every subset, all other vertices are at distance one. No deeper layer imposes additional order constraints. Choosing any desired permutation of the seven neighbors as the start's adjacency-list order produces exactly that traversal after the fixed initial ∅. Thus the number is 7!, not 8!; the start position is not free. Later edges cannot create new vertices because all seven are already discovered.
For positive functions f(n), identify the universally valid statement under its specified restriction: A f(n²)=Θ(f(n)²) if f is polynomial; B f(n²)=o(f(n)²); C f(n²)=O(f(n)²) if f is exponential; D f(n²)=Ω(f(n)²).
Your answer
Answer & solution
Official answer: A
For a positive polynomial of degree d with leading coefficient c>0, f(n²)~c n2d and f(n)²~c² n2d, so they are Θ-equivalent, A. B fails with f(n)=n. C fails with f(n)=2n, since 2n²/22n diverges. D fails with f(n)=log n, since 2log n/(log n)² tends to zero.
The ratio f(n²)/f(n)² tends to 1/c for a degree-d polynomial, a positive finite constant, which is exactly enough for a Θ comparison. In B the ratio for n is 1 rather than tending to zero. In C the ratio is 2n²−2n, unbounded. In D use log(n+1) if positivity is required even at n=1; the ratio still tends to zero.
A simple undirected weighted graph has distinct edge weights. Select true MST claims: A second-lightest edge is always included; B at least one of third/fourth lightest is included; C unique lightest edge across every nontrivial cut is included; D multiple MSTs can exist. Assume existence of an MST and the referenced edges.
Select all that apply
Answer & solution
Official answer: A,B,C
Assume an MST exists and the graph has the referenced four edges. Kruskal always accepts the second-lightest edge: with only one accepted edge a simple graph cannot form a cycle. If the third is rejected, the first three edges form a triangle. The fourth cannot be another simple edge inside that already complete triangle, so it is accepted. Thus at least one of the third and fourth edges belongs to the MST. The unique lightest edge crossing any nontrivial cut belongs to every MST by the cut property. Distinct weights imply the MST is unique, making D false. Hence A, B, C. Connectedness and existence of the named edges are implicit in the question’s wording.
The cut property follows by exchange: if an MST omits the unique cheapest crossing edge e, adding e creates a cycle containing another crossing edge f. Since w(f)>w(e), replacing f by e lowers the total, a contradiction. Distinct weights also prove uniqueness by considering the cheapest edge where two proposed MSTs differ.
An array contains n integers. Let t be the optimal worst-case number of element comparisons needed to find both its minimum and maximum. Which printed bound is intended? A t>2n−2; B t>3⌈n/2⌉ and t≤2n−2; C t>n and t≤3⌈n/2⌉; D t>⌈log2 n⌉ and t≤n. The source gives no small-n restriction.
Your answer
Answer & solution
Official answer: C
Our answer: C for n≥5; small-n premise omitted
The optimal worst-case comparison count for simultaneous minimum and maximum is ceil(3n/2)−2. Compare elements in pairs, then compare each pair’s smaller element only against the running minimum and its larger element only against the running maximum; for even n this costs 3n/2−2, and for odd n it costs 3(n−1)/2. The standard adversary lower bound matches these counts. Consequently n<t≤3ceil(n/2) for n≥5, giving intended C. Literal qualification: for n=3 or 4, t=n, and for n=1 or 2 it is smaller, so the strict inequality in C is not valid for every unspecified n.
For even n, first compare one pair to initialize min/max (1 comparison); each of the remaining (n−2)/2 pairs needs one internal comparison and two comparisons with min/max. Total 1+3(n−2)/2=3n/2−2. For odd n, initialize both extrema to the first value for free, then spend three comparisons for each of (n−1)/2 pairs. Pseudocode for each pair (a,b): compare a,b; let lo=min(a,b), hi=max(a,b); compare lo with running_min and hi with running_max. For the matching lower bound, each nonmaximum needs a loss certificate and each nonminimum a win certificate, totaling 2n−2 certificates. An adversary classifies elements as untouched, winner-only, loser-only or both, and consistently places winner-only elements above loser-only elements. Comparing two untouched elements can create two certificates, but such comparisons are disjoint and number at most floor(n/2). Other comparisons can be answered to create at most one new certificate. Therefore at least 2n−2−floor(n/2)=ceil(3n/2)−2 comparisons are needed. This proof concerns worst-case comparisons, not a particular presorted input.
Let f1=10^n, f2=n^(log n), and f3=n^(√n). Arrange by increasing asymptotic growth. A f3,f2,f1; B f2,f1,f3; C f1,f2,f3; D f2,f3,f1.
Your answer
Answer & solution
Official answer: D
Taking logarithms gives log f2=Θ((log n)²), log f3=√n log n, and log f1=n log10. Since (log n)²=o(√n log n) and √n log n=o(n), the increasing order is f2, f3, f1, D.
Logarithms are strictly increasing on positive values, so their comparison preserves the order. Ratios of logarithms settle both gaps: (log n)²/(√n log n)=(log n)/√n→0 and (√n log n)/n=(log n)/√n→0. Consequently f2/f3 and f3/f1 tend to zero. The phrase 'n raised to log n' is not n log n; misreading the exponent would change the classification.
For [23,32,45,69,72,73,89,97], which standard sorting algorithm uses the fewest comparisons between array elements to sort in increasing order? A selection sort; B mergesort; C insertion sort; D quicksort with last-element pivot.
Your answer
Answer & solution
Official answer: C
Step through it (4 runs)
The displayed eight elements are already sorted. Standard insertion sort makes one failed element comparison for each of the seven later elements, totaling 7. Selection sort makes 28; ordinary mergesort makes more than 7; last-element-pivot quicksort repeatedly chooses the largest element and makes 28. Therefore insertion sort uses the least, C, for the standard versions of the named algorithms.
For selection sort the unsorted suffixes have lengths 8,7,...,2, producing 7+6+...+1=28 comparisons. Balanced top-down mergesort uses 4 comparisons merging singletons, 4 merging the sorted pairs, then 4 merging the two sorted halves, totaling 12 on this input. Insertion sort compares each new key with its immediate predecessor and stops, totaling 7. Quicksort's last pivot is always the maximum, so its partition costs sum to 28 in the standard implementation.
Find the number of minimum-weight spanning trees in this undirected graph. Essential diagram: nine vertices in a 3×3 grid, named a,b,c (top row), d,e,f (middle), g,h,i (bottom). Edges and weights: ab=.1, bc=.1, de=.1, ef=.9, gh=.9, hi=.1, ad=.9, be=.9, cf=.9, dg=.1, eh=.1, fi=.1. There are no other edges.
Answer & solution
Official answer: 3
Step through it (13 steps)
The seven weight 0.1 edges form a forest with two components: the top row of three vertices and the remaining six vertices. All seven cheap edges can be included without a cycle. Connecting these components requires one weight 0.9 edge; exactly the three vertical links between the top and middle rows do so. Each choice gives total weight 1.6, and any tree using fewer cheap edges is more expensive. Therefore exactly 3 MSTs.
A spanning tree on nine vertices needs eight edges. The seven cheap edges are acyclic and leave precisely two components, so Kruskal's algorithm accepts all seven before considering weight .9. Among the expensive edges only ad,be,cf cross that component cut; ef and gh stay within the lower component and create cycles. Thus each MST contains seven cheap edges and one of those three cross edges. This proves both attainability and exhaustiveness rather than merely counting three plausible trees.
The printed recurrence is T(n)=T(n/2)+T(2n/5)+7n for n>0, and T(0)=1. Under the intended integer-rounded or terminating-cutoff interpretation, select its tight order. A Θ(n^(5/2)); B Θ(n log n); C Θ(n); D Θ((log n)^(5/2)). The printed recurrence itself omits a rounding/cutoff convention.
Your answer
Answer & solution
Official answer: C
Our answer: C under terminating integer-size recurrence convention
The two recursive subproblem sizes sum to 0.9n. Thus the nonrecursive work over successive levels is bounded by 7n[1+0.9+0.9²+…]=70n. A terminating rounded-size recursion tree has O(n) leaves, so constant leaf costs do not alter the upper bound. The root alone costs 7n, giving Ω(n), hence Θ(n), C. Literal qualification: exact real-valued subproblem sizes never reach 0 from positive n, and the only printed base case is n=0. Integer rounding or a positive-size cutoff is therefore implicit; without such a convention the displayed recursion is not a terminating algorithm.
An induction makes the linear upper bound concrete: for floor-rounded subproblems and n≥1, assume T(k)≤Ck+D for smaller k. Then T(n)≤.9Cn+2D+7n, so any C sufficiently above 70 absorbs the constant excess for large n; enlarge constants for finitely many small cases. Alternatively a positive cutoff and geometric level sum yield the same result. Applying the equal-subproblem Master theorem directly would be invalid because the two recursive sizes differ.
Let R_n be the maximum revenue from cutting a rod of integer length n into one or more integer-length pieces. Prices for lengths 1,...,7 are 1,5,8,9,10,17,18. Select all true statements: A R7=18; B R7=19; C R7 is achieved by three different solutions; D no three-piece solution achieves R7. Different piece orders are not different cutting solutions.
Select all that apply
Answer & solution
Official answer: A; C
With R0=0 and Rn=max1≤i≤n(p[i]+Rn−i), the values R1,…, R7 are 1, 5, 8, 10, 13, 17, 18. Revenue18 is achieved by exactly the three unordered partitions 7; 6+1; 3+2+2. The last uses three pieces, so D is false, and 19 is not attainable. Hence A, C. Different orders of the same piece lengths are not counted as distinct cutting solutions.
Dynamic-programming pseudocode: R[0]=0; for length=1..7: R[length]=max(price[i]+R[length−i] for i=1..length). At length 7 the candidates for first piece sizes 1..7 are 18,18,18,17,15,18,18. Backtracking optimal candidates and sorting piece lengths gives {7},{1,6},{2,2,3}; different first-piece choices can lead to the same sorted partition, so count each only once. The recurrence is exhaustive because every nonempty cutting solution has some first piece and an optimally solved remainder.
For a DFS tree T of a connected undirected graph G, select all true statements. A its root can never be an articulation point; B its root is an articulation point iff it has at least two DFS children; C a DFS leaf can be an articulation point; D if u is an articulation point, x is its ancestor and y its descendant in T, every graph path x→y must pass through u.
Select all that apply
Answer & solution
Official answer: B
The DFS root is an articulation point exactly when it has at least two DFS children. Distinct child subtrees have no connecting edge in an undirected DFS, whereas one child subtree remains connected after deleting the root. This proves B and disproves A. A DFS leaf cannot disconnect the remaining DFS tree when removed, so C is false. D is too strong: use edges x-u, u-y, y-x, u-z and DFS order x, u, y, z. Vertex u is an articulation point because its removal isolates z, but the edge x-y avoids u even though x is its ancestor and y its descendant.
For a nonroot vertex u, the actual test is whether some DFS child v has low[v]≥discovery[u], meaning that child's subtree lacks a back-edge to a strict ancestor of u. It does not assert that every descendant is trapped. The counterexample in the main derivation separates a trapped branch z from a branch y that can reach ancestor x by a back-edge. For the root, two distinct child subtrees cannot connect except through the root, or DFS would have explored them as one subtree.
For connected undirected weighted G: S1 some minimum-weight edge belongs to every MST; S2 distinct edge weights imply a unique MST. A both true; B only S1; C only S2; D neither.
Your answer
Answer & solution
Official answer: C
An equal-weight triangle has three MSTs, each omitting a different minimum-weight edge, so no edge belongs to every MST. This refutes S1. Distinct edge weights ensure a unique MST by the cut/exchange property, so S2 is true. Thus C.
For S1 the quantifier “every MST” is crucial: a minimum edge is safe for some MST, but ties can let another edge replace it. For S2 suppose two MSTs differ and choose the lightest edge in their symmetric difference. Adding it to the other tree creates a cycle containing a heavier edge from that difference; exchanging them lowers the weight, a contradiction.
What is the worst-case number of arithmetic operations in recursive binary search on a sorted n-element array? A Θ(√n); B Θ(log₂ n); C Θ(n²); D Θ(n).
Your answer
Answer & solution
Official answer: B
Each binary-search call performs constant arithmetic and reduces the remaining interval by roughly one half. The worst-case recurrence is T(n)=T(n/2)+Θ(1), so Θ(log n), B, under the standard unit-cost arithmetic model.
After j unsuccessful comparisons, at most about n/2j candidates remain. Reaching one candidate needs j≈log₂n. A call computes a midpoint and adjusts bounds using a constant number of arithmetic operations. This counts operations, not bit complexity of arbitrary-precision index arithmetic.
Encode abbccddeee with a binary prefix code. Among equal-frequency letters, earlier dictionary letters must have code length no greater than later ones. Find minimum encoded length. A 21; B 23; C 25; D 30.
Your answer
Answer & solution
Official answer: B
The frequencies are 1, 2, 2, 2, 3. Huffman merging costs are 3, 4, 6, 10, totaling 23 bits, the optimal weighted path length. The dictionary tie rule can also be met: assign b=00, c=01, e=10, a=110, d=111. Then lengths of b, c, d are 2, 2, 3, and total length is 3+4+4+6+6=23. Thus B.
Huffman repeatedly merges the two smallest available weights: 1+2=3; 2+2=4; 3+3=6; 4+6=10. Each merge adds its weight once to the encoded length because all leaves below it gain one bit. The displayed code is prefix-free and satisfies the alphabetical tie restriction, so the unrestricted Huffman lower bound is attainable with the extra condition.
T(n)=aT(n/b)+f(n), a>1,b>1. Let d=log_b a. A f=n log₂n implies T=Θ(n log₂n); B f=n/log₂n implies T=Θ(log₂n); C f=O(n^(d−ε)), ε>0 implies T=Θ(n^d); D f=Θ(n^d) implies T=Θ(n^d). Choose correct statement under usual running-time recurrence conventions.
Your answer
Answer & solution
Official answer: C
For the standard running-time recurrence with positive constant base cost, nonnegative work, and terminating integer-size conventions, write d=logb a. If f(n)=O(nd−ε) for ε>0, work per level increases geometrically toward the leaves and total cost is Θ(nd), Master Theorem case1, C. Equal-order work in D adds a logarithmic factor. A lacks a condition on a, b, and B is already smaller than its own n/log n root work.
At recursion depth j, there are aj nodes of size n/bj, and height logb n. Leaves number alogb n=nd. For polynomially smaller f, the sum is bounded by a geometric series of that order. At equal order every level instead costs Θ(nd), so D misses Θ(log n) levels. Taking a=b and f=n log n also refutes A, giving Θ(n log²n).
Directed graph is the 4×4 vertex grid in the embedded figure; S is bottom-left. A no topological order; B DFS from S classifies exactly three directed edges as back edges; C no strongly connected component; D every ordered pair is mutually reachable.
Select all that apply
Answer & solution
Official answer: A; B
Label grid positions (row, column), top to bottom and left to right. There are three nontrivial SCCs, each a directed four-cycle: {(3, 1),(4, 1),(4, 2),(3, 2)}, {(3, 3),(4, 3),(4, 4),(3, 4)}, and {(1, 2),(2, 2),(2, 3),(1, 3)}. Other vertices are singleton SCCs. Each directed cycle contributes exactly one DFS back edge; edges between SCCs cannot be back edges, since a back edge would make its endpoints mutually reachable. All vertices are reachable from S, so DFS finds exactly three back edges, B. The cycles preclude a topological order, A. C is false, and D is false because the top-right vertex is a sink and cannot reach S.
In each four-cycle, DFS follows the sole internal successor until the closing edge points to a gray ancestor, giving one back edge. Exploring outgoing edges to other components cannot create another such ancestor return, because that would imply a return path and merge the components. A graph always has SCCs, even if all were singletons; C is therefore also terminologically wrong.
DAG vertices s,a,b,c,d,e,f,g,t. Edges with weights: s→a 9,s→c 1,a→b 1,a→d 1,c→d 1,c→f 9,d→e 9,d→g 9,b→e 1,f→g 1,g→t 1,e→t 9. Path score is edge-weight product; vertex score is largest path score from s; score(s)=1. Find sum of all vertex scores.
Answer & solution
Official answer: 929
Step through it (10 steps)
Process vertices topologically with Q(v)=max over predecessors u of Q(u)*weight(u, v), starting Q(s)=1. The diagram yields Q(a)=9, Q(c)=1, Q(b)=9, Q(d)=max(1, 9)=9, Q(f)=9, Q(e)=max(9, 81)=81, Q(g)=max(9, 81)=81, Q(t)=max(81, 729)=729. Sum=1+9+1+9+9+9+81+81+729=929.
A topological dynamic program initializes score(s)=1 and all other scores=0, then for each edge u→v sets score(v)=max(score(v),score(u)×weight). A predecessor ordering such as s,a,b,c,d,e,f,g,t suffices. It runs in O(V+E), since a DAG has no profitable cycle to revisit. Store parent pointers when maximizing if an actual maximizing path is also wanted.
For parameters a,b, both printed as ω(1), T(n)=T(n^(1/a))+1 and T(b)=1. Choose the printed asymptotic expression. Options: A Θ(log_a(log_b n)); B Θ(log_(ab) n); C Θ(log_b(log_a n)); D Θ(log_2(log_2 n)). No cutoff for inputs below b is specified; retain this qualification.
Your answer
Answer & solution
Official answer: A
Our answer: A under the intended recurrence-depth convention
Worked explanation
Unroll without changing the logarithm bases: T(n)=T(n1/a²)+2=…=T(n1/a^j)+j. Exact termination at b requires n1/a^j=b, or (ln n)/aj=ln b. Thus aj=ln n/ln b=logb n. Taking log base a yields the expression in A, with total value j+1. This derivation assumes a,b are held fixed during a recursion chain, even if their initial values depend on the original input size. It does not justify swapping a and b as in C. The rigorous cutoff-based estimate is Θ(1+max(0,loga(logb n))) in the regime n>1,a>1,b>1, with ceiling for integral depth.
Derivation and answer
After j recursive calls the argument is n1/a^j. Equating it to b gives aj=logb n, hence j=loga(logb n) and T(n)=j+1 on exact-depth inputs. With a base cutoff at n≤b, the corresponding depth is max(0, ceil(loga(logb n))) for fixed call parameters a, b>1. This gives intended A when the depth is bounded below away from 0, in particular when it grows. Qualification: the source says a, b are ω(1), not fixed constants, and gives only T(b)=1. Arbitrary inputs need a cutoff/rounding convention, and the additive 1 cannot always be dropped when parameters vary. For example a=n, b=log n gives depth 1 under the cutoff, but loga(logb n) tends to 0. Thus the printed unconditional Theta claim requires a parameter regime/termination convention.
A weighted undirected graph has MST T maintained in adjacency lists. A new weighted edge (u,v) is added. Without an additional preprocessed path-query index, what is the worst-case time to decide whether T remains an MST? A Θ(|E|+|V|); B Θ(|E||V|); C Θ(|E| log |V|); D Θ(|V|).
Your answer
Answer & solution
Official answer: D
Worked explanation
Let e be the new edge and P the unique u-v path in T. If w(e)<max weight on P, replace a maximum-weight path edge by e; the resulting spanning tree is strictly lighter, so T fails. Conversely, if w(e)≥that maximum, consider any competing tree using e. Removing e separates it into two parts; P crosses that cut at some tree edge f with w(f)≤w(e). Replacing e by f gives an old-graph spanning tree no heavier than the competitor. Since T was minimum among old trees, no new competitor is lighter. A DFS of T visits at most |V|−1 edges, carrying the path maximum. No need to rerun an MST algorithm on all of G.
Derivation and answer
Adding edge(u, v) creates one cycle with the unique u-v path in T. T remains minimum exactly when the new weight is at least the maximum weight on that tree path. A DFS of the adjacency-list tree finds the path and its maximum in O(|V|), and an unpreprocessed path-like tree can force inspection ofΘ(|V|) edges. ThusΘ(|V|), D.
A directed weighted graph has reweighted edges w′(u,v)=w(u,v)+f(u)−f(v), with f:V→R. Shortest paths are preserved: A for every f; B iff f is everywhere positive; C iff f is everywhere negative; D iff f gives shortest distances from a new source joined to all vertices by zero-weight edges.
Your answer
Answer & solution
Official answer: A
Worked explanation
For a path v0=s,v1,…,vk=t, summing the added terms gives f(v0)−f(v1)+f(v1)−f(v2)+…+f(vk−1)−f(vk)=f(s)−f(t). Intermediate contributions cancel pairwise. Thus for two s-t paths P,Q, w′(P)−w′(Q)=w(P)−w(Q), preserving strict inequalities and ties. The signs of individual potentials do not matter. Choosing shortest-distance potentials is useful in Johnson’s algorithm to make edge weights nonnegative, but that is an additional goal; it is not necessary for path-order preservation. This argument compares common endpoints, not unrelated paths with different sources or destinations.
Derivation and answer
For any path from s to t, the added potentials telescope: sum[w(u, v)+f(u)−f(v)]=original path weight+f(s)−f(t). All paths with the same endpoints receive the same constant, so their relative order and shortest paths are unchanged for every real-valued f, A. Cycle weights are unchanged too; this does not create finite shortest paths where reachable negative cycles originally prevented them.
Similar questions2 more → · asked again: GATE 2006, Q11
Graph Algorithms
Tap to enlarge
The complete undirected graph has vertices v1,…,v100 and edge (vi,vj) for every 1≤i<j≤100, with weight |i−j|. Find its MST weight.
Answer & solution
Official answer: 99
Worked explanation
A spanning tree is connected and acyclic on all 100 vertices, hence has exactly 99 edges. Here i≠j makes every weight |i−j| a positive integer, at least 1. Thus 99 is a universal lower bound. Choose precisely the edges (v1,v2),(v2,v3),…,(v99,v100). They form a path through every vertex, so are a valid spanning tree, and every edge has weight 1. Their sum is 99, attaining the bound. Taking all weight-one edges happens to work because they form this path; merely selecting individually cheap edges would not prove connectivity in a general graph.
Derivation and answer
Every edge has positive integer weight at least 1, and every spanning tree on 100 vertices has 99 edges, so its total weight is at least 99. The path v1-v2-...-v100 uses 99 consecutive-index edges of weight 1 and attains that bound. Hence the MST weight is 99.
Quicksort is applied to 25 distinct elements, choosing the first pivot uniformly among them. Find the probability that the first partition puts the pivot in a worst possible position, rounded to two decimal places.
Answer & solution
Official answer: 0.08
Method: characterize the pivot ranks that make the two recursive subproblems maximally unequal.
1. If the pivot has sorted rank r among 25 distinct elements, partitioning leaves r−1 elements smaller and 25−r larger. 2. The worst split is 0 and 24, leaving almost the entire problem for one recursive branch. This occurs when r=1 (minimum pivot) or r=25 (maximum pivot). 3. Exactly two of the 25 possible pivots have those ranks. Uniform selection makes each pivot equally likely, so the probability is 2/25=0.08.
Result: 0.08 to two decimal places. This asks only about the first split. It is not the probability that every later recursive call also takes its worst split, nor does a bad first pivot alone prove that the whole execution has the maximum possible running time.
For A=[−5,−10,6,3,−1,−2,13,4,−9,−1,4,12,−3,0], find the maximum S(i,j)=sum of A[k] for k=i through j, with 0≤i≤j<14. The chosen elements must form a contiguous segment.
Answer & solution
Official answer: 29
Method: use Kadane's dynamic program. Let E[j] be the largest sum of any nonempty segment ending exactly at j. Such a segment either starts at j or extends the best segment ending at j−1.
1. The recurrence is E[0]=A[0]=−5 and E[j]=max(A[j],E[j−1]+A[j]). It is exhaustive because every segment ending at j has one of those two forms. 2. At indices 0 and 1, E is −5 then max(−10,−15)=−10. At index 2, starting afresh with 6 beats extending the negative prefix, so E[2]=6 and the candidate segment starts at index 2. 3. Continue through indices 3 to 7: E values are 9,8,6,19,23. Although −1 and −2 reduce the running sum, discarding the accumulated positive prefix would be worse. 4. For indices 8 to 13 the values are 14,13,17,29,26,26. The maximum across all E values is 29, achieved at j=11. 5. Recover the segment from i=2 through j=11: 6+3−1−2+13+4−9−1+4+12=29. The negative terms inside it must remain because the segment is contiguous. 6. Since every segment has some ending index j and E[j] is optimal for that ending index, taking the largest E[j] proves that no omitted segment has a greater sum.
Result: 29. The prompt permits divide and conquer but does not require it; this linear-time recurrence gives the same optimum and a direct correctness argument.
There are n unsorted arrays, n odd, each containing n distinct elements; different arrays have no common elements. Find the worst-case complexity of computing the median of the n array medians. Choices A O(n), B O(n log n), C O(n²), D Ω(n² log n).
Your answer
Answer & solution
Official answer: C
1. The median of n distinct values for odd n is their order statistic of rank (n+1)/2. Finding that one rank does not require sorting every value. 2. Apply deterministic worst-case linear-time selection to each array. The median-of-medians selection algorithm, for example, finds an exact order statistic in O(n) time per array. 3. There are n arrays, so obtaining all their medians costs n×O(n)=O(n²). Store the n resulting medians in a separate array. 4. Apply linear-time selection once more to those n medians. This adds O(n), so the total remains O(n²), identifying C. The desired statistic is the median of array medians, which is not in general the median of all n² input values. 5. Sorting each original array would cost O(n² log n) and is unnecessary. Worst-case exact selection on arbitrary unsorted rows requires inspecting linearly many entries in potentially decisive rows; the general problem has quadratic worst-case scale, not O(n) or O(n log n) in the row count n. Randomized quickselect offers expected linear selection, but deterministic selection is what directly justifies the worst-case bound here.
For a connected weighted undirected graph G, test: I distinct weights on all edges imply a unique MST; II every cut having a unique cheapest crossing edge implies a unique MST. Options A I only, B II only, C both, D neither.
Your answer
Answer & solution
Official answer: C
1. Use the cut property: if an edge is the unique lightest edge crossing some cut, every minimum spanning tree must contain it. Otherwise adding it to an MST forms a cycle containing another crossing edge, and replacing that heavier edge makes a cheaper spanning tree. 2. To prove II, choose any MST T and remove one of its edges e. The remaining components define a cut. Edge e must be a cheapest crossing edge: a strictly cheaper one could reconnect the components and improve T. 3. Under II the cheapest crossing edge is unique, so e is that unique edge. By step 1, every MST must contain e. This reasoning applies to each edge of T. 4. Any other MST must therefore contain all |V|−1 edges of T and hence equal T. This proves II. 5. If every edge weight in the graph is distinct, each nonempty cut automatically has a unique cheapest crossing edge. Thus I implies the condition of II and is also true. Answer C. These are sufficient conditions for uniqueness; the question does not require proving that all edge weights must be distinct in every graph with a unique MST.
For a simple undirected graph, I says DFS has no cross edge between unrelated vertices; II says every graph edge joins BFS depths differing by exactly 1. Which must hold? A I only; B II only; C both; D neither.
Your answer
Answer & solution
Official answer: A
Method
If an undirected DFS edge led to a still-unvisited vertex, DFS would explore it before returning, making that vertex a descendant. If the vertex is already on the recursion stack it is an ancestor; an edge to a completed unrelated subtree would have discovered the current vertex earlier. For BFS, shortest-path distances differ by at most 1 across an edge. A triangle rooted at one vertex places the other two at depth 1 and still has an edge between them, disproving “exactly”.
Solution
In undirected DFS, an edge to an undiscovered vertex is explored before the current DFS call completes, so every non-tree edge joins an ancestor and descendant; no cross edges, making I true. BFS edges can connect equal-depth vertices, for example the edge joining the two non-root vertices of a triangle. The necessary inequality is |i−j|≤1, not equality 1. Thus only I, A.
Matrices F1…F5 have dimensions 2×25,25×3,3×16,16×1,1×1000. Multiplying p×q by q×r costs pqr scalar operations. Which adjacent original pairs are directly multiplied in an optimal parenthesization? A F1F2 and F3F4; B F2F3; C F3F4; D F1F2 and F4F5.
Your answer
Answer & solution
Official answer: C
Step through it (12 steps)
Method
The dynamic-programming state M[i,j] is the minimum scalar cost of multiplying the consecutive subchain; a split k adds the costs of its two subchains and their final product. This systematically tests all parenthesizations without a local greedy assumption. In the winning chain, F3F4 first produces 3×1 at cost 48; F2 times that gives 25×1 at cost 75; F1 times that gives 2×1 at cost 50; multiplying F5 costs 2000. Only the first operation multiplies two original matrices directly.
Solution
Use matrix-chain DP: M[i, j]=mink(M[i, k]+M[k+1, j]+d[i−1]d[k]d[j]). Dimensions are 2, 25, 3, 16, 1, 1000. Pair costs are 150, 1200, 48, 16000; three-matrix optimal costs 246, 123, 3048; four-matrix costs 173, 25123. Splitting the full chain after F1, F2, F3, F4 costs 75123, 9198, 48246, 2173 respectively. The unique optimum is((F1(F2(F3F4)))F5), costing 48+75+50+2000=2173. Its only directly multiplied original pair is F3F4, C.
Name graph vertices top T, left L, bottom-left B, bottom-right C, right R. Edges: TL=4,LB=4,TB=1,BC=4,TC=3,TR=x,CR=5. Choose x to maximize the number of minimum-weight spanning trees; report that number.
Answer & solution
Official answer: 4
Method
The cut property forces a uniquely lightest edge across a cut into every MST. Across {B}, TB=1 is strictly less than LB=4 and BC=4; across {C}, TC=3 is less than BC=4 and CR=5. Contract these two forced edges to a central component. Connecting L has two tied cost-4 choices. Connecting R has two choices only when x=5. These choices are independent and each yields four edges with no cycle, so their product counts actual spanning trees, not merely edge subsets.
Solution
Name the top vertex T, bottom-left B, bottom-right C, left L and right R. Edge TB of weight 1 is uniquely cheapest across the cut {B}; TC of weight 3 is uniquely cheapest across {C}. Both must be in every MST, independently of x. Contract them. L can connect to that component by either of its two weight 4 edges. R can connect by TR of weight x or CR of weight 5. At x=5 both choices tie, giving 2*2=4 MSTs. Otherwise only one right edge is cheapest and there are 2. The remaining BC edge would form a cycle with the two mandatory edges and cannot be chosen. Thus the maximum count is 4.
Capacity is 11 kg. Single available items (weight,value) are 1:(10,60),2:(7,28),3:(4,20),4:(2,24). Items cannot split. Greedy scans descending value/weight, taking items that fit. Find optimal value minus greedy value.
Answer & solution
Official answer: 16
Step through it (2 tables)
Method
The ratio order is item 4 then 1 then 3 then 2. Taking item 4 leaves 9 kg, so item 1 no longer fits. Item 3 then fits and leaves 5 kg, too little for item 2. To verify optimality, item 1 alone gives 60 and cannot pair with even the smallest other item. Without item 1, feasible pairs (2,3),(2,4),(3,4) have values 48,52,44; all three weigh 13 and are infeasible. Thus exhaustive feasible alternatives confirm the optimum.
Solution
Value/weight ratios order the items as 4, 1, 3, 2, with ratios 12, 6, 5, 4. Greedy takes item4 (weight 2, value 24), skips item1 because it no longer fits, then takes item3 (weight 4, value 20), and skips item2. Its value is 44. The best feasible subset is item1 alone, value 60: pairs among 2, 3, 4 have maximum 52, all three weigh13, and item1 cannot accompany any other item under capacity 11. Hence60−44=16.
Arrange 10, √n, n, log₂n, 100/n in increasing asymptotic complexity. A log₂n,100/n,10,√n,n; B 100/n,10,log₂n,√n,n; C 10,100/n,√n,log₂n,n; D 100/n,log₂n,10,√n,n.
Your answer
Answer & solution
Official answer: B
1. Compare eventual growth rather than the values at a particular small n. The reciprocal 100/n tends to zero while 10 stays constant.
2. log₂n is unbounded, but log₂n/√n→0. Also √n/n=1/√n→0. These limiting ratios put logarithm below square root below linear growth.
3. Consequently 100/n < 10 < log₂n < √n < n in asymptotic growth, option B. Constants such as 100 do not reverse eventual ordering.
Match P Kruskal, Q Quicksort, R Floyd–Warshall to i divide and conquer, ii greedy, iii dynamic programming. A P-ii Q-iii R-i; B P-iii Q-i R-ii; C P-ii Q-i R-iii; D P-i Q-ii R-iii.
Your answer
Answer & solution
Official answer: C
1. Kruskal sorts edges by weight and repeatedly accepts a cheapest edge that does not form a cycle. This is the greedy paradigm ii.
2. Quicksort partitions around a pivot, recursively sorts the two resulting parts, and combines their order: divide and conquer i.
3. Floyd–Warshall updates distances by allowing intermediate vertices one at a time: Dk[i,j]=min(Dk−1[i,j],Dk−1[i,k]+Dk−1[k,j]). Reused subproblem values make it dynamic programming iii. Thus C.
In any connected undirected graph with positive distinct edge weights, are these necessarily true? I the minimum spanning tree is unique; II the shortest path between any two vertices is unique. A I only; B II only; C both; D neither.
Your answer
Answer & solution
Official answer: A
1. For uniqueness of the MST, suppose two different minimum trees exist. Select the lightest edge in their symmetric difference and add it to the tree not containing it.
2. The resulting cycle has an edge belonging to that tree but not the other. This edge is heavier because weights are distinct and the chosen edge was lightest in the difference. Exchanging them strictly reduces weight, contradicting minimality. Thus I is true.
3. Distinct edge weights do not make path sums distinct. In a triangle with weights 1,2,3 the direct weight-3 edge ties the 1+2 route. II fails, so A.
An array of 31 entries consists of zeros followed by ones. Find the smallest index i with A[i]=1 using the minimum number of array probes. What is an optimal algorithm’s worst-case probe count?
Answer & solution
Official answer: 5.0
Our answer: 5
1. A probe returns one bit: if A[mid]=0 the first one lies to the right; if A[mid]=1 it lies at mid or to the left. This monotonicity permits binary search.
2. Balanced probing halves the candidate boundary positions each time. Five probes suffice for 31 first-one positions, or 32 possibilities if an all-zero sentinel is allowed.
3. For optimality, a binary decision tree of depth four has at most 24=16 leaves, fewer than 31 distinguishable answers. Thus no algorithm can guarantee four probes. The optimal worst case is 5, not a linear scan of 31.
Match P:Towers of Hanoi with n disks; Q:binary search of n sorted numbers; R:worst-case heapsort of n numbers; S:addition of two n×n matrices. Complexities i:Θ(n²), ii:Θ(n log n), iii:Θ(2^n), iv:Θ(log n). Options (P,Q,R,S): A:(iii,iv,i,ii), B:(iv,iii,i,ii), C:(iii,iv,ii,i), D:(iv,iii,ii,i).
Your answer
Answer & solution
Official answer: C
1. Hanoi moves n-1 disks away, moves the largest disk once, then moves n-1 disks back: T(n)=2T(n-1)+1=2n-1, so P→iii.
2. Binary search halves the candidate interval each time; after k comparisons about n/2k candidates remain. Reaching one requires Θ(log n) comparisons, so Q→iv.
3. Heapsort builds a heap in O(n) and performs n extractions costing O(log n) each in the worst case, giving Θ(n log n): R→ii. Matrix addition performs one addition at each of n² positions, giving S→i. Select C.
An undirected graph has vertices M,N,O,P,Q,R and edges MN,NO,MR,MQ,NQ,OQ,OP,PQ. Which is a possible BFS visiting order, with the first vertex as the start? A:MNOPQR. B:NQMPOR. C:QMNROP. D:POQNMR.
Your answer
Answer & solution
Official answer: D
Step through it (4 options)
1. BFS removes vertices from a FIFO queue and discovers all vertices at a smaller distance before any at a larger distance. For D, start at P and enqueue its neighbors O then Q. The visited prefix is P,O,Q.
2. Processing O discovers N; its other neighbors P and Q are already discovered. Processing Q then discovers M, with N already queued. Processing N adds nothing, and processing M finally discovers R. The resulting order is P,O,Q,N,M,R.
3. A fails from M because O at distance 2 precedes its distance-1 neighbors Q and R. B fails from N because P at distance 2 precedes O at distance 1. C fails from Q because R at distance 2 precedes O and P at distance 1. Thus D is possible; BFS neighbor ordering need not be alphabetical.
T(n)=2T(√n)+1 for n>2, and T(n)=2 for 0<n≤2. What is its asymptotic order? A:Θ(log log n). B:Θ(log n). C:Θ(√n). D:Θ(n).
Your answer
Answer & solution
Official answer: B
1. The argument shrinks by square root, so transform to its logarithm. Put m=log₂n and S(m)=T(2m). Since √(2m)=2m/2, the recurrence becomes S(m)=2S(m/2)+1 with a constant base for m≤1.
2. This is a binary recursion tree with Θ(m) leaves and Θ(m) total nodes. Equivalently, the Master theorem has a=2,b=2 and f(m)=1, giving S(m)=Θ(m).
3. Substituting back gives T(n)=Θ(log n), option B. The recursion depth is only Θ(log log n), but each level branches into twice as many subproblems. Counting depth alone misses the total work.
For positive n, C code executes: for(i=1;i<=n;i++){ for(j=1;j<n;j+=i){ printf(" %d %d",i,j); } }. Find its Θ time complexity, treating each iteration/output as unit cost. A:Θ(n√n). B:Θ(n²). C:Θ(n log n). D:Θ(n² log n).
Your answer
Answer & solution
Official answer: C
1. Fix i. The inner-loop j values are 1,1+i,1+2i,… below n, so there are ceil((n-1)/i) iterations. The step size is i, not 1; different outer-loop iterations therefore have different costs.
2. Sum over i=1,…,n. Ignoring rounding gives (n-1)Σ1/i=(n-1)Hn. Rounding adds at most n operations, and Hn=Θ(log n), so the total is Θ(n log n).
3. The outer-loop overhead is only Θ(n) and does not change the result, giving C. This is the conventional unit-cost model used by the question. Counting the individual decimal digits written by printf, or fixed-width integer overflow at extreme n, would be a different analysis from the intended asymptotic loop count.
A message uses symbols P,Q,R,S,T with probabilities 0.22,0.34,0.17,0.19,0.08 respectively. For a 100-character message encoded with binary Huffman coding, what is the expected encoded length in bits?
Answer & solution
Official answer: 225.0
Our answer: 225
1. Huffman coding repeatedly merges the two smallest current weights. Merge T and R:0.08+0.17=0.25. Next merge S and P:0.19+0.22=0.41. The remaining weights are 0.25,0.34,0.41; merge 0.25+0.34=0.59, then 0.41+0.59=1.
2. The resulting depths are 2 for P,Q,S and 3 for R,T. One valid code assignment is S=00,P=01,T=100,R=101,Q=11; swapping branch labels changes codewords but not lengths.
3. Expected bits per symbol are 2(0.22+0.34+0.19)+3(0.17+0.08)=1.5+0.75=2.25. Equivalently sum the merge weights 0.25+0.41+0.59+1=2.25. For 100 symbols the expectation is 225 bits, excluding codebook/container overhead. It is an expectation, not a guarantee for every possible 100-symbol sequence.
Count the topological orders of the directed graph with vertices {a,b,c,d,e,f} and exactly the edges a→b, b→c, c→f, a→d, d→e, e→f. These two directed branches are the complete content of the source diagram.
Answer & solution
Official answer: 6.0 : 6.0
Our answer: 6
Step through it (8 steps)
The graph consists of a→b→c→f and a→d→e→f. Vertex a must come first and f last. Interleave the two ordered middle chains(b, c) and(d, e), choosing their two positions among four: C(4, 2)=6.
After fixing a and f, the middle orders are bcde, bdce, bdec, dbce, dbec, debc. Each respects b before c and d before e. Choosing the two positions occupied by b,c determines the remaining positions for d,e, giving the binomial coefficient without listing all 4! permutations. A topological order need not follow a single path; it is any ordering in which every directed edge points forward.
Select the worst-case running times of insertion sort, merge sort, and quicksort, in that order. A: Θ(n log n), Θ(n log n), Θ(n^2). B: Θ(n^2), Θ(n^2), Θ(n log n). C: Θ(n^2), Θ(n log n), Θ(n log n). D: Θ(n^2), Θ(n log n), Θ(n^2).
Your answer
Answer & solution
Official answer: D
Insertion sort may shift Θ(n) elements on each of n insertions, giving Θ(n²). Merge sort uses Θ(n) work across each of Θ(log n) levels, giving Θ(n log n). Quicksort’s most unbalanced partitions give n+(n−1)+...+1=Θ(n²). Thus D.
For reverse-sorted input, insertion sort shifts 1+2+...+(n−1) elements. Merge sort's balanced divide-and-conquer recurrence T(n)=2T(n/2)+Θ(n) yields Θ(n log n) regardless of initial order. Quicksort can repeatedly choose an extreme pivot, leaving subproblems of sizes 0 and n−1, so its recurrence becomes T(n)=T(n−1)+Θ(n). Its average-case or expected randomized Θ(n log n) bound must not be substituted for this requested worst-case bound.
In a connected weighted undirected graph with distinct positive edge weights, add the same positive amount to every edge weight. Evaluate P: the minimum spanning tree is unchanged; Q: the shortest path between every pair is unchanged. A: P only. B: Q only. C: neither. D: both.
Your answer
Answer & solution
Official answer: A
Every spanning tree has |V|−1 edges, so adding a constant c to each edge adds the same c(|V|−1) to every tree’s weight, preserving the unique MST. Paths may have different edge counts: triangle weights 1, 2, 4 initially favor 1+2 over 4, but adding 2 makes the direct 6 shorter than 3+4. Thus only P, A.
The invariant for trees is equal edge count, not merely preserved ordering of individual edge weights. Compare two trees T1,T2: the added terms cancel in their weight difference. By contrast a k-edge path gains kc, and another path with fewer edges gains less. The triangle counterexample demonstrates an actual reversal while retaining positive, distinct edge weights, so Q fails as a universal statement even though some particular graphs keep their shortest paths.
A four-vertex weighted undirected graph has weight matrix W with rows (0,2,8,5), (2,0,5,8), (8,5,0,x), (5,8,x,0). Find the largest integer x for which some shortest path between some pair uses the edge of weight x.
Answer & solution
Official answer: 12.0 : 12.0
Our answer: 12
Without edge 3–4, the shortest route between its endpoints is 3→2→1→4 of length 5+2+5=12; the two-edge alternatives both cost 13. Any edge heavier than an alternative endpoint path cannot occur in a shortest path, since replacing it improves the route. At x=12 the edge itself ties the shortest endpoint route, so the largest integer is 12.
It suffices to compare x against the best route between its own endpoints that avoids that edge. Any shortest path using a heavier edge could be improved by substituting that alternative segment. The relevant routes from 3 to 4 have costs 13 via 1,13 via 2,12 via 2 then 1, and 18 via 1 then 2; thus 12 is the threshold. Equality is allowed because the question requires at least one shortest path, not a uniquely shortest path. At x=12, the direct edge is itself a shortest 3-to-4 path.
A complete undirected graph on 4 vertices has its 6 edges assigned the distinct weights 1,2,3,4,5,6. Over all assignments, find the largest possible weight of its minimum spanning tree.
Answer & solution
Official answer: 7.0 : 7.0
Our answer: 7
Kruskal always accepts edges 1 and 2. If edge 3 does not make a triangle, it completes the tree and total is 6. If edges 1, 2, 3 form a triangle, edge 3 is rejected and the next edge 4 must join the fourth vertex, giving total 7. Assigning 1, 2, 3 to one triangle and 4, 5, 6 to the remaining incident edges attains 7.
Kruskal processes weights in increasing order and cannot reject either of the first two edges of a simple graph: a cycle requires at least three. If the first three edges do not form a triangle, they connect all four vertices and total 6. Otherwise they occupy three vertices, and every remaining edge joins that triangle to the fourth vertex, so edge 4 is necessarily accepted. This proves the upper bound 7 and the triangle arrangement witnesses attainability over all 720 weight assignments.
In a simple undirected graph with distinct edge weights and an MST, consider edge e. I: If e is the lightest edge of some cycle, every MST includes e. II: If e is the heaviest edge of some cycle, every MST excludes e. Which statements are true? A:I only. B:II only. C:both. D:neither.
Your answer
Answer & solution
Official answer: B
The unique heaviest edge of a cycle is excluded by the cycle property, so II holds. I fails: take edges ab=3, bc=4, ca=5, ad=1, db=2. Edge ab is the lightest in triangle abc but the heaviest in triangle adb, hence excluded from the MST. Thus II only, B, assuming the connected graph/MST component context.
The valid cycle property concerns the heaviest edge: if a tree used it, deleting it creates a cut, and the rest of that cycle contains a lighter edge crossing the cut. Swapping would lower tree weight, contradicting minimality. The lightest edge of a cycle has no symmetric guarantee, because it might be a heavy choice relative to another route outside that cycle. Do not confuse it with the cut property, which guarantees inclusion of the unique lightest edge crossing a cut.
For ascending sorted input, assess: I quicksort is Θ(n²); II bubblesort is Θ(n²); III mergesort is Θ(n); IV insertion sort is Θ(n). A I,II only; B I,III only; C II,IV only; D I,IV only. The source supplies no implementation details.
Your answer
Answer & solution
Official answer: D
Our answer: D under textbook implementation conventions
With first/last-element pivot selection, sorted input gives quicksort Θ(n²). An early-exit bubble sort detects no swaps after one pass and takes Θ(n), ordinary mergesort remains Θ(n log n), and insertion sort takes Θ(n). These conventions make I and IV true, D. The names alone do not determine these cases: a balanced/randomized-pivot quicksort need not be quadratic, unoptimized bubble sort can be quadratic, and adaptive mergesort can be linear. The official answer requires the stated implementation choices.
The quadratic quicksort recurrence is T(n)=T(n−1)+Θ(n), whose level costs add to Θ(n²). The insertion-sort best case makes one failed comparison per new item, hence linear work. Standard merging processes n elements at each of log n levels. These derivations explain the official convention rather than falsely treating algorithm names as complete implementations.
Which paradigm underlies Floyd–Warshall all-pairs shortest paths? A greedy; B divide-and-conquer; C dynamic programming; D none of these.
Your answer
Answer & solution
Official answer: C
Floyd–Warshall maintains shortest distances whose allowed intermediate vertices come from the first k vertices, updating dk(i, j)=min(dk−1(i, j), dk−1(i, k)+dk−1(k, j)). Reusing these subproblems is dynamic programming, C.
Define Dk(i,j) as the best i-to-j path using only vertices 1,…,k internally. Such a path either avoids k or decomposes through k into two earlier subproblems. Initialize D0 with edge weights, zero diagonals and infinity for absent edges. Iterating k,i,j uses Θ(V³) time and can reuse one distance matrix.
Code for positive X,Y: int exp(int X,int Y){int res=1,a=X,b=Y; while(b!=0){if(b%2==0){a=a*a;b=b/2;}else{res=res*a;b=b-1;}}return res;}. Which invariant holds before every iteration? A X^Y=a^b; B (res*a)^Y=(res*X)^b; C X^Y=res*a^b; D X^Y=(res*a)^b.
Your answer
Answer & solution
Official answer: C
Our answer: C under no-overflow arithmetic
The invariant is X^Y=res·a^b, C. Initially res=1, a=X, b=Y. An even step replaces(a, b) by(a², b/2), preserving a^b. An odd step multiplies res by a and decreases b by 1, preserving the product. At termination b=0, res=X^Y. This mathematical proof assumes intermediates fit the C int type; arbitrary positive inputs can overflow signed int and then lack defined C behavior.
For example X=2,Y=3 gives states (res,a,b)=(1,2,3),(2,2,2),(2,4,1),(8,4,0). The invariant product is 8 at each state. Option A fails once a factor moves into res; option D incorrectly raises res to b. Initialization, preservation and termination are three distinct obligations in a loop-invariant proof.
Matrices A1,A2,A3,A4 have dimensions 10×5,5×20,20×10,10×5. Find the minimum number of scalar multiplications using ordinary matrix multiplication to compute their product.
Answer & solution
Official answer: 1500.0 : 1500.0
Our answer: 1500
Step through it (8 steps)
Use A1((A2A3)A4): A2A3 costs 5·20·10=1000 and yields 5×10; multiplying A4 costs 5·10·5=250 and yields 5×5; multiplying A1 costs 10·5·5=250. Total 1500. The five full parenthesizations cost 1750, 1500, 3000, 2000, 3500, so 1500 is minimal.
Matrix-chain DP uses M(i,j)=min over k of M(i,k)+M(k+1,j)+di−1dk dj, with M(i,i)=0. For d=(10,5,20,10,5), two-matrix costs are 1000,1000,1000; three-matrix optima are M(1,3)=1500 and M(2,4)=1250. Splitting the full chain after A1 then costs 1250+250=1500.
A recursive flowchart starts with A(n/2), then branches. Left: call A(n/2), return. Right: call A(n/2) twice, then branch to return or call A(n/2) and branch again to return or one final A(n/2) then return. All other work is O(1); assume a constant-size base case and attainable recursive worst branches. Find the least α for worst-case O(n^α), to two decimals.
Answer & solution
Official answer: 2.2 : 2.4
Our answer: log₂5 ≈2.32
Assuming the displayed worst branch can recur and a constant-size base case, T(n)=5T(n/2)+O(1), yielding Theta(nlog₂5). The least exponent islog₂5≈2.32; the official accepted interval 2.2 : 2.4 is preserved.
Only calls on a single executed control-flow path are added. The two alternative exits must not both be counted. At recursion level j, the worst-case tree has 5j calls of size n/2j; after log₂n levels it has 5log₂n=nlog₂5 leaves. This yields the exponent without mistaking five sequential calls for five levels of recursion.
An undirected simple graph with n vertices and m edges uses adjacency lists. Entries [v] in u’s list and [u] in v’s list are twins. With unrestricted auxiliary memory, find the best time to set all twin pointers. A Θ(n²); B Θ(n+m); C Θ(m²); D Θ(n⁴).
Your answer
Answer & solution
Official answer: B
Number vertices 0..n−1. Scan the adjacency lists and record each entry’s pointer together with the ordered endpoint pair(min(u, v), max(u, v)). Two stable counting-sort passes on the endpoint labels sort all 2m records in O(n+m) time. Consecutive equal pairs are twins, so link their pointers in O(m). Scanning the n list heads and writing the 2m pointers gives the matching linear input/output bound in the adjacency-list model. Thus Θ(n+m), B; the algorithm uses allowed auxiliary memory without initializing an n² matrix.
Give each adjacency entry a record (min endpoint,max endpoint,address). Integer vertex labels permit stable counting sorts instead of comparison sorting’s extra logarithm. Simplicity ensures exactly two records per undirected edge, so matching neighbors after sorting is unambiguous. A dense n-by-n matrix is unnecessary and initializing it would lose the linear bound for sparse graphs.
Match algorithms P Prim MST, Q Floyd–Warshall all-pairs shortest paths, R mergesort, S Hamiltonian circuit search with i backtracking, ii greedy, iii dynamic programming, iv divide-and-conquer. A P-iii Q-ii R-iv S-i; B P-i Q-ii R-iv S-iii; C P-ii Q-iii R-iv S-i; D P-ii Q-i R-iii S-iv.
Your answer
Answer & solution
Official answer: C
Prim greedily adds a cheapest edge crossing the current tree's cut. Floyd–Warshall builds shortest paths by increasing the allowed intermediate vertices, a dynamic-programming recurrence. Mergesort solves two smaller sorting problems and merges their answers. A standard Hamiltonian-circuit search tries vertices and abandons partial paths that cannot extend, illustrating backtracking.
Solution: Prim uses greedy selection; Floyd–Warshall uses dynamic programming; mergesort uses divide and conquer; the standard Hamiltonian-circuit search uses backtracking. Thus P-ii, Q-iii, R-iv, S-i, C.
For n≥2, choose the worst-case quicksort recurrence; c is constant. A T(n)=2T(n/2)+cn; B T(n)=T(n−1)+T(1)+cn; C T(n)=2T(n−1)+cn; D T(n)=T(n/2)+cn.
Your answer
Answer & solution
Official answer: B
Worst-case pivots repeatedly leave one side with nearly every remaining element. Treat the constant-size side's cost as O(1), yielding T(n)=T(n−1)+Θ(n). Unrolling accumulates n+(n−1)+…+2=Θ(n²). A represents balanced splitting, C duplicates the large subproblem, and D omits one half of a balanced sort. Printed B uses T(1) for constant work.
Solution: The most unbalanced quicksort split leaves one nontrivial subproblem of size n−1 and constant base-case work, plus cn partition work. Hence the listed recurrence T(n)=T(n−1)+T(1)+cn, B, gives Θ(n²).
G is a simple undirected graph, s a source, d(x) shortest distance from s, and T a BFS tree. For an edge (u,v) not in T, which cannot equal d(u)−d(v)? A −1; B 0; C 1; D 2.
Your answer
Answer & solution
Official answer: D
An edge gives a one-step extension of a shortest path: d(u)≤d(v)+1 and d(v)≤d(u)+1. Combining gives −1≤d(u)−d(v)≤1. BFS non-tree edges can connect two vertices on the same level or consecutive levels; being non-tree does not force equal levels. Distances must be finite, so interpret u,v as vertices in the explored source component.
Solution: For any edge joining reachable vertices u, v, a shortest path to v followed by that edge proves d(u)≤d(v)+1, and symmetrically d(v)≤d(u)+1. Hence their distances differ by at most 1, so 2 is impossible, D. The restriction to a non-tree edge does not change the bound; same-level and adjacent-level non-tree edges can occur. Distances are understood within the source component, since subtraction of two infinite unreachable distances is not defined.
Graph vertices A,B,C,D,E,F; edges AB,AC,BC,BE,CD,DE,DF,EF. All eight weights are distinct integers. Its MST has weight 36 and edges AC=9,BC=2,BE=15,EF=4,DF=6. Find the minimum total of all eight edges.
Answer & solution
Official answer: 69
Adding a non-tree edge creates one cycle. If its weight were below the largest edge on that tree path, replacing that tree edge would give a lighter spanning tree. Distinctness forces a strict inequality. AB's path maximum is 9, CD's is 15, and DE's is 6, so their least integer choices are 10,16,7. These choices do not clash with any existing weight. The cycle conditions are also sufficient to preserve this MST, establishing attainability, not merely a lower bound. Total is 36+33=69.
Solution: For a tree to remain the MST with distinct weights, every non-tree edge must be heavier than the maximum edge on its tree path. AB must exceed max(AC9, CB2)=9, so at least 10. CD must exceed max(CB2, BE15, EF4, FD6)=15, so at least 16. DE must exceed max(DF6, FE4)=6, so at least 7. Values10, 16, 7 are mutually distinct and different from the given tree weights, and satisfy all cycle conditions. Minimum total is 36+10+16+7=69.
C function: int fun1(int n){int i,j,k,p,q=0;for(i=1;i<n;++i){p=0;for(j=n;j>1;j=j/2)++p;for(k=1;k<p;k=k*2)++q;}return q;}. Which most closely approximates its return value? A n³; B n(log n)²; C n log n; D n log(log n).
Your answer
Answer & solution
Official answer: D
The first inner loop computes p≈log₂n but never increments q. The second loop increments q for k=1,2,4,… below p, about log₂p times. Multiplying by n−1 outer iterations gives Θ(n log log n). This asks for the returned number, not running time: computing p itself costs Θ(log n) each iteration, so the code's runtime is Θ(n log n). Mathematical asymptotics assume integers do not overflow.
Solution: The outer loop runs n−1 times. Repeated integer halving of j from n until≤1 gives p=floor(log₂n). Doubling k from 1 while k<p increments q ceil(log₂p) times when p≥1. Thus for sufficiently large n the return value is(n−1)*ceil(log₂ floor(log₂n))=Θ(n log log n), D. This is the mathematical count under no-overflow arithmetic; q can overflow a fixed-width int for sufficiently large inputs.
An unordered list has n distinct elements. What is the asymptotic number of comparisons needed to find an element that is neither maximum nor minimum? AΘ(nlogn), BΘ(n), CΘ(logn), DΘ(1), assuming n≥3.
Your answer
Answer & solution
Official answer: D
Assuming n≥3, inspect any three distinct elements and return their median using at most three comparisons. It has a smaller and larger element within those three, so cannot be the global minimum or maximum. A constant positive number of comparisons suffices and is necessary, Θ(1), D.
Choose any three distinct list elements and compare them to identify their middle value. That value is larger than one chosen element and smaller than another, so it cannot be an extreme of the full list. This uses at most three comparisons regardless of n. At least some information is needed to certify a nonextreme value on arbitrary unsorted data, so the asymptotic requirement is constant. For n<3 no such value exists, which is why that natural premise is stated.
Match algorithms 1Dijkstra, 2Floyd–Warshall, 3 binary search, 4 backtracking with i divide/conquer, ii dynamic programming, iii greedy, iv DFS, v BFS. A1i2 iii 3i4v; B1 iii 2 iii 3i4v; C1 iii 2 ii 3i4 iv; D1 iii 2 ii 3i4v.
Dijkstra commits the currently smallest tentative distance using a greedy safe-choice argument. Floyd–Warshall improves paths by allowing successively larger sets of intermediate vertices, which is dynamic programming. Binary search reduces the search interval to one half, matching divide-and-conquer here. Backtracking explores one partial-choice path before undoing it and trying another, so its traversal is depth-first rather than breadth-first. The complete matching is 1 iii, 2 ii, 3i, 4 iv.
partition(a, n)moves first-element pivot to end of left part and prose says it returns left part COUNT. Skeleton sets p=partition(a, n); if(p+1==k)return a[p]; if(p+1>k)return kth_smallest(…); else return kth_smallest(…). Missing calls: A(a, p, k), (a+p+1, n−p−1, k−p−1); B(a, p, k), (a, n−p−1, k−p−1); C reverse A calls; D(a, n−p−1, k−p−1), (a, p, k). The fixed code instead requires pivot INDEX.
Your answer
Answer & solution
Official answer: A
Our answer: A only if partition returns zero-based pivot index
With pivot index p, its rank is p+1. The left recursive call uses(a, p, k); the right uses(a+p+1, n−p−1, k−p−1), giving A. However the prose explicitly says partition returns the left-part COUNT, which is p+1. The fixed skeleton then compares the wrong rank and accesses the wrong element; no option repairs that. Correct by assigning left_end=partition(a, n)−1 or changing the function contract to return the pivot index. Official A retains this index interpretation.
If p were the zero-based pivot index, its rank would be p+1. Recursing left keeps the same base pointer and k but changes length to p. Recursing right advances past the pivot byp+1 and subtracts that many elements from both length and rank. These are A’s arguments. But the prose-returned count is p+1 already; assigning it to p makes the fixed equality and a[p] off by one before either missing call runs. Thus no choice repairs the literal contract. A applies only after changing the contract or subtracting 1 on assignment.
Let X=Σ(i³), i=0,...,n. Which asymptotic descriptions of X are valid? I: Θ(n⁴); II: Θ(n⁵); III: O(n⁵); IV: Ω(n³). Options: (A) only I; (B) only II; (C) I or III or IV, but not II; (D) II or III or IV, but not I.
Your answer
Answer & solution
Official answer: C
1. The exact polynomial is n⁴/4+n³/2+n²/4. Its leading term supplies a two-sided Θ(n⁴) bound; a looser upper bound n⁵ and looser lower bound n³ remain valid, whereas a two-sided n⁵ bound does not.
2. Sum(i³, i=0..n)=[n(n+1)/2]²=Θ(n⁴). It is consequently O(n⁵) and Ω(n³), but not Θ(n⁵). Thus I, III, IV, C; equality to an asymptotic class is conventional membership notation.
A mergesort implementation takes 30 seconds in the worst case for an input of size 64. Using its standard asymptotic running-time model, which option most closely approximates the maximum input size solvable in 6 minutes? (A) 256; (B) 512; (C) 1024; (D) 2048.
Your answer
Answer & solution
Official answer: B
1. Using the standard dominant-term model T(n)=c n log₂n, the time increases by 360/30=12.
2. Hence n log₂n≈12·64·6=4608. For n=512, 512·9=4608, so B. Lower-order implementation overhead is ignored in this approximation.
A connected undirected graph G has 100 vertices and 300 edges. The weight of a minimum spanning tree is 500. If the weight of every edge in G is increased by 5, what is the new minimum spanning-tree weight?
Answer & solution
Official answer: 995
1. The 300 graph edges do not all belong to the spanning tree. Connectedness makes every spanning tree have exactly |V|−1=99 edges, so the increment is 99·5 rather than 300·5. Because all candidate trees receive the same increment, a previously minimum tree remains minimum.
2. Every spanning tree on 100 vertices has 99 edges. Adding5 to every edge increases every spanning-tree weight by exactly 495, preserving their ordering and the set of minimum spanning trees. The new minimum weight is 500+495=995.
DOSOMETHING(c,a,n) receives a bit array c[0..k−1] and positive integers a,n. It sets z=1; then for i=0,...,k−1 sets z=z² mod n, and, if c[i]=1, sets z=(z×a) mod n; finally it returns z. For k=4, c=(1,0,1,1), a=2, n=8, what is returned?
Answer & solution
Official answer: 0
1. Iteration details: bit 1 gives 1²·2 mod 8=2; bit 0 gives 2² mod 8=4; bit 1 gives (4² mod 8)·2 mod 8=0; the last bit 1 keeps the value 0. Each iteration squares before the optional multiplication.
2. The loop processes the binary exponent 1011 from most significant bit to least. The successive z values modulo 8 are 2, 4, 0, 0: square and multiply by 2 when the current bit is 1. Equivalently it computes 211 mod8=0.
Let f(n)=n and g(n)=n^(1+sin n), for positive integers n, with sine measured in radians. Which asymptotic statements hold? I: f(n)=O(g(n)); II: f(n)=Ω(g(n)). Options: (A) I only; (B) II only; (C) both; (D) neither.
Your answer
Answer & solution
Official answer: D
1. The ratio g(n)/f(n)=nsin n.
2. Since1/(2π) is irrational, integer n modulo 2π is dense, and every tail is dense. There are therefore arbitrarily large n with sin n≥1/2 and arbitrarily large n with sin n≤−1/2. Along the former subsequence g/f≥sqrt(n) is unbounded, ruling out f=Ω(g); along the latter f/g≥sqrt(n) is unbounded, ruling out f=O(g). Thus neither statement holds, D, with sine in radians.
A graph has n vertices and m edges and is stored as an adjacency matrix. What is the tightest asymptotic upper bound for a complete depth-first search? A: Θ(n). B: Θ(n+m). C: Θ(n²). D: Θ(m²).
Your answer
Answer & solution
Official answer: C
1. Method and setup. For adjacency lists, examining neighbors costs the degree of the current vertex. With a matrix, locating all neighbors requires inspecting n possible entries even for a low-degree vertex. A full DFS forest covers disconnected components too, so all n rows are scanned.
2. Work through the result and its assumptions. DFS scans an entire adjacency-matrix row for each visited vertex. A full traversal visits all n vertices, giving n rows of n entries and Θ(n²) time, C.
A directed graph has vertices P,Q,R,S and exactly the edges P→Q, P→R, R→Q, S→R, S→Q. Which statement holds? A: No topological ordering exists. B: Both PQRS and SRQP are topological orderings. C: Both PSRQ and SPRQ are topological orderings. D: PSRQ is the only topological ordering.
Your answer
Answer & solution
Official answer: C
Step through it (2 orders)
1. Method and setup. Topological order must place the tail of every edge before its head. Initially P and S have indegree zero. Both must precede R, and R must precede Q. There is no edge imposing an order between P and S, so either may appear first.
2. Work through the result and its assumptions. The edges require P and S before R, and R before Q; there is also P→Q and S→Q. P and S may occur in either order, giving exactly PSRQ and SPRQ. Thus C.
Quicksort sorts ascending using the first element as pivot. Let t₁ be its comparison count on [1,2,3,4,5] and t₂ the count on [4,1,5,3,2]. Which holds? A: t₁=5. B: t₁<t₂. C: t₁>t₂. D: t₁=t₂. Use the conventional partitioning comparison model.
Your answer
Answer & solution
Official answer: C
Our answer: C under standard linear partition comparisons
Step through it (2 runs)
1. Method and setup. With the first-element pivot, an already sorted list always selects the smallest remaining value, producing maximally unbalanced recursive subproblems. For the second list, pivot 4 separates three smaller elements from one larger element. Bounding the cost of sorting that three-element side suffices; its exact partition order is unnecessary.
2. Work through the result and its assumptions. Sorted input with first-element pivot repeatedly splits 0 versus n−1, using 4+3+2+1=10 pivot comparisons. The second input first splits 3 versus 1, so its total is 4 plus at most 3 within the three-element side, at most 7. Thus t1>t2, C. This is the usual partition comparison model, not arbitrary redundant implementation tests.
What is the minimum worst-case number of comparisons needed to find both the minimum and maximum of 100 numbers?
Answer & solution
Official answer: 147.1 to 148.1
Our answer: 148 worst-case comparisons
1. Method and setup. Finding extrema separately takes 99+99 comparisons and wastes information. Pair the elements: one comparison per pair identifies a candidate for the minimum and a candidate for the maximum. Thereafter only the pair-losers need participate in the minimum search and only the pair-winners in the maximum search.
2. Work through the result and its assumptions. Compare50 disjoint pairs. Find the minimum among 50 smaller values in 49 comparisons and maximum among 50 larger values in 49. Total 50+49+49=148. This matches the optimal worst-case lower bound ceil(3n/2)−2; an adversary forces enough first comparisons to classify candidates before eliminating all but one in each class.
Pseudocode sets D=2, then loops i=1..n, j=i..n, k=j+1..n, performing D=D*3 once per innermost iteration. How many multiplications occur? A: Half the product of three consecutive integers. B: One-third the product of three consecutive integers. C: One-sixth the product of three consecutive integers. D: None of these.
Your answer
Answer & solution
Official answer: C
1. Method and setup. Count valid index triples rather than estimating every loop as n iterations. For a fixed j, index i can take j values and k can take n−j values. Multiplying those independent choices and summing over j gives an exact count; the assignment D=2 performs no multiplication.
2. Work through the result and its assumptions. For each middle index j there are j choices of i and n−j choices of k. The number of multiplications is sum(j=1..n)j(n−j)=n·n(n+1)/2−n(n+1)(2n+1)/6=(n−1)n(n+1)/6, one-sixth the product of three consecutive integers, C.
Solve asymptotically T(n)=2T(n/2)+log n with T(1)=1. A Θ(n); B Θ(n log n); C Θ(n²); D Θ(log n).
Your answer
Answer & solution
Official answer: A
1. Set up the reasoning. Apply the Master theorem with a=2 and b=2: nlogb a=n. The extra work log n grows polynomially more slowly than n, for example log n=O(n1/2).
2. Derive the result. For T(n)=2T(n/2)+log n, the leaf contribution is n. At level i, extra cost is 2i(log₂n−i); its total over levels is O(n). Equivalently log n is polynomially smaller than n in the Master theorem. Therefore T(n)=Θ(n), A.
3. Check the interpretation. There are n constant-cost leaves, which already force an Ω(n) lower bound. The logarithmic work is not multiplied by n at every level; subproblem sizes shrink, and summing the level costs gives O(n).
Run BFS from W in a connected, undirected, unweighted graph and retain its tree edges in T. This tree supports which task? A shortest paths between every vertex pair; B shortest paths from W to every vertex; C shortest paths from W only to leaves of T; D a longest path in the graph.
Your answer
Answer & solution
Official answer: B
1. Set up the reasoning. BFS assigns a vertex to the earliest reachable distance layer. When a vertex is first discovered, its parent is one layer closer to W, so following parents yields a path of exactly that shortest distance.
2. Derive the result. BFS explores vertices in increasing edge-distance from W. Parent pointers in the BFS tree therefore reconstruct a shortest path from W to every vertex. They need not preserve shortest paths between arbitrary other pairs. Thus B.
3. Check the interpretation. The guarantee is rooted at W and covers internal vertices as well as leaves. A non-tree edge may shorten the route between two other vertices, so one BFS tree is not an all-pairs shortest-path representation.
Sorted sequences P,Q,R,S,T have lengths 20,24,30,35,50. Merge two sequences at a time until one remains. Find the minimum possible worst-case total number of comparisons.
Answer & solution
Official answer: 358
1. Set up the reasoning. A merge of lengths a and b needs a+b-1 comparisons in the worst case. The optimal merge-pattern rule repeatedly joins the two currently shortest sequences, reinserting the combined length.
2. Derive the result. Optimal merging repeatedly combines the two shortest lists: 20+24=44, 30+35=65, 44+50=94, 65+94=159. A merge of lengths a, b uses at most a+b−1 comparisons, so total 43+64+93+158=358. The shortest-pair rule minimizes weighted leaf depth, as in Huffman coding.
3. Check the interpretation. Track lengths after each merge: 44 joins the queue after 20 and 24; 65 after 30 and 35; then combine 44 and 50. Subtract one comparison for each of the four merges, not just once from the final length.
How many distinct MSTs does the illustrated undirected weighted graph have? Textual equivalent: label left cluster vertices A top-left, B top-right, C middle-left, D center, E middle-right, F bottom-left; right triangle G bottom-left, H top, I bottom-right. Edges: AB=2, AC=2, AD=1, BD=2, BE=1, CD=2, CF=1, DE=2, DF=1, FG=2, GH=2, HI=1, GI=2. No other edges exist.
Answer & solution
Official answer: 6
Step through it (15 steps)
1. Set up the reasoning. Run Kruskal by weight groups. Weight-one edges AD,BE,CF,DF,HI form a forest, so include them and contract each connected component before counting choices among weight-two edges.
2. Derive the result. The weight 1 edges form an acyclic forest and all are included before any weight 2 edge by Kruskal. In the left component, contraction leaves three parallel weight 2 choices joining its two weight 1 components. The long horizontal bridge of weight 2 is mandatory. In the right triangle, the weight 1 edge is mandatory and either of the two weight 2 edges connects the third vertex. Thus independent choices give 3·2=6 MSTs. The remaining left weight 2 edges internal to contracted components cannot be used.
3. Check the interpretation. After contraction, the left cluster has three parallel choices AB,BD,DE between its two components. FG is the only connection to the right cluster and is compulsory. On the right choose GH or GI. The independent choices yield 3×1×2 trees, each with eight edges and total weight 11.
The undirected graph consists of two 3×3 square grids, each with horizontal and vertical edges only between adjacent grid vertices. Label their vertices L(r,c) and R(r,c), rows and columns 1…3 from top-left. Add connector v with edges L(3,3)−v−R(3,1), a pendant vertex u attached only to v, and pendant w attached only to R(2,3). Recursive DFS starts at an unspecified vertex and calls visit only after confirming the neighbor is unvisited. Find the maximum possible call-stack depth, including the initial call.
Answer & solution
Official answer: 19
Step 1: Active DFS calls form a simple path because an already visited vertex is never recursively called. Conversely, a desired simple path can be followed first by a suitable starting vertex and neighbor order. Step 2: A path spanning both grids must pass through connector v using its two grid edges; it cannot also visit pendant u without revisiting v. It uses at most nine left-grid vertices. Step 3: On the right, color the 3×3 grid like a checkerboard. A Hamilton path through all nine vertices starting at R(3,1), in the five-vertex color class, must end in that same color class. The pendant w attaches at R(2,3), in the opposite class, so a path entering at R(3,1) cannot include all nine grid vertices and then w. The right side contributes at most nine vertices including w. Step 4: Thus a spanning path has at most 9+1+9=19 vertices. Paths not spanning both grids are shorter, even with pendant leaves. Step 5: Attain 19 by snaking through all left vertices from L(1,1) to L(3,3), crossing v, then snaking through all right vertices from R(3,1) to R(1,3). DFS can follow this path before exploring unused pendants. The maximum depth is 19.
Quicksort on n elements always selects the element at the central array index as pivot. What is the tightest listed worst-case upper bound? A O(n²); B O(n log n); C Θ(n log n); D O(n³).
Your answer
Answer & solution
Official answer: A
Step 1: A central position in an array is not necessarily the median value. An adversarial ordering can place the smallest or largest current value at each selected pivot position. Step 2: Partitioning then leaves subproblems of sizes 0 and n−1 while doing Θ(n) work. The recurrence is T(n)=T(n−1)+Θ(n). Step 3: Summing the partition costs gives Θ(n+(n−1)+…+1)=Θ(n²). Therefore A is the tightest offered upper bound; O(n³) is true but weaker.
Move from 0 to 100 on the number line. One step either moves from k to k+1 or takes a supplied shortcut (i,j), i<j, directly from i to j. At most one shortcut involves any number; in particular 9 has a shortcut to 15. T(k) is the minimum steps from k to 100. If T(9)=1+min(T(y),T(z)), find yz.
Answer & solution
Official answer: 150
Step 1: Condition on the first move from 9. The ordinary unit move reaches 10; the available shortcut reaches 15. Each costs one step. Step 2: Once the first move is made, the optimal remaining cost is T(10) or T(15), so optimal substructure yields T(9)=1+min(T(10),T(15)). Step 3: The order of y and z is irrelevant: their product is 10×15=150. No knowledge of the remaining shortcuts is needed to identify these two immediate successor states.
Similar questions2 more → · asked again: GATE 2009, Q11
Selection-sort swap count
Searching, Sorting & Selection
Tap to enlarge
Give the tightest listed upper bound on selection-sort swaps for n numbers: A O(log n), B O(n), C O(n log n), D O(n²).
Your answer
Answer & solution
Official answer: B
Each selection-sort pass finds the minimum of the unsorted suffix and moves it using at most one swap. There are n−1 passes, and worst-case inputs require a linear number of swaps. Hence O(n), B; the quadratic comparison count does not imply quadratic swaps.
On pass i, selection sort scans the remaining suffix to locate its minimum, then swaps it into position i. It may perform many comparisons during that scan, but at most one swap. There are n−1 such passes, giving at most n−1 swaps. A cyclic displacement input can require a swap on each pass, so the worst-case number grows linearly, not logarithmically. The commonly remembered quadratic selection-sort cost counts comparisons, not swaps.
Which are true?1 Undirected-cycle detection is in P.2 It is in NP.3 Every NP-complete problem has a nondeterministic polynomial-time algorithm. A1, 2, 3; B1, 2; C2, 3; D1, 3.
Your answer
Answer & solution
Official answer: A
Undirected-cycle detection is polynomial via DFS or union-find, so it belongs to P and therefore also NP. By definition an NP-complete decision problem belongs to NP and has a nondeterministic polynomial-time algorithm. All three statements are true, A.
DFS detects an undirected cycle in O(V+E) time by finding an already visited neighbor other than the parent, so the first claim is polynomial. Every deterministic polynomial computation is also an allowed nondeterministic polynomial computation, giving P⊆NP and claim 2. NP-completeness includes membership in NP in its definition, not only NP-hardness, so claim 3 follows. No assumption that P≠NP is needed for any of these conclusions.
What is standard Bellman–Ford complexity on a complete n-vertex graph? AΘ(n²), BΘ(n²log n), CΘ(n³), DΘ(n³log n).
Your answer
Answer & solution
Official answer: C
The standard Bellman-Ford algorithm performs up to n−1 full edge-relaxation passes. A complete graph has Θ(n²) edges, yielding Θ(n³) time, C, for the usual worst-case/full-pass algorithm.
One relaxation pass examines all edges. The standard algorithm allows n−1 passes because a simple shortest path can use up to n−1 edges. A complete directed graph has n(n−1) edges; an undirected one has n(n−1)/2, both Θ(n²). Multiplying by Θ(n) passes gives Θ(n³). Early termination may improve a particular instance, but does not change the stated standard worst-case/full-pass bound.
How many elements can heapsort sort in Θ(log n) time? AΘ(1), BΘ(√log n), CΘ(log n/log log n), DΘ(log n).
Your answer
Answer & solution
Official answer: C
Let m be the number of elements. Heapsort takes Θ(m log m). Choosing m=Θ(log n/log log n) gives log m=Θ(log log n), so m log m=Θ(log n). Hence C; m=Θ(log n) would require an extra log log n factor.
Use a new variable m for the input length, since n only describes the time budget. Heapsort costs Θ(m log m). Set L=log n. The candidate m=L/log L has log m=log L−log log L=Θ(log L), so m log m=Θ(L). Constant m is too small, and m=√L gives Θ(√L log L)=o(L). Setting m=L instead gives Θ(L log L), which is too large. Thus the inverse scale is log n/log log n.
Besides constant-time Enqueue/Dequeue, MultiDequeue sets m=k and repeatedly dequeues while the queue is nonempty and m>0, decrementing m. Starting with an empty queue, find worst-case total time for n top-level operations: AΘ(n), BΘ(n+k), CΘ(nk), DΘ(n²).
Your answer
Answer & solution
Official answer: A
Let E be the number of Enqueue operations among the n top-level operations. Starting from an empty queue, at most E elements can be removed in total, whether by individual Dequeue calls or inside MultiDequeue. Therefore all successful inner-loop iterations together cost O(E)⊆O(n), not O(nk). Each top-level call and each terminating loop check contribute O(1), adding O(n). Conversely, n calls incur Ω(n) total overhead, and n Enqueue calls witness that bound. The worst-case total is Θ(n), option A, assuming constant-time primitive queue operations and constant-time arithmetic on the counter.
Charge every actual deletion to the earlier insertion that supplied that element. Since an element cannot be deleted twice without being inserted again, the total number of successful dequeues is no larger than the number of Enqueue operations, at most n. MultiDequeue also performs one final failing guard check, but there are at most n top-level calls to pay for those checks. This accounting bounds the complete sequence by a constant times n regardless of k. Multiplying the worst cost of one call by n would ignore the initially empty queue and double-count available elements.
The recurrence relation capturing the optimal execution time of the Towers of Hanoi problem with n discs is (A) T(n) = 2T(n − 2) + 2 (B) T(n) = 2T(n − 1) + n (C) T(n) = 2T(n/2) + 1 (D) T(n) = 2T(n − 1) + 1
Your answer
Answer & solution
Official answer: D
To move n discs, first move the top n−1 discs to the spare peg, move the largest disc once, then move those n−1 discs onto it. These two subproblems cannot be avoided in an optimal solution. Thus T(n)=2T(n−1)+1 with T(0)=0, yielding 2n−1 moves. Hence D.
Check: The largest disc cannot move until all n−1 smaller discs are off it, and afterward those smaller discs must be transferred onto it. With T(1)=1, the recurrence yields T(2)=3 and T(3)=7, consistent with 2n−1.
Let W(n) and A(n) denote respectively, the worst case and average case running time of an algorithm executed on an input of size n. Which of the following is ALWAYS TRUE? (A) A(n) = Ω(W(n)) (B) A(n) = Θ (W(n)) (C) A(n) = O (W(n)) (D) A(n) = o (W(n))
Your answer
Answer & solution
Official answer: C
At a fixed input size, each running time is at most the maximum W(n). Taking an expectation over any input distribution preserves the inequality A(n)≤W(n). Hence A(n)=O(W(n)), C. Equality in order can occur, ruling out an always-strict little-o claim; no matching lower bound is guaranteed.
Check: Average time depends on a distribution; worst-case time does not. If every input takes n steps then A=W=n, disproving an unconditional o bound. If a rare expensive input exists, the average can be much smaller, disproving an unconditional Θ bound.
Let G be a weighted graph with edge weights greater than one and G′ be the graph constructed by squaring the weights of edges in G. Let T and T′ be the minimum spanning trees of G and G′, respectively, with total weights t and t′. Which of the following statements is TRUE? (A) T′ = T with total weight t′ = t² (B) T′ = T with total weight t′ < t² (C) T′ ≠ T but total weight t′ = t² (D) None of the above
Your answer
Answer & solution
Official answer: Marks to All
Our answer: B under additional uniqueness and size assumptions
Squaring positive weights preserves every pairwise edge order and equality. Consequently it preserves the set of minimum spanning trees: any chosen MST of G remains an MST of G′, although independently chosen T and T′ can differ if the MST is not unique. For a fixed spanning tree with edge weights wi, its new weight is Σwi², while t²=Σwi²+2Σ_{i<j}w_iw_j. With at least two edges this gives t′<t²; with one edge there is equality. Thus B describes a consistent common choice of tree on at least three vertices, but the unqualified statement T′=T need not hold when multiple MSTs exist, and small graphs also matter. The official entry is Marks to All. These are independent qualifications, not a claimed official cancellation rationale.
Check: For an explicit nonuniqueness example, give every edge of a triangle weight 2. Any two edges form an MST, before and after squaring. T and T′ can therefore be chosen differently even though the collection of optimal trees is unchanged.
A list of n strings, each of length n, is sorted lexicographically using mergesort. What is the worst-case running time? (A) O(n log n) (B) O(n² log n) (C) O(n²+log n) (D) O(n²).
Your answer
Answer & solution
Official answer: Marks to All
Our answer: B under the standard character-comparison model
Ordinary mergesort uses O(n log n) comparisons to sort n strings. A lexicographic comparison can inspect all n characters, so the standard upper bound is O(n² log n), option B. The bound is tight in the usual character-by-character implementation: strings can share a prefix of length n−O(log n) and have suitably ordered distinct suffixes, so a worst-case merge pattern performs Θ(n log n) comparisons each costing Θ(n). Treating entire strings as unit-cost keys, using LCP-aware comparison, or restricting how many distinct strings exist changes the analysis; those are extra models not specified. The official entry remains Marks to All. No official reason for awarding marks is asserted.
Check: At each merge level O(n) string comparisons may be needed, and there are Θ(log n) levels. Multiplying by the worst-case Θ(n) character work per comparison gives Θ(n² log n) under the ordinary implementation, rather than counting comparisons as constant-time operations.
Run Dijkstra from S to T on the directed weighted graph below. Update a vertex’s path only when a strictly shorter path is found, never on an equal-distance tie. Which path is reported? The complete directed edge list (source,target,weight) is: (S,A,4), (S,B,3), (B,S,3), (S,D,7), (A,C,1), (B,D,4), (C,D,3), (C,E,1), (D,E,1), (D,F,5), (D,T,3), (E,G,2), (G,E,2), (E,T,4), (G,T,3), (T,F,5). (A) SDT (B) SBDT (C) SACDT (D) SACET.
Your answer
Answer & solution
Official answer: D
Step through it (27 steps)
After settling S, tentative distances are B=3, A=4 and D=7. Settling B offers D=3+4=7, an equal value that does not replace predecessor S. Settling A discovers C=5. Settling C discovers E=6; its edge to D offers 8 and is ignored. E is settled before D and gives T=6+4=10 with predecessor E (and G=8). D then offers T=7+3=10, which is equal and therefore cannot replace the predecessor. The path retained is S→A→C→E→T of length 10, option D. The graph’s G→E edge and T→F edge directions must not be reversed.
Check: The decisive relaxation is E→T, performed at distance 6 before D is settled at distance 7. Both propose distance 10, but only the first establishes T’s predecessor. Thus equal shortest lengths do not imply that a later equal path replaces the already stored path.
An array algorithm initializes L[n-1]=1 and for 0≤i≤n-2 defines L[i]=1+L[i+1] when A[i]<A[i+1], otherwise L[i]=1. It returns max(L[0],...,L[n-1]). The source calls this the longest monotonically increasing sequence. Which statement is TRUE?
(A) It uses dynamic programming (B) It has linear complexity and uses branch and bound (C) It has nonlinear polynomial complexity and uses branch and bound (D) It uses divide and conquer
Your answer
Answer & solution
Official answer: A
Compute the displayed Li from right to left, reusing the already-computed Li+1. This is a dynamic program with linear time and the maximum Li as output, so A. Its recurrence computes strictly increasing contiguous runs; it is not the general longest increasing subsequence algorithm when skipped elements are permitted. A suitable evaluation order is needed even though the source writes the index range without an order.
For the recurrence to run, process i=n-2,n-3,...,0. If adjacent entries increase, the run beginning at i is the current element followed by the already-solved run at i+1; otherwise it ends immediately. Each table entry takes constant work, and the final maximum takes linear work. For A=[1,3,2,4], every increasing contiguous run has length 2, although the noncontiguous subsequence [1,2,4] has length 3. This illustrates the important limitation of the displayed recurrence.
n log n grows slower than n3/2. The function nlog2 n=2^((log2 n)²) eventually exceeds every fixed power of n, but is smaller than 2n since(log2 n)²=o(n). Hence f3<f2<f4<f1 asymptotically, A.
Pairwise ratios justify the ordering beyond a few sample values. f3/f2=(log2 n)/√n tends to zero. Taking logarithms, log2(f4/f2)=(log2 n)²-(3/2)log2 n tends to infinity. Finally log2(f4/f1)=(log2 n)²-n tends to minus infinity. Thus the quasipolynomial sits above every fixed-degree polynomial but below the exponential. Finite small-n ties or reversals do not affect an asymptotic comparison.
Four matrices M1,M2,M3,M4 have dimensions 10×100,100×20,20×5,5×80. Multiplication of an a×b matrix by a b×c matrix costs abc scalar multiplications. What is the minimum total for their ordered product over all parenthesizations?
(A) 248000 (B) 44000 (C) 19000 (D) 25000
Your answer
Answer & solution
Official answer: C
Step through it (8 steps)
For dimensions 10, 100, 20, 5, 80, the five full parenthesizations have costs 25000 for(((AB)C)D), 19000 for((A(BC))D), 44000 for((AB)(CD)), 130000 for(A((BC)D)) and 248000 for(A(B(CD))). The minimum is 19000, attained by BC costing 100×20×5=10000, then A(BC) costing 10×100×5=5000, then the final product costing 10×5×80=4000. Thus C.
Label the matrices A,B,C,D. Dimensions of intermediate results matter: BC is 100×5, A(BC) is 10×5, and the final product is 10×80. Multiplying the dimensions of each operation yields the stated 10000+5000+4000 optimum. Checking all five full binary parenthesizations proves that this is a global minimum, not merely a good greedy choice. For example, doing AB first already costs 20000 before the remaining work, exceeding the optimum by itself.
An undirected graph has vertices v1,...,vn for n>2. Vertices vi and vj are adjacent exactly when 0<abs(i-j)≤2, and that edge has weight i+j. (For n=4 the edges are 12:3,13:4,23:5,24:6,34:7.) What is its minimum spanning-tree weight?
(A) (11n²-5n)/12 (B) n²-n+1 (C) 6n-11 (D) 2n+1
Your answer
Answer & solution
Official answer: B
For each vertex vi with i≥3, its lightest incident edge is (vi−2, vi), with weight 2i−2. The edge (v1, v2), of weight 3, is likewise the unique lightest edge incident to v1 and to v2. By the cut property all these edges must belong to an MST. They form two parity chains joined by (v1, v2), so they are connected and contain exactly n−1 edges, hence already form a spanning tree. Its weight is 3+sum from i=3 to n of (2i−2)=3+2[(n−1)n/2−1]=n²−n+1, option B.
For vertex vi with i≥3, possible smaller neighbors are v(i-2) and v(i-1), of weights 2i-2 and 2i-1; larger neighbors have still greater weights. Thus its distance-two backward edge uniquely minimizes the cut separating vi from all other vertices. The cut property forces every such edge, and also v1-v2. The odd-index chain and even-index chain are internally connected and joined by that last edge, showing the forced edges are sufficient, not merely a lower bound on the optimum.
Weighted path within the prescribed minimum spanning tree
Graph Algorithms
Tap to enlarge
An undirected graph has vertices v1,...,vn, edges precisely when 0<abs(i-j)≤2, and edge weight i+j. For n=10, what is the weighted length of the path from v5 to v6 in the minimum spanning tree of this graph?
(A) 11 (B) 25 (C) 31 (D) 41
Your answer
Answer & solution
Official answer: C
Step through it (19 steps)
The MST consists of (v1, v2) and (vi−2, vi) for i=3,..., 10. Its unique path from v5 to v6 is v5→v3→v1→v2→v4→v6. The edge weights are 8, 4, 3, 6 and 10, respectively, so its weighted length is 8+4+3+6+10=31, option C. The direct graph edge (v5, v6) has weight 11 but is not in the MST.
Write the two chains explicitly for n=10: odd vertices 1-3-5-7-9 and even vertices 2-4-6-8-10, joined by 1-2. Any route inside this tree from an odd to an even vertex must pass through that bridge. The requested route therefore goes downward in the odd chain to 1, crosses to 2, and climbs the even chain to 6. 'Length' here is total edge weight, not the number of edges; the path uses five edges but has weight 31.
A database contains 10^k records. To process n records, package A takes 0.0001n² time units and B takes 10n log₁₀n time units. What is the smallest offered value of k for which B is preferred to A? Options: (A) 12; (B) 10; (C) 6; (D) 5.
Your answer
Answer & solution
Answer: C (no official key was published)
Put n=10k. Package B is faster when 10·10k·k < 0.0001·102k, equivalently 10k−5>k. At k=5 this is 1>5, false; at k=6 it is 10>6, true. For positive integer k≤5, 10k−5≤1≤k, so 6 is the smallest positive integer exponent, C. The meaningful growing-database interpretation excludes the degenerate n=1 case k=0.
The inequality compares actual running-time formulas, not only asymptotic orders. At k=5, A=106 and B=5×106 time units, so A wins. At k=6, A=108 and B=6×107, so B wins. This illustrates why the smaller-growth algorithm need not be faster at small inputs when its constant factor is much larger.
The weight of a real sequence a₀,…,aₙ₋₁ is a₀+a₁/2+⋯+aₙ₋₁/2^(n−1). A subsequence deletes elements without changing the order. X is the maximum subsequence weight of a₀,…,aₙ₋₁ and Y is that of a₁,…,aₙ₋₁. What is X? Options: (A) max(Y,a₀+Y); (B) max(Y,a₀+Y/2); (C) max(Y,a₀+2Y); (D) a₀+Y/2.
Your answer
Answer & solution
Answer: B (no official key was published)
Split subsequences according to whether they include a₀. If not, their optimum weight is Y, the optimum on the suffix. If they do, a₀ contributes with weight 1 and each selected suffix element shifts one position, halving its contribution; the best such weight is a₀+Y/2. Thus X=max(Y,a₀+Y/2), B. The usual subsequence convention permits the empty subsequence, ensuring this also works with negative inputs.
The split is exhaustive and disjoint: every candidate either omits a₀ or contains it. Including a₀ shifts every chosen suffix element one weight position to the right, multiplying the entire suffix weight by 1/2; its internal order and relative weights are unchanged. Since 1/2 is positive, the suffix maximizing its own weight also maximizes the scaled weight. The outer maximum is necessary because including a negative a₀ can be harmful.
A complete undirected graph has vertices 0,1,2,3,4 and symmetric weight matrix W, with rows/columns in that order: [[0,1,8,1,4],[1,0,12,4,9],[8,12,0,7,3],[1,4,7,0,2],[4,9,3,2,0]]. What is the minimum weight of a spanning tree in which vertex 0 is a leaf? Options: (A) 7; (B) 8; (C) 9; (D) 10.
Your answer
Answer & solution
Answer: D (no official key was published)
Step through it (6 steps)
If vertex 0 is a leaf, removing it leaves a spanning tree on {1,2,3,4}; conversely any such tree plus one edge incident on 0 is feasible. Kruskal on the induced four-vertex graph chooses (3,4) of weight 2, (2,4) of weight 3, and (1,3) of weight 4, totaling 9. The cheapest edge from 0 has weight 1, either (0,1) or (0,3), hence the constrained minimum is 9+1=10, D. The unconstrained MST need not satisfy the leaf requirement.
The leaf constraint permits exactly one edge incident to 0. Therefore 0 cannot serve as a cheap connector joining vertices 1 and 3 through two weight-one edges. On vertices 1,2,3,4, the sorted edges begin 3–4:2, 2–4:3, 1–3:4; these three create no cycle and already connect all four vertices, proving the induced-tree minimum of 9.
A complete undirected graph has vertices 0,1,2,3,4 and symmetric weight matrix W, with rows/columns in that order: [[0,1,8,1,4],[1,0,12,4,9],[8,12,0,7,3],[1,4,7,0,2],[4,9,3,2,0]]. What is the minimum weight of a path from vertex 1 to vertex 2 containing at most three edges? Options: (A) 7; (B) 8; (C) 9; (D) 10.
Your answer
Answer & solution
Answer: B (no official key was published)
Step through it (14 steps)
The direct 1→2 path costs 12. With one intermediate vertex, costs via 0,3,4 are 9,11,12. With two distinct intermediate vertices, the six paths have costs: 1→0→3→2=9; 1→0→4→2=8; 1→3→0→2=13; 1→3→4→2=9; 1→4→0→2=21; 1→4→3→2=18. Thus minimum 8 is attained by 1→0→4→2, option B. All edge weights are positive, so adding a repeated-vertex cycle cannot improve a path within the edge limit.
An unconstrained shortest-path calculation is insufficient because it may return a path with four edges. Indeed 1→0→3→4→2 has weight 1+1+2+3=7 but violates the three-edge limit. Enumerating zero, one and two intermediate vertices is exhaustive for simple paths with at most three edges; the weight-eight candidate obeys the constraint.
Similar questions2 more → · asked again: GATE 2013, Q6
Selection-sort worst-case swaps
Searching, Sorting & Selection
Tap to enlarge
What is the worst-case number of swaps in selection sort on n elements? A Θ(n); B Θ(n log n); C Θ(n²); D Θ(n² log n).
Your answer
Answer & solution
Answer: A (no official key was published)
Each pass places one selected minimum using at most one swap, and there are n−1 passes. Inputs exist requiring a linear number of those swaps, so the worst-case swap count is Θ(n), A, despite Θ(n²) comparisons.
Selection sort scans the remaining suffix to find its minimum and moves that minimum into the next position. There are n−1 such placements and at most one swap per placement. Some inputs require a swap in a linear number of passes, giving a tight Θ(n) worst-case swap count. This differs from its Θ(n²) comparison count, since each pass may examine many elements before performing only one exchange.
For single-source Bellman–Ford, assess P: always detects a negative cycle if any exists; Q: detects whether a negative cycle is reachable from the source. A P only; B Q only; C both; D neither.
Your answer
Answer & solution
Answer: B (no official key was published)
Single-source Bellman-Ford detects a negative cycle reachable from that source by checking for a further relaxable edge after n−1 passes. A negative cycle in an unreachable component remains at infinite distance and need not be found. Therefore Q is true but P is not, giving B.
Bellman–Ford initializes only the source distance as finite. Vertices unreachable from it remain at infinity, so a disconnected negative cycle does not cause a finite relaxation. After |V|−1 passes, an additional successful relaxation among reachable vertices detects a reachable negative cycle. Therefore Q is true and P, which omits reachability, is false. Connecting a new super-source to every vertex would change the setup and allow global detection.
Problem π belongs to NP. Which assertion follows? A no polynomial algorithm exists; B a deterministic polynomial algorithm for π would imply P=NP; C if π is NP-hard then it is NP-complete; D π may be undecidable.
Your answer
Answer & solution
Answer: C (no official key was published)
A problem already in NP is NP-complete exactly when it is also NP-hard, so C. Membership in NP does not exclude membership in P, and solving an arbitrary NP problem efficiently would not by itself prove P=NP. Every NP decision problem is decidable.
NP-complete means both membership in NP and NP-hardness. Since membership is given, adding NP-hardness proves C directly. NP also contains easy problems in P, so a polynomial algorithm for an arbitrary member does not settle P versus NP. All NP languages are decidable by finite exhaustive certificate search, ruling out D, and A is not generally true.
T(n)=n for n≤3, otherwise T(n)=T(n/3)+cn with fixed c>0. Which growth rate? A Θ(n); B Θ(n log n); C Θ(n²); D Θ(n² log n).
Your answer
Answer & solution
Answer: A (no official key was published)
Expanding T(n)=T(n/3)+cn gives cn+cn/3+cn/9+... plus a constant-size base case. For fixed positive c this is bounded above by(3c/2)n+O(1) and below by cn. Hence Θ(n), A, with routine integer rounding not changing the asymptotic result.
The recursion tree has only one child, whose size shrinks by 3. Work by level is cn, cn/3, cn/9, … . The geometric sum is below cn/(1−1/3)=1.5cn, while the root alone contributes cn. These upper and lower linear bounds establish Θ(n). The depth is logarithmic, but multiplying n by that depth overcounts because work per level decreases rather than remaining n.
Weighted undirected graph edges ab 5, ac 3, bc 4, be 2, bd 6, cd 5, de 6, df 6, cf 6, ef 3, eg 5, fg 4. Which accepted-edge sequence cannot be Kruskal? A be, ef, ac, bc, fg, cd; B be, ef, ac, fg, bc, cd; C be, ac, ef, bc, fg, cd; D be, ef, bc, ac, fg, cd.
Your answer
Answer & solution
Answer: D (no official key was published)
Step through it (4 options)
Kruskal considers accepted edges in nondecreasing weight. The relevant weights are be 2, ef 3, ac 3, bc 4, fg 4, cd 5. Equal-weight 3 or 4 edges may be interchanged in the valid choices. D instead accepts bc of weight 4 before ac of weight 3, even though ac can be safely accepted at that point. Thus D is not a possible Kruskal acceptance order.
Kruskal sorts by edge weight and accepts an edge whenever it connects two different components. The unique weight 2 edge be comes first. Both weight 3 edges ef and ac can be accepted, in either order, before any weight 4 edge. The weight 4 pair bc, fg can also be exchanged. D violates this by putting bc before ac. At that point ac is not cyclic, so it cannot have been skipped. The other orders respect both sorted weights and cycle avoidance.
Quicksort selects the n/4-th smallest key as pivot using a linear-time selection algorithm. What is its worst-case time? A Θ(n); B Θ(n log n); C Θ(n²); D Θ(n² log n).
Your answer
Answer & solution
Answer: B (no official key was published)
Selecting the one-quarter order statistic in linear time gives recurrence T(n)=T(n/4)+T(3n/4−1)+Θ(n). Each recursion level has linear total work, and the longest/shortest nontrivial paths are logarithmic up to constants. Equivalently the Akra–Bazzi exponent is 1 because 1/4+3/4=1. Thus Θ(n log n), B, assuming rank partitioning is implemented appropriately for distinct keys or duplicates.
At each partition, linear-time selection plus partitioning costs Θ(n), and subproblems have sizes approximately n/4 and 3n/4. Both are fixed fractions, so recursion depth is Θ(log n); total size across a complete level remains proportional to n until leaves. Consequently total cost is Θ(n log n). Choosing the quarter-rank pivot is not perfectly balanced, but still prevents the n−1 versus 0 split responsible for quadratic quicksort.
Let l(i, j) be LCS length of prefixes of lengths i, j of zero-indexed X, Y. Boundary l=0 if either prefix empty; expr1 applies if last symbols match, expr2 otherwise. Which proposal is correct? A expr1=l(i−1, j)+1; B expr1=l(i, j−1); C expr2=max(l(i−1, j), l(i, j−1)); D expr2=max(l(i−1, j−1), l(i, j)).
Your answer
Answer & solution
Answer: C (no official key was published)
Let l(i, j) be the LCS length of the first i elements of X and first j elements of Y. If either prefix is empty, l(i, j)=0. When X[i−1]=Y[j−1], the matching final elements extend an optimal LCS of both shortened prefixes, so expr1=l(i−1, j−1)+1. If they differ, an LCS omits at least one of the two final elements, yielding expr2=max(l(i−1, j), l(i, j−1)). Only option C gives a correct proposed expression. A omits shortening Y in the matching case, B omits both the match increment and shortening X, and D is circular.
If the last symbols match, use that matched pair and extend the best solution for both shorter prefixes: l(i−1, j−1)+1. If they differ, a common subsequence must omit at least one of them, so take the larger of the two one-prefix-shortened values. Only C states a valid supplied formula. Option D references l(i, j) on its own right side and cannot define a bottom-up recurrence.
Store the LCS recurrence in L[m+1, n+1]. Which is true? A every cell must first be zero; B increasing row-major or column-major computation works; C neither works; D L[p, q] must precede L[r, s] whenever p<r OR q<s.
Your answer
Answer & solution
Answer: B (no official key was published)
Initialize only the empty-prefix boundary L[0, j]=L[i, 0]=0. Every other L[i, j] depends on L[i−1, j−1] in the matching case, or on L[i−1, j] and L[i, j−1] in the nonmatching case. Increasing-index row-major order computes all predecessors first; increasing-index column-major order also does so. Therefore B. Initializing every cell to zero is not necessary (A), and C contradicts these valid orders. D overstates the dependency: p<r alone does not require an arbitrarily far-right cell L[p, q] before L[r, s]; its OR condition can even demand opposite orders for incomparable cells such as (1, 2) and (2, 1).
The dependency arrows point left, up or diagonally up-left. Both increasing row order and increasing column order place all those predecessor cells before the current cell. Only row 0 and column 0 require initialization; every interior cell can be assigned when reached. The proposed OR ordering in D is too strong: cells(1, 2) and(2, 1) would each be required before the other. Therefore B.
What is the most efficient time complexity to count connected components in an undirected graph with n vertices and m edges?
(A) Θ(n) (B) Θ(m) (C) Θ(m+n) (D) Θ(mn)
Your answer
Answer & solution
Answer: C (no official key was published)
1. Maintain a visited flag for each vertex. Start a BFS/DFS at every vertex not yet visited and increment a component counter. 2. Each search visits precisely one previously unvisited component. Across all searches each vertex is processed once and each undirected edge twice. 3. With adjacency lists the total is Θ(n+m), C. The n term includes isolated vertices; an adjacency-matrix representation instead requires Θ(n²).
An undirected graph has vertices M,N,O,P,Q,R and edges MN,NO,OP,PQ,QM,QN,MR. Which is a possible queue-based breadth-first traversal?
(A) MNOPQR (B) NQMPOR (C) QMNPRO (D) QMNPOR
Your answer
Answer & solution
Answer: C (no official key was published)
Step through it (4 options)
1. BFS uses a FIFO queue, so all newly discovered neighbors enter behind previously queued vertices. Start at Q and discover M,N,P in that order. 2. Processing M next discovers R. Processing N then discovers O. Processing P adds nothing because O is already discovered. 3. The dequeue/visit order is Q,M,N,P,R,O, C. D puts O before R despite the specified first-layer order; the other offered orders violate BFS layers.
1. Compare logarithms, which preserve growth order for positive functions. log h=(log n)² up to base constants; log f=Θ(n). Since (log n)²=o(n), h grows slower than f. 2. Stirling gives log(n!)=n log n−n+O(log n), which grows faster than n. Thus f grows slower than g. 3. Therefore h=O(f) and g=Ω(f), D.
What is the minimum worst-case number of comparisons needed to determine whether some integer appears more than n/2 times in a sorted array of n integers?
(A) Θ(n) (B) Θ(log n) (C) Θ(log* n) (D) Θ(1)
Your answer
Answer & solution
Answer: B (no official key was published)
1. If a value occurs more than n/2 times, it must occupy the middle array position. Take that value as candidate and use binary searches for its first and last occurrences; accept exactly when the count exceeds n/2. 2. This needs Θ(log n) comparisons in the worst case. A logarithmic lower bound follows by locating a candidate-block boundary among linearly many possible positions while distinguishing length floor(n/2) from floor(n/2)+1. 3. Sortedness is essential; without it a linear majority scan is needed. Thus B.
A quicksort pivot procedure splits the list into two sublists each containing at least n/5 elements. If T(n) counts sorting comparisons, which offered upper recurrence follows?
1. Each recursive subproblem has size at most 4n/5, because each side has at least n/5 elements. With the usual monotone worst-case upper-bound interpretation of T and linear partitioning cost, both recursive costs are bounded individually by T(4n/5), so T(n)≤2T(4n/5)+n, option C. 2. This loose recurrence follows immediately from the given size bounds. The tempting expression T(n/5)+T(4n/5)+n assumes that the most unequal permitted split maximizes the sum of recursive costs; monotonicity alone does not establish that. 3. More precisely the general recurrence is T(n)≤maxn/5≤k≤4n/5{T(k)+T(n−k)}+O(n), ignoring pivot/rounding constants. The standard comparison model includes linear partition/pivot overhead; the statement does not specify the cost of an arbitrary extra pivot-selection procedure.
Subset sum asks whether a subset of n positive integers sums to a positive integer W. Algorithm Q takes O(nW) time. Which statement is false?
(A) Q is polynomial-time for unary input encoding (B) Q is polynomial-time for binary input encoding (C) Subset sum belongs to NP (D) Subset sum is NP-hard
Your answer
Answer & solution
Answer: B (no official key was published)
1. B is false. The dynamic program takes O(nW), polynomial in the numerical value W, not in its binary encoding length Θ(log W). 2. For binary input W can be exponential in the input length, so this is a pseudo-polynomial algorithm. With unary encoding the input has length at least W and at least n, hence nW is polynomial in that length. 3. A subset is a polynomial-size certificate whose sum can be checked in polynomial time, so subset sum is in NP; its standard decision form is NP-complete and therefore NP-hard. Thus A, C and D are true.
Run Dijkstra from a in this directed weighted graph: a→b:1, b→c:2, c→d:3, d→a:2, b→e:−3, c→h:−5, d→g:2, h→e:1, g→h:2, g→e:1, e→f:2, f→g:3. To which vertices does it compute correct shortest-path distances?
(A) Only a (B) Only a,e,f,g,h (C) Only a,b,c,d (D) All vertices
Your answer
Answer & solution
Answer: D (no official key was published)
Step through it (22 steps)
1. All vertices receive the correct distance despite the negative edges. From a, settle b at 1, which sets c=3 and e=−2. Settle e at −2, then f at 0, setting g=3. Vertices c and g tie at 3. 2. Whichever is handled first, c sets h=3−5=−2 before h is settled (if g was handled first it only proposes h=5). Vertex h proposes e=−1, not an improvement over −2. Vertex d gets 6 from c and offers no improvement to a or g. Final distances (a,b,c,d,e,f,g,h)=(0,1,3,6,−2,0,3,−2). 3. They also satisfy every edge relaxation inequality, with each value attained by a path, proving optimality. Negative edges invalidate Dijkstra’s general guarantee, but do not force failure on every particular input.
Consider these C functions, assuming valid array bounds and the intended unit-cost arithmetic model: int f1(int n) { if(n==0 || n==1) return n; else return 2*f1(n-1)+3*f1(n-2); } int f2(int n) { int i; int X[N],Y[N],Z[N]; X[0]=Y[0]=Z[0]=0; X[1]=1; Y[1]=2; Z[1]=3; for(i=2;i<=n;i++) { X[i]=Y[i-1]+Z[i-2]; Y[i]=2*X[i]; Z[i]=3*X[i]; } return X[n]; } What are the running times of f1(n) and f2(n), respectively?
Answer: No exact option; B is the apparent intended choice (no official key was published)
1. The recursive function makes one call on n−1 and one on n−2; coefficients 2 and 3 multiply the returned values and do not multiply the number of calls. Thus T(n)=T(n−1)+T(n−2)+Θ(1), giving Θ(φn), where φ=(1+√5)/2. 2. The iterative f2 executes n−1 constant-time iterations, Θ(n). None of the printed options gives Θ(φn),Θ(n). 3. Option B prints Θ(2n),Θ(n), which supplies an exponential upper bound but falsely labels it tight Θ. This analysis assumes unit-cost bounded-size arithmetic and n within valid array bounds; unbounded n in actual C would also encounter overflow.
Given positive integers S={a₁,…,aₙ} and target W>0, a subset-sum dynamic program uses Boolean X with n rows and W+1 columns. X[i,j] is true iff some subset of {a₁,…,aᵢ} sums to j, for 1≤i≤n and 0≤j≤W. Which recurrence is valid for 2≤i≤n and aᵢ≤j≤W?
1. Consider whether the chosen subset contains aᵢ. If not, the first i−1 elements alone must sum to j, represented by X[i−1,j]. 2. If aᵢ is included, remove it once; the remaining subset of the first i−1 elements must sum to j−aᵢ, represented by X[i−1,j−aᵢ]. 3. Either alternative suffices, so combine with OR, giving B. Using row i in the second term allows repeated copies of aᵢ; AND incorrectly requires both choices.
Given positive integers S={a₁,…,aₙ} and target W>0, a subset-sum dynamic program uses Boolean X with n rows and W+1 columns. X[i,j] is true iff some subset of {a₁,…,aᵢ} sums to j, for 1≤i≤n and 0≤j≤W. Which entry, if TRUE, implies there is a subset summing to W? (This preserves the printed one-way wording.)
(A) X[1,W] (B) X[n,0] (C) X[n,W] (D) X[n−1,n]
Your answer
Answer & solution
Answer: C intended; A also satisfies the literal implication (no official key was published)
1. By the definition of X, X[n,W] is true if and only if a subset of all n inputs sums to W. Therefore C is the terminal decision cell intended by the algorithm. 2. However, the printed wording asks only which TRUE entry implies the existence of a subset summing to W. X[1,W] being true also implies that fact, since {a1} is contained in the full set. 3. B is always true via the empty subset and D concerns sum n rather than W. Thus A and C both satisfy the literal one-way implication; C alone is necessary and sufficient for the full problem.
The directed acyclic graph has V={1,2,3,4,5,6} and edges 1→2, 1→3, 2→4, 3→4, 2→5, 4→5, 3→6, 4→6. Which sequence is NOT a topological ordering? Options: (A) 1,2,3,4,5,6 (B) 1,3,2,4,5,6 (C) 1,3,2,4,6,5 (D) 3,2,4,1,6,5
Your answer
Answer & solution
Answer: D (no official key was published)
Step through it (4 options)
1. Approach. A topological ordering places the tail of every directed edge before its head. It suffices to find one violated edge to reject an ordering.
2. Derivation and interpretation. The figure has 1→2 and 1→3, then 2,3 preceding 4 and 4 preceding 5,6. A topological ordering must place 1 before 2 and 3. D begins 3,2,4,1 and violates both outgoing constraints from 1; A,B,C respect the displayed edges. Thus D.
Which listed sorting algorithm has the lowest worst-case time complexity? Options: (A) Merge sort (B) Bubble sort (C) Quick sort (D) Selection sort
Your answer
Answer & solution
Answer: A (no official key was published)
1. Approach. Compare guaranteed worst-case bounds, not average performance. Mergesort halves the input and performs linear merging on each recursion level.
2. Derivation and interpretation. Standard mergesort guarantees Θ(n log n) worst-case time. Bubble sort, selection sort and conventional quicksort can take Θ(n²) in the worst case. Hence mergesort, A.
Single-source shortest paths in an unweighted graph
Graph Algorithms
Tap to enlarge
In an unweighted undirected connected graph, which method most efficiently finds shortest paths from a source S to every other vertex? Options: (A) Dijkstra from S (B) Warshall (C) DFS from S (D) BFS from S
Your answer
Answer & solution
Answer: D (no official key was published)
1. Approach. All edges have equal cost, so distance is the number of edges. A FIFO queue processes every distance-d vertex before any distance-(d+1) vertex.
2. Derivation and interpretation. BFS starts at S and discovers vertices in increasing number of edges from S. When a vertex is first discovered, its level is its shortest-path distance; parent pointers recover paths. With adjacency lists, every vertex and edge is processed O(1) times, giving O(V+E). DFS does not generally find shortest paths; generic Dijkstra adds priority-queue overhead, and Warshall solves a more expensive all-pairs/reachability problem. Thus D is the appropriate algorithm.
For the following source C-style function with n≥m, how many recursive calls are made? int gcd(n,m) { if(n % m == 0) return m; n = n % m; return gcd(m,n); } The source does not explicitly say worst case or m>0; state those assumptions in interpreting the options. Options: (A) Θ(log₂ n) (B) Ω(n) (C) Θ(log₂ log₂ n) (D) Θ(√n)
Your answer
Answer & solution
Answer: A (no official key was published)
1. Approach. This is Euclid’s algorithm. An upper bound comes from a constant-factor size reduction within two calls; a tight worst-case lower bound comes from consecutive Fibonacci arguments.
2. Derivation and interpretation. For positive integers n≥m>0, Euclid replaces (n,m) by (m,n mod m). Within two recursive steps the larger argument decreases by at least a factor of two, so there are O(log n) recursive calls. Consecutive Fibonacci inputs attain a matching lower bound: their quotients are one for most steps, and Fk grows exponentially in k, giving Θ(log n) calls in the worst case (A). The statement does not say worst case: when m divides n, there are zero recursive calls. Therefore Θ(log n) is not a pointwise bound for every input satisfying n≥m. Positive m is also necessary to avoid remainder by zero.
What is the time complexity of this recursive function, with unit-cost arithmetic and square root? int DoSomething(int n) { if(n<=2) return 1; else return DoSomething(floor(sqrt(n))) + n; } Options: (A) Θ(n²) (B) Θ(n log₂ n) (C) Θ(log₂ n) (D) Θ(log₂ log₂ n)
Your answer
Answer & solution
Answer: D (no official key was published)
1. Approach. The function makes one recursive call, not n calls. Each square root halves the logarithm of the argument, so analyze the recursion in terms of log n.
2. Derivation and interpretation. Assuming unit-cost integer arithmetic and square root as intended, T(n)=T(floor(sqrt(n)))+Θ(1). After k reductions the argument is approximately n1/2^k, and reaches a constant when 2k=Θ(log n). Thus k=Θ(log log n), giving D. Adding n to the returned value is one arithmetic operation, not n operations; floors change only constant-level stopping details.
A globally minimum-weight edge and minimum spanning trees
Graph Algorithms
Tap to enlarge
In a connected undirected graph, w is the minimum edge weight and e is a particular edge of weight w. Which statement is false? Options: (A) Some minimum spanning tree contains e (B) If an MST T omits e, every edge of the cycle in T+e has the same weight (C) Every MST contains an edge of weight w (D) Every MST contains e
Your answer
Answer & solution
Answer: D (no official key was published)
1. Approach. Use the exchange argument: inserting a non-tree edge creates one cycle, and removing a cycle edge gives another spanning tree. Equal minimum-weight edges need not be individually mandatory.
2. Derivation and interpretation. Take any MST T. If e is absent, adding it creates a cycle. Every edge of that cycle has weight at least w by global minimality of w, and none can have weight greater than w: exchanging such an edge for e would make a strictly cheaper spanning tree. Thus all cycle edges have weight w, proving B; exchanging any one of them for e produces an MST containing e, proving A. Every MST contains an edge of weight w by the same argument (or contains e itself), proving C. However a triangle with all edges weight w has MSTs omitting any chosen edge, so e need not belong to every MST. D is false, assuming the usual loop-free graph convention.
Given an array of an even number n of values, both its minimum and maximum must be found. Which comparison-count claim is true? Options: (A) At least 2n−c comparisons are necessary for some constant c (B) At most 1.5n−2 comparisons are sufficient (C) At least n log₂ n comparisons are necessary (D) None of these
Your answer
Answer & solution
Answer: B (no official key was published)
1. Approach. A comparison within a pair simultaneously rules one element out as maximum and the other out as minimum. Exploit this dual use before separately reducing the two candidate sets.
2. Derivation and interpretation. Partition the even number n of values into n/2 pairs. Compare within each pair, putting its smaller member in a minimum-candidate set and larger member in a maximum-candidate set. Find the minimum of the n/2 smaller values and maximum of the n/2 larger values. The comparison count is n/2+(n/2−1)+(n/2−1)=3n/2−2, so B. This construction disproves the claimed asymptotically larger lower bounds in A and C.
For the following printed C fragment, T(n) counts for-loop executions on input n. Which asymptotic bounds are intended? int IsPrime(n) { int i,n; for(i=2;i<=sqrt(n);i++) if(n%i==0) { printf("Not Prime\n"); return 0; } return 1; } The source redeclares n; interpret the intended divisor-testing algorithm separately from literal C validity. Options: (A) O(√n) and Ω(√n) (B) O(√n) and Ω(1) (C) O(n) and Ω(√n) (D) None of these
Your answer
Answer & solution
Answer: B (no official key was published)
1. Approach. A uniform lower bound must apply to easy inputs too. Even numbers terminate at i=2, whereas prime numbers make the loop test all candidate divisors through floor(√n).
2. Derivation and interpretation. Under the intended interpretation that n is the positive input integer, at most floor(sqrt(n))−1 candidate divisors are tested, so T(n)=O(sqrt(n)). For even n≥4, the first divisor i=2 causes immediate return, so T(n)=1 on an unbounded input family and no uniform Ω(sqrt(n)) lower bound is valid. For all sufficiently large n at least one iteration occurs, establishing Ω(1); B is therefore the intended answer. Prime n attain Θ(sqrt(n)). Source caveat: the printed function uses old-style IsPrime(n) and then declares int i,n inside its body, redeclaring its parameter n in the same scope. This is not valid C as printed; the algorithmic answer requires repairing the parameter declaration/removing the duplicate local n.
Letters a,b,c,d,e,f occur with probabilities 1/2,1/4,1/8,1/16,1/32,1/32, respectively. Which list, in a,b,c,d,e,f order, is a Huffman code? Options: (A) 0,10,110,1110,11110,11111 (B) 11,10,011,010,001,000 (C) 11,10,01,001,0001,0000 (D) 110,100,010,000,001,111
Your answer
Answer & solution
Answer: A (no official key was published)
1. Approach. Repeatedly merge the two lowest-probability nodes. Code length is leaf depth in the resulting binary tree; high-probability a should get a one-bit word. Prefix-free alone is not enough to guarantee optimality.
2. Derivation and interpretation. Huffman merging combines e and f (1/32 each) into 1/16, merges with d to 1/8, merges with c to 1/4, merges with b to 1/2, then merges with a. The resulting leaf depths for a,b,c,d,e,f are 1,2,3,4,5,5. Option A supplies a prefix code with these depths: 0,10,110,1110,11110,11111. Bit reversal at internal branches can give other equivalent codes, but A is the listed optimal code.
Letters a,b,c,d,e,f occur with probabilities 1/2,1/4,1/8,1/16,1/32,1/32, respectively. What is the average length of an optimal binary Huffman code (the linked Q76 code)? Derive the code lengths from these probabilities. Options: (A) 3 (B) 2.1875 (C) 2.25 (D) 1.9375
Your answer
Answer & solution
Answer: D (no official key was published)
1. Approach. Average code length is probability-weighted, not the arithmetic mean of the six word lengths. Huffman merging gives lengths 1,2,3,4,5,5, with the shortest code assigned to the most frequent symbol.
2. Derivation and interpretation. Using the independently derived lengths 1,2,3,4,5,5, the weighted average is (1/2)*1+(1/4)*2+(1/8)*3+(1/16)*4+(1/32)*5+(1/32)*5 = 31/16 = 1.9375 bits per symbol. Answer D.
For nonzero coefficients a₀,…,a₃, consider p(x)=a₀+a₁x+a₂x²+a₃x³. What is the minimum multiplication count for evaluating p at x? This is the GFG cubic reading; GateForum prints a₃x² instead, and neither source explicitly says generic coefficients. Options: (A) 3 (B) 4 (C) 6 (D) 9
Your answer
Answer & solution
Answer: A for generic cubic coefficients (no official key was published)
1. The the paper displays a cubic: p=a0+x(a1+x(a2+a3x)). Horner evaluation uses three multiplications and three additions, giving A under the conventional generic-coefficient evaluation model.
2. Nonzero coefficients alone also do not rule out special simplifications, for example (x+1)3 uses two multiplications after forming x+1.
3. Thus three is the standard generic cubic cost, not a universal lower bound for every coefficient choice. Original official wording and key remain unavailable.
4. Teaching check: Evaluate the nested form from the inside: t=a₃x+a₂, then t=tx+a₁, then p=tx+a₀. Each stage contributes one multiplication. The answer depends on treating the cubic as a generic polynomial; it is not a theorem about every particular nonzero coefficient tuple.
Similar questions2 more → · asked again: GATE 2020, Q49
Minimum spanning tree on indexed vertices
Graph Algorithms
Tap to enlarge
A weighted complete graph has vertices v₁,…,vₙ and edge weight w(vᵢ,vⱼ)=2|i−j|. What is the minimum spanning-tree weight? Options: (A) n−1 (B) 2n−2 (C) C(n,2) (D) n²
Your answer
Answer & solution
Answer: B (no official key was published)
1. Every edge has weight 2|i−j|≥2, so every spanning tree costs at least 2(n−1). The path v1,v2,...,vn uses n−1 edges of weight 2 and attains the bound.
2. Hence2n−2, B.
3. Teaching check: This is a lower-bound-plus-construction proof. Every spanning tree has exactly n−1 edges and every available edge costs at least two. Connecting consecutive indices achieves that lower bound; no search over all spanning trees is necessary.
Which data structure lets the shortest-path method on an unweighted graph run in linear time, as the unweighted specialization of Dijkstra’s algorithm? Options: (A) Queue (B) Stack (C) Heap (D) B-tree
Your answer
Answer & solution
Answer: A (no official key was published)
1. All edges have equal unit cost, so increasing distance order is breadth-first order. A FIFO queue processes each vertex and scans each adjacency list once, in O(V+E) time.
2. Thus A; a priority heap is unnecessary.
3. Teaching check: In an unweighted graph, every discovered neighbor is exactly one hop farther than its predecessor. A FIFO queue keeps frontier layers in nondecreasing distance order, which is the priority rule Dijkstra needs here. With adjacency lists the total scan cost is the sum of degrees, O(V+E).
Among the standard in-place sorting algorithms listed, which needs the fewest swaps under the conventional worst-case exchange-count comparison? Options: (A) Quicksort (B) Insertion sort (C) Selection sort (D) Heapsort
Your answer
Answer & solution
Answer: C under the standard swap-based comparison (no official key was published)
1. Selection sort places the minimum remaining item in its final location with at most one exchange per pass, hence at most n−1 swaps. Standard swap-based insertion sort, quicksort and heapsort can use more.
2. Thus selection sort, C, in the conventional worst-case exchange-count comparison. A shift-based insertion implementation can avoid an explicit swap operation, so literal source-code swap counts are implementation-dependent.
3. Teaching check: Selection sort can inspect the entire unsorted suffix without moving any item, then exchange its minimum with the first unsorted position. This separates comparison count, Θ(n²), from exchange count, O(n). The question asks about swaps, not fastest running time.
An array element is a leader if it exceeds every element to its right. Which description gives the best algorithm for finding all leaders? No auxiliary-space restriction is stated, which affects whether the options are exclusive. Options: (A) Linear time with a left-to-right pass (B) Linear time with a right-to-left pass (C) Divide and conquer in Θ(n log n) (D) Θ(n²) time
Your answer
Answer & solution
Answer: B with constant extra space; A also possible with a stack (no official key was published)
1. Scanning right to left while retaining the largest value seen reports exactly the elements strictly larger than every element to their right. This is Θ(n) time and O(1) extra working space, yielding the usual B.
2. However A is also achievable in linear time if extra storage is allowed: scan left to right, keep candidate leaders in a decreasing stack, and pop every prior candidate≤the new value before pushing it. Each entry is pushed/popped at most once; the final stack contains the leaders.
3. Since the prompt does not require constant space, traversal direction alone does not make B uniquely correct.
4. Teaching check: Right-to-left scanning initializes the current maximum with the rightmost element and reports a new element only when it is strictly greater. Equal values do not become leaders if an equal value occurs later. A left-to-right monotone stack is a separate linear-time possibility, explaining the nonunique direction-only options.
An undirected graph has vertices a,b,c,d,e,f and weighted edges ab:1, ac:6, bc:3, bd:4, bf:2, cd:2, ce:4, cf:7, de:3, df:1, ef:5. Which sequence cannot be the edges added, in order, by Kruskal’s minimum-spanning-tree algorithm? GFG A prints af, an edge absent from the graph; GateForum A instead prints df. Both readings are retained. Options: (A) ab, af, bf, dc, de [GFG]; ab, df, bf, dc, de [GateForum] (B) ab, df, dc, bf, de (C) df, ab, dc, bf, de (D) df, ab, bf, de, dc
Your answer
Answer & solution
Answer: A, D (no official key was published)
1. The graph has ab=df=1, bf=dc=2, and de=bc=3. Kruskal first adds ab and df in either order, then bf and dc in either order, then de.
2. B and C are legal. D adds de of weight 3 before dc of weight 2, although dc still joins distinct components, so D is impossible.
3. However, the paper prints (a-f) as the second edge of A; no such edge exists, making A impossible too. Replacing that entry with (d-f) would make A legal and yield the intended unique answer D.
4. This is a the paper-specific ambiguity, not an established defect in the original exam.
6. Teaching check: Kruskal processes available edges in nondecreasing weight and only skips an edge when its endpoints are already connected. Tie order can vary for equal weights, but it cannot justify selecting weight 3 while a useful weight-2 edge remains. The absent af edge is a separate transcription defect.
T is a depth-first-search tree of an undirected graph G. Distinct u and v are leaves of T and both have graph degree at least 2. Which statement must hold? Options: (A) Some vertex w is adjacent to both u and v (B) Some vertex w has removal disconnecting u from v (C) Some cycle contains both u and v (D) Some cycle contains u and every neighbor of u
Your answer
Answer & solution
Answer: D (no official key was published)
1. In an undirected DFS, every non-tree edge joins a vertex to an ancestor. Since u is a DFS leaf, all its neighbors lie on its single root-to-u tree path.
2. Let w be its highest ancestor-neighbor. The tree path w to u plus the edge uw forms a cycle containing every neighbor of u, since all those neighbors lie between w and u.
3. Degree at least two ensures a genuine cycle. Thus D.
4. Two distinct cycles sharing only a root refute the asserted common cycle; other DFS graphs refute the universal common neighbor and separator assertions.
5. Teaching check: DFS in an undirected graph has no cross edge joining separate finished subtrees. A leaf’s non-parent neighbors must therefore be ancestors. The path from its highest such neighbor to the leaf contains every other neighbor along that ancestor chain, and the closing back edge creates the required cycle.
For integers n>1, T(n)=2T(⌊√n⌋)+1 and T(1)=1. What is the asymptotic growth? Options: (A) Θ(log log n) (B) Θ(log n) (C) Θ(√n) (D) Θ(n)
Your answer
Answer & solution
Answer: B (no official key was published)
1. After h repeated floor-square-root steps, the subproblem size is floor(n1/2^h). For n≥2 it first reaches 1 when n<22^h, so h=floor(log₂(log₂ n))+1.
2. The recurrence tree is a full binary tree of height h. Every node contributes one, including the T(1)=1 leaves, so T(n)=2h+1−1. Because log₂ n<2h≤2 log₂ n, this is Θ(log n), option B.
3. Teaching check: The depth is Θ(log log n), but exponentiating that Θ statement alone would not justify Θ(log n). The sharper h=log₂(log₂ n)+O(1) bound controls the number of leaves within constant factors. Floor rounding is included explicitly and ensures termination at the stated base case.
The median of n elements can be selected in O(n) time. What is quicksort’s complexity if the median is always chosen as pivot, with balanced partitioning? Options: (A) Θ(n) (B) Θ(n log n) (C) Θ(n²) (D) Θ(n³)
Your answer
Answer & solution
Answer: B (no official key was published)
1. Select the median in Θ(n) time and partition in Θ(n) time, producing two subproblems of approximately n/2 elements. The recurrence T(n)=2T(n/2)+Θ(n) gives Θ(n log n), option B, including the median-selection cost.
2. This assumes standard balanced handling of duplicate keys or distinct keys; a two-way partition that mishandles equal keys can defeat that guarantee.
3. Teaching check: Finding the median is not free, but its linear cost can be absorbed into the same Θ(n) term as partitioning. Each recursion level processes a total of Θ(n) elements, and balanced halves give Θ(log n) levels. Thus median selection does not make quicksort linear overall.
Given two length-n binary arrays a,b, find the longest interval [i,j] on which Σₖ₌ᵢʲaₖ=Σₖ₌ᵢʲbₖ, or report none. Which complexity describes the fastest method? Options: (A) O(3^n) and Ω(2^n) time if hashing is allowed (B) O(n³) and Ω(n^2.5) time in the key-comparison model (C) Θ(n) time and space (D) O(√n) time only if the sum of all 2n entries is even
Your answer
Answer & solution
Answer: C (no official key was published)
1. Set prefix differences D[0]=0 and D[k]=sum(a[1..k])−sum(b[1..k]). A span (i,j) has equal sums iff D[i−1]=D[j].
2. Every D[k] lies in [−n,n], so an array of 2n+1 entries can store the earliest index of each difference. Scan once and maximize the distance to its first occurrence.
3. Time and space are Θ(n), option C; hashing is unnecessary. Reading the inputs already takes Ω(n) time.
4. Teaching check: Store the earliest occurrence of each prefix difference because that maximizes the length to a later equal difference. A binary-array prefix difference stays between −n and n, so direct indexing gives worst-case linear performance rather than relying on average-case hash-table behavior.
A known bound for computing transitive closure of an n-element relation is: A O(n); B O(n log n); C O(n^(3/2)); D O(n³).
Your answer
Answer & solution
Answer: D (no official key was published)
Warshall’s algorithm considers each possible intermediate vertex k and updates reachability R[i, j]←R[i, j]∨(R[i, k]∧R[k, j]) for every i, j. Its three nested loops take O(n³), D. Faster algebraic algorithms exist; the question asks a known upper bound, not a tight lower bound. The other listed bounds are subquadratic and cannot explicitly output every entry of an arbitrary n×n closure matrix.
Warshall’s algorithm loops over intermediate vertex k and every ordered pair(i, j), updating reachability using i→k→j. There are n choices in each loop, giving O(n³). This is a known upper bound, not a proof that faster algebraic methods are impossible. An explicitly written arbitrary n×n closure has quadratic output size, so the three listed subquadratic alternatives cannot generally output the full matrix.
T(n)=2T(n/2)+n, with T(0)=T(1)=1. Which claim is false? A O(n²); B Θ(n log n); C Ω(n²); D O(n log n).
Your answer
Answer & solution
Answer: C (no official key was published)
For n=2k, dividing by n gives T(n)/n=T(n/2)/(n/2)+1, so T(n)=n(1+log2 n). Standard rounding of subproblem sizes preserves Θ(n log n). Therefore O(n²), Θ(n log n), and O(n log n) hold, but Ω(n²) does not, C, since(n log n)/n²→0.
For powers of two, each recursion level contributes n and there are log₂n nontrivial levels plus linear total base cost. Thus T(n)=n(1+log₂n), giving Θ(n log n). This is bounded above by n² but not below by a positive constant times n², since log n/n tends to zero. Hence the false bound is C. A loose upper bound can still be true even when it is not tight.
Dijkstra on positive-weight undirected G(V, E), using adjacency lists and a binary heap, has standard bound: A O(V²); B O(E+V log V); C O(V log V); D O((E+V)log V).
Your answer
Answer & solution
Answer: D (no official key was published)
Using adjacency lists, up to V extract-min operations and O(E) decrease-key operations each cost O(log V) with a binary heap. Including initialization gives O((E+V)log V), D. The O(E+V log V) bound requires different amortized heap operations, such as a Fibonacci heap, not a standard binary heap.
Dijkstra extracts each vertex once and may relax each edge. A binary heap takes logarithmic time for extract-min and decrease-key, producing V log V plus E log V. The sum is O((V+E)log V). The tempting E+V log V bound uses an amortized heap with cheaper decrease-key, not the specified ordinary binary heap. Positive weights ensure the settled-distance greedy step is valid.
Merge roughly log n sorted lists, each containing roughly n/log n elements, using a heap. Options include A O(n log log n), B Θ(n log n), C Ω(n log n), D Ω(n^(3/2)). Find the intended efficient merge bound.
Your answer
Answer & solution
Answer: A (no official key was published)
Keep the smallest remaining item from each of k=Θ(log n) lists in a min-heap. Repeatedly extract the minimum and replace it by the next item from the same list. There are Θ(n) items, each costing O(log k)=O(log log n), so the merge costs O(n log log n), A. The comparison lower bound for arbitrary interleavings of equally sized lists is Ω(n log k), so this is also the worst-case asymptotic order.
The heap needs one current head per list, only Θ(log n) elements. Removing the smallest head and inserting its successor costs O(log log n), not O(log n), because heap height depends on list count. Repeating for Θ(n) output elements gives O(n log log n). The lists are already internally sorted, so sorting their whole union from scratch would waste that available order.
Two undirected-graph decision problems: α asks for an independent set of size |V|−4; β asks for an independent set of size 5. A α in P, β NP-complete; B α NP-complete, β in P; C both NP-complete; D both in P. The source says independent set, not clique, for β.
Your answer
Answer & solution
Answer: D (no official key was published)
For α, an independent set of |V|−4 vertices exists exactly when some four-vertex complement covers all edges (handle |V|<4 separately). Enumerate O(n4) complements and check the remaining edges. For β, enumerate O(n5) five-vertex subsets and test that all ten vertex pairs are nonedges. Both are polynomial-time because 4 and 5 are constants, so D.
An independent set leaves no edge with both endpoints inside it. For α, enumerate every possible four-vertex excluded set and test the remaining induced graph for an edge; O(n⁴(n+m)) is polynomial. For β, enumerate every five-vertex set and test its ten pairs for the absence of edges; O(n⁵) suffices with adjacency lookup. Unlike the NP-complete general independent-set problem, the relevant size or complement size here is a fixed constant, not part of the input. Hence both are in P.
double foo(int n){int i;double sum;if(n==0)return 1.0;sum=0.0;for(i=0;i<n;i++)sum+=foo(i);return sum;} Printed 81(a): maximum auxiliary space of foo(n)? A O(1); B O(n); C O(n!); D O(n^n). Seek intended tight order, not merely any loose upper bound.
Your answer
Answer & solution
Answer: B (no official key was published)
Every activation stores only a constant number of locals, but calls are nested. A path foo(n)→foo(n−1)→…→foo(0) reaches n+1 simultaneous activations. The loop calls execute sequentially, so the exponentially many calls are not all live at once. Maximum stack space is Θ(n), option B.
Count simultaneously live activations, not total recursive calls. During its last recursive branch, foo(n) may be suspended while foo(n−1), foo(n−2),…, foo(0) are active, giving linear depth. Each frame contains only a constant number of scalar locals. Separate loop iterations return before the next call, so their storage is reused. This distinguishes linear stack space from exponential running time. Larger Big-O choices are also loose bounds; the intended answer describes the tight growth.
double foo(int n){int i;double sum;if(n==0)return 1.0;sum=0.0;for(i=0;i<n;i++)sum+=foo(i);return sum;} Printed 81(b): memoize foo(i), 0≤i<n, as computed. Auxiliary space? A O(1); B O(n); C O(n²); D O(n!).
Your answer
Answer & solution
Answer: B (no official key was published)
Caching foo(i) for 0≤i<n requires n scalar values, hence Θ(n) space. Any recursive call stack is also at most O(n), so the total remains Θ(n), option B. Memoization reduces recomputation but does not require storing all call-tree nodes. This counts machine words, as in the question’s double-valued implementation.
Memoization allocates one result per argument value, a linear-size table, rather than one result per recursive-call occurrence. A recursive implementation can still have a linear stack, but adding two linear requirements remains linear. The table itself gives a linear lower bound in the stated storage scheme. Count constant-size machine words as specified by the double implementation; arbitrary-precision value bit lengths would be a different model.
Undirected connected graph has distinct positive edge weights. Partition X, Y separates s∈X, t∈Y; e is the minimum-weight edge crossing that cut. Printed 82(a): e must belong to which object: minimum spanning tree, weighted shortest s–t path, every s–t path, or weighted longest s–t path? GFG has a blank A and shifted labels; preserve the concept rather than a universal option letter.
Your answer
Answer & solution
Answer: B: MST (no official key was published)
Let T be a minimum spanning tree. If its edges omit the unique lightest crossing edge e, insert e into T, making a cycle. That cycle contains another edge f crossing the same cut. Distinct weights give w(e)<w(f); replacing f by e makes a lighter spanning tree, a contradiction. Hence e belongs to the MST. Connectivity is implicitly required for a spanning tree (otherwise use a minimum spanning forest in relevant components). The answer concept is unambiguous, but the source option letters are not interchangeable.
Use an exchange argument. If an MST omitted the lightest crossing edge, adding it creates a cycle. Because its endpoints are on opposite sides, the rest of that cycle must cross the same cut elsewhere. Replace that heavier crossing edge by e; distinct weights make the improvement strict, contradicting minimality. This proves MST membership but not membership in every s–t path: a path can cross on a more expensive edge. Minimum total distance is a different objective.
Undirected connected graph has distinct positive edge weights. Partition X, Y separates s∈X, t∈Y; e is the minimum-weight edge crossing that cut. Printed 82(b): path congestion is its largest edge weight. Which always minimizes congestion from s to t? A path in an MST; B weighted shortest path; C Euler walk; D Hamiltonian path.
Your answer
Answer & solution
Answer: A (no official key was published)
Take the s–t path in an MST and let f be its heaviest edge. Removing f partitions the tree with s and t on opposite sides. Any other s–t path must cross this cut. A crossing edge lighter than f could replace f to improve the MST, so every crossing edge has weight at least w(f). Every alternative path therefore has bottleneck at least w(f), exactly the MST path’s bottleneck. Option A.
Take the unique s–t path in an MST and remove its heaviest edge f. This creates a cut separating s, t. If any crossing edge were lighter than f, substituting it would create a cheaper spanning tree. Thus every alternative s–t path must use a crossing edge at least as heavy as f. Its maximum edge cannot be lower than the MST path’s maximum, proving minimax optimality even though the MST path need not minimize total distance.
Nine unit-time jobs T1…T9, one at a time, earn profits[15, 20, 30, 18, 18, 10, 23, 16, 25] if finished by deadlines[7, 2, 5, 3, 4, 5, 2, 7, 3], respectively. Printed 84(a): in a maximum-profit schedule A all jobs done; B T1, T6 omitted; C T1, T8 omitted; D T4, T6 omitted.
Your answer
Answer & solution
Answer: D (no official key was published)
Order jobs by descending profit and put each in the latest free slot not exceeding its deadline. One resulting schedule in slots 1…7 is T2, T7, T9, T5, T3, T8, T1. Their deadlines are respectively 2, 2, 3, 4, 5, 7, 7, so all meet their deadlines. T4 and T6 are omitted, option D. In particular T2, T4, T7, T9 all have deadline≤3, so at least one of them must be omitted; T4 has their lowest profit. Only seven slots exist through the latest deadline, requiring another omission, optimally T6.
The greedy unit-job method processes larger profits first and places each job as late as its deadline permits, leaving earlier slots for tighter deadlines. It yields T2, T7, T9, T5, T3, T8, T1. Check every slot against its deadline:1≤2, 2≤2, 3≤3, 4≤4, 5≤5, 6≤7, 7≤7. T4 and T6 are absent. The three-slot deadline bottleneck among T2, T4, T7, T9 explains why a job must be omitted even before considering total capacity.
Nine unit-time jobs T1…T9, one at a time, earn profits[15, 20, 30, 18, 18, 10, 23, 16, 25] if finished by deadlines[7, 2, 5, 3, 4, 5, 2, 7, 3], respectively. Printed 84(b): maximum profit A147; B165; C167; D175.
Your answer
Answer & solution
Answer: A (no official key was published)
The schedule T2, T7, T9, T5, T3, T8, T1 earns 20+23+25+18+30+16+15=147. All nine profits sum to 175. At least one of the four jobs with deadline≤3 must be dropped, losing at least 18, and at least one additional job must be dropped since the latest deadline is 7, losing at least 10. Therefore profit≤175−18−10=147, attained above. Option A.
Sum the feasible schedule’s seven profits to obtain 147. For optimality, the four jobs with deadline at most 3 cannot all fit in three slots, requiring a loss of at least 18. At most seven jobs can finish by the latest deadline 7, so another distinct job must be omitted, losing at least 10. Subtract these unavoidable losses from 175 to get upper bound 147, matched by the schedule. Thus the result is proven optimal rather than just a greedy candidate.
What is the tight asymptotic order of the worst-case lower bound on comparisons required by comparison-based sorting of n elements? Options: (A) n (B) n² (C) n log n (D) n(log n)²
Your answer
Answer & solution
Answer: C (no official key was published)
1. A comparison decision tree must distinguish n! possible input permutations, so its worst-case height is at least ceil(log2(n!))=Ω(n log n). Mergesort or heapsort attains O(n log n), making that the tight order of the worst-case comparison bound, C.
2. Teaching check: A binary comparison tree of height h has at most 2h leaves. Distinct orderings need separate leaves, so 2h≥n!. Summing logarithms or using Stirling’s estimate gives log2(n!)=Θ(n log n). This lower bound applies to comparison sorting, not every integer-key sorting method.
Matrices M1,M2 are stored in arrays A,B respectively. Each may use row-major or column-major contiguous storage. How does this affect the time complexity of a fixed algorithm computing M1×M2? Options: (A) Best when A is row-major and B column-major (B) Best when both are row-major (C) Best when both are column-major (D) Independent of storage scheme
Your answer
Answer & solution
Answer: D under a unit-cost RAM model (no official key was published)
1. Changing row-major to column-major storage changes the address formula, not the number of arithmetic operations or constant-time element accesses. Thus asymptotic running time for a fixed multiplication algorithm is independent of the layout, D.
2. For the usual i,j,k loop order, A-row-major/B-column-major can improve locality and elapsed time, but that is a cache-performance distinction rather than an asymptotic RAM-operation count.
3. Teaching check: For an r×c row-major array, address(i,j) uses ic+j; column-major uses jr+i. Both formulas take constant time under a unit-cost RAM model. Cache misses may differ dramatically, but that does not by itself alter a fixed algorithm’s asymptotic arithmetic/access count.
For real arithmetic, m>1 and ε>0, what does this algorithm approximate? x=m; y=1; while(x-y>ε) { x=(x+y)/2; y=m/x; } print(x); Options: (A) log m (B) m² (C) m^(1/2) (D) m^(1/3)
Your answer
Answer & solution
Answer: C (no official key was published)
1. In real arithmetic xy=m initially and after each iteration. Thus x is an upper bound and y=m/x a lower bound for sqrt(m).
2. Updating x to (x+m/x)/2 preserves x≥sqrt(m) and decreases it unless equality holds; resetting y preserves the invariant. The limits agree at sqrt(m).
3. At termination y≤sqrt(m)≤x and x−y≤epsilon, giving absolute error at most epsilon. This is an algorithm question about iteration, not a request to solve an excluded calculus topic; integer division would invalidate the real-arithmetic interpretation.
4. Teaching check: After the update, x is the arithmetic mean of a pair whose product is m, so x≥sqrt(m) by AM–GM. Setting y=m/x gives y≤sqrt(m). Their shrinking gap supplies a direct error bound, not merely a guess based on numerical similarity.
Run Dijkstra from P on the directed graph with vertices P,Q,R,S,T,U and weighted arcs P→Q:1, P→S:6, P→T:7, Q→R:1, Q→S:4, R→S:2, R→U:1, S→T:3, S→U:2, T→U:2. In what order are shortest-path distances finalized? This arc list completely specifies the source figure. Options: (A) P,Q,R,S,T,U (B) P,Q,R,U,S,T (C) P,Q,R,U,T,S (D) P,Q,T,R,U,S
Your answer
Answer & solution
Answer: B (no official key was published)
Step through it (18 steps)
1. From P, tentative distances are Q=1,S=6,T=7. Finalizing Q sets R=2 and improves S=5.
2. Finalizing R sets U=3 and improves S=4. U has no outgoing improvement, so S=4 is next; S gives T=min(7,4+3)=7.
3. The order is P,Q,R,U,S,T, with final distances 0,1,2,3,4,7 in that order. In particular the diagonal edge is directed R→S, not S→R.
4. Teaching check: Record the finalized distances in extraction order: P:0,Q:1,R:2,U:3,S:4,T:7. Once R is processed, its outgoing R→S edge lowers S to 4. Reversing that arrow would alter the computation, so direction is part of the essential figure data.
A[1..n] stores bits. Function f(m) takes Θ(m) time for positive m, with constant bookkeeping for m=0. What is the complexity of: counter=0; for(i=1;i<=n;i++) { if(A[i]==1) counter++; else { f(counter); counter=0; } } Option D is little-o in the clearer GateForum reproduction. Options: (A) Ω(n²) (B) Ω(n log n) and O(n²) (C) Θ(n) (D) o(n)
Your answer
Answer & solution
Answer: C (no official key was published)
1. The counter measures the current consecutive run of ones. A zero invokes f on that run length and then resets the counter.
2. The lengths passed to all calls sum to at most n, because no position containing one belongs to two completed runs. Thus all calls together take O(n), including O(1) bookkeeping for zero-length runs, while the loop itself always performs n iterations and costs Ω(n).
3. Total complexity is Θ(n), C. A final run without a trailing zero does not increase this bound.
4. Teaching check: Charge each unit of f’s linear work to one of the ones in its completed run. No one belongs to two runs, so total charged work is linear. The always-executed loop supplies the matching linear lower bound; little-o(n) cannot describe it.
For positive integer n, find the time complexity of: int recursive(int n) { if(n==1) return 1; else return recursive(n-1)+recursive(n-1); } Use the ordinary execution model without memoization; the source prose says “a>0” although the code parameter is n. Options: (A) O(n) (B) O(n log n) (C) O(n²) (D) O(2^n)
Your answer
Answer & solution
Answer: D (no official key was published)
1. For positive integer n, each nonbase invocation makes two independent calls at n−1. With the usual unit-cost model and no memoization, T(n)=2T(n−1)+Θ(1), T(1)=Θ(1).
2. The recursion tree has 2n−1 leaves and 2n−1 total calls, yielding Θ(2n), and hence D. The identical arguments do not make the two evaluations a single call in this abstract execution model; integer overflow and compiler transformations are outside the model.
3. Teaching check: At recursion depth k there are 2k calls, until depth n−1. Adding the geometric series gives 2n−1 calls. The depth is only n, but depth alone is not total work when the recursion branches.
Solve T(1)=1 and T(n)=2T(n−1)+n for n≥2. The sign is plus in the rendered sources, despite faulty text extraction. Options: (A) 2^(n+1)−n−2 (B) 2^n−n (C) 2^(n+1)−2n−2 (D) 2^n+n
Your answer
Answer & solution
Answer: A (no official key was published)
1. The rendered recurrence is T(1)=1 and T(n)=2T(n−1)+n. A particular solution is −n−2, so T(n)=C·2n−n−2.
2. Using T(1)=1 gives 2C−3=1 and C=2. Therefore T(n)=2n+1−n−2, A.
3. Direct substitution gives 2[2n−(n−1)−2]+n=2n+1−n−2.
4. Teaching check: An alternative transformation is U(n)=T(n)+n+2. Then U(n)=2U(n−1), U(1)=4, so U(n)=2n+1. Subtract n+2 to recover T(n); this directly verifies the affine particular solution.
A program visits every node x of a balanced binary search tree with n leaves, computing g(x). The cost at x is min(number of leaves in x’s left subtree,number in x’s right subtree). What is worst-case total time? Options: (A) Θ(n) (B) Θ(n log n) (C) Θ(n²) (D) Θ(n² log n)
Your answer
Answer & solution
Answer: B (no official key was published)
1. In a perfect balanced tree with n leaves, the root costs n/2, the two children together cost n/2, and every internal level similarly costs n/2. There are log2 n internal levels, so this supplies a Θ(n log n) worst-case lower bound.
2. For any balanced tree, at each depth the subtrees are disjoint and the sum of their leaf counts is at most n; summing min(left leaves,right leaves) at that depth is at most n/2. Height O(log n) gives O(n log n), with traversal overhead O(n).
4. Teaching check: For n=8 in a perfect tree, the root cost is 4, the next level totals 4 and the next totals 4, giving 12 before traversal bookkeeping. Each internal level contributes n/2, and there are log2 n such levels. Counting only the root misses the repeated per-level work.
Which asymptotic claims are correct? I. (n+k)^m=Θ(n^m) for fixed constants k,m; II. 2^(n+1)=O(2^n); III. 2^(2n)=O(2^n) in GFG; GateForum instead shows 2^(2n+1)=O(2^n). Both claims have the same false truth value. A. I and II; B. I and III; C. II and III; D. I, II and III.
Your answer
Answer & solution
Answer: A (no official key was published)
1. Test big-O claims by ratios. A bounded positive ratio suffices for O; a ratio bounded away from zero as well establishes Θ. Doubling the exponent is not multiplying the result by a constant: 22n=(2n)². This is the specific error behind claim III.
2. For fixed k,m, ((n+k)m)/(nm)=(1+k/n)m tends to 1, so I holds.2n+1=2·2n, so II holds. But 22 n/2n=2n is unbounded, so III fails. Thus I and II only, A.
An undirected graph has vertices {a,b,e,f,g,h} and edges {ae,ab,af,eb,eg,bf,bh,fh,fg,gh}. Which listed sequences can be depth-first traversals starting at a, allowing arbitrary neighbor order? I. a,b,e,g,h,f; II. a,b,f,e,h,g; III. a,b,f,h,g,e; IV. a,f,g,h,b,e. A. I, II and IV only; B. I and IV only; C. II, III and IV only; D. I, III and IV only.
Your answer
Answer & solution
Answer: D (no official key was published)
Step through it (4 options)
1. DFS must finish every reachable unexplored neighbor before returning from a vertex. The three accepted sequences can be realized without any backtrack until all six vertices are visited because each consecutive pair is an edge. In II the transition from f to e would require backtracking through b, but f still has unvisited neighbors g and h, so DFS cannot yet leave f. Hence e cannot be next.
2. I, III and IV each trace a simple path through all vertices using displayed edges, so a neighbor order realizes each. In II, f has no edge to e and still has unvisited neighbors g and h; DFS must visit one of these before backtracking. Thus II is impossible and the answer is D.
Array insertion sort normally uses linear search to find where the next element belongs. If binary search replaces that search, what happens to worst-case total running time? A. It remains Θ(n²); B. It becomes Θ(n(log n)²); C. It becomes Θ(n log n); D. It becomes Θ(n).
Your answer
Answer & solution
Answer: A (no official key was published)
1. During insertion into a sorted prefix of length i, search needs O(log i) comparisons but opening an array slot may move i elements. Summing these movements over all prefixes dominates the sum of logarithmic searches. Binary search improves comparisons, not the cost of physically maintaining the sorted array.
2. Binary search reduces comparisons needed to locate each insertion position, but array elements still must shift to make room. A reverse-sorted input needs 1+2+...+(n−1)=Θ(n²) moves. The worst-case runtime therefore remains Θ(n²), A, despite O(n log n) comparisons.
Given T(1)=1, find T(m²) for integer m≥1. GFG prints T(n+1)=T(n)+floor(sqrt(n−1)), n≥1; GateForum instead prints floor(sqrt(n+1)). Preserve both versions. Options: A. (m/6)(21m−39)+4; B. (m/6)(4m²−3m+5); C. (m/2)(3m^(2.5)−11m+20)−5; D. (m/6)(5m³−34m²+137m−104)+5/6.
Your answer
Answer & solution
Answer: As printed (n−1) the value differs from the options; B holds for the n+1 recurrence (no official key was published)
1. In the block k²≤j<(k+1)² the value is k and the block length is 2k+1. Use sum k=(m−1)m/2 and sum k²=(m−1)m(2m−1)/6 to simplify. The shifted range omits the final terms m and m−1 and adds the initial 1, explaining the difference −2m+2.
2. For the latter, T(m²)=sum_(j=1)m²floor(sqrt(j)). Group j from k² through(k+1)²−1: for k<m there are 2 k+1 copies of k, followed by the final m. Hence sum_(k=1)m−1k(2 k+1)+m=m(4 m²−3 m+5)/6, option B. Literal the paper instead gives 1+sum_(j=0)m²−2floor(sqrt(j))=m(4 m²−3 m+5)/6−2 m+2, including m=1. These are not silently equated; original wording/key are needed to resolve the source discrepancy.
For a permutation a1,...,an of n distinct integers, an inversion is an index pair i<j with ai>aj. What is insertion sort's worst-case time if inputs are restricted to permutations of 1,...,n with at most n inversions? A. Θ(n²) B. Θ(n log n) C. Θ(n^1.5) D. Θ(n)
Your answer
Answer & solution
Answer: D (no official key was published)
1. In insertion sort, a larger element shifts right exactly when it is an inversion partner of the current key. Each original inversion causes one such shift and is then removed. 2. With I inversions, the inner loops therefore make I shifts. The n−1 outer iterations and their final failed/boundary tests add Θ(n) work, so total work is Θ(n+I). 3. The restriction I≤n gives O(n+n)=O(n). Reading and processing n entries still requires Ω(n), including an already sorted input. 4. Matching the upper and lower bounds gives Θ(n), D. The unrestricted reverse-order example has Θ(n²) inversions and is excluded here.
Solution: In standard insertion sort, shifting an earlier larger element past the current key removes exactly one inversion. Total shifts equal the input inversion count I, and outer-loop work plus terminating comparisons contributes Θ(n). Hence running time is Θ(n+I). With I≤n this is O(n), while scanning the n elements requires Ω(n), so the restricted worst case is Θ(n), option D.
The integer cube root of a natural number n is the largest natural m with m³≤n. The input n is represented in binary. Which describes its computation complexity? A. O(n), but not O(n^0.5) B. O(n^0.5), but not O((log n)^k) for any constant k>0 C. O((log n)^k) for some constant k>0, but not O((log log n)^m) for any constant m>0 D. O((log log n)^k) for some constant k>0.5, but not O((log log n)^0.5)
Your answer
Answer & solution
Answer: C (no official key was published)
1. The input length is b=floor(log2 n)+1; complexity in n and in the bit length b must not be confused. 2. Binary search the integer interval [0,n], retaining the largest tested m with m³≤n. Halving the interval takes O(log n)=O(b) iterations. 3. Using schoolbook arithmetic, a multiplication of O(b)-bit numbers costs O(b²); two multiplications form m³. Hence this explicit algorithm costs O(b³), polynomial in log n. 4. The output cube root has about b/3 bits, so even writing it costs Ω(b), which dominates every fixed power of log b. Thus a polynomial in log log n cannot suffice in the bit model, and C follows.
Solution: Let b be the number of input bits, so b=Theta(log n). Binary search for the largest m with m³≤n needs O(b) comparisons. Schoolbook multiplication computes a b-bit cube in O(b²) bit operations, giving an explicit O(b³) algorithm. The answer itself has Theta(b) bits for growing n, so writing it already requires Omega(b) bit operations. Thus the problem is polynomial in log n, but not polynomial in log log n, option C. This is a bit-complexity statement, not a unit-cost model for arbitrarily large integers.
Detecting subgraph connectivity with zero-weight edges
Graph Algorithms
Tap to enlarge
G=(V,E) is an undirected graph with subgraph G1=(V1,E1). Give an edge weight 0 if it is in E1, and 1 otherwise. Run single-source shortest paths from an arbitrary v1∈V1. Which property can always be inferred from the computed path costs? A. Number of edges in shortest paths from v1 to every vertex of G B. G1 is connected C. V1 forms a clique in G D. G1 is a tree Interpret B as determining whether G1 is connected, not asserting connectivity on every input.
Your answer
Answer & solution
Answer: B (no official key was published)
1. With only weights 0 and 1, a finite path has total cost 0 precisely when all of its edges belong to E1. 2. Hence d(v1,v)=0 precisely for vertices in the G1 component of v1. Test this for every v∈V1: all distances zero means G1 is connected; any positive/infinite distance means it is not. 3. Cost does not count zero-weight edges. A zero-weight chain and a zero-weight clique on V1 can give identical distance-zero results but different edge counts and cycle structure. 4. Thus the distances determine connectivity (B), but neither clique/tree status nor shortest-path edge counts.
Solution: An edge has weight zero exactly when it belongs to E1. Consequently, for a vertex v in V1, distance(v1,v)=0 exactly when v is connected to v1 using only edges of G1. Checking whether every vertex of V1 has zero distance therefore decides whether G1 is connected, B. Zero distances do not reveal edge counts, clique structure, or acyclicity: a tree and a triangle within the reachable zero-weight component can have identical distances. B must be read as determining connectivity, not asserting that every possible input G1 is connected.
Find the weight of a minimum spanning tree of the undirected weighted graph with vertices a,b,c,d,e,f,g,h,i,j and edges: ac:1; ad:2; cd:2; bg:2; ei:2; bd:3; fh:4; hi:4; ij:5; ab:6; ae:8; eh:8; gh:8; fi:9; ef:11; gi:14; dh:15; gj:19. These edges describe the complete printed diagram; no other edges are present. A. 29 B. 31 C. 38 D. 41
Your answer
Answer & solution
Answer: B (no official key was published)
Step through it (15 steps)
1. Kruskal processes edges by nondecreasing weight, accepting an edge only when its endpoints lie in different components. 2. Accept ac(1), ad(2); reject cd(2), since a,c,d are already connected. Accept bg(2), ei(2), then bd(3), which joins {b,g} with {a,c,d}. 3. Accept fh(4), hi(4), connecting {f,h} to {e,i}; accept ij(5) to add j. Reject ab(6), whose endpoints are already in the first component. 4. The two remaining components are {a,b,c,d,g} and {e,f,h,i,j}. Any weight-8 edge ae or gh can join them; choose gh. Nine accepted edges connect all ten vertices. 5. Total=1+2+2+2+3+4+4+5+8=31, B. eh(8) is internal to the second component and is not needed.
Solution: Kruskal's algorithm can select ac(1), ad(2), bg(2), ei(2), bd(3), fh(4), hi(4), ij(5), and gh(8). These nine edges connect all ten vertices without a cycle. Their total is 1+2+2+2+3+4+4+5+8=31, option B. The other weight-2 edge cd is skipped because ac and ad already connect c and d; the final weight-8 edge joins the two remaining components. Equal-weight alternatives may produce a different MST with the same total.
Activities A,...,H must each occupy a room throughout their duration. Let xs and xe denote the start and finish of X. The complete GateForum chronological sequence is: as,bs,cs,ae,ds,ce,es,fs,be,de,gs,ee,fe,hs,ge,he. GFG instead prints the same sequence with ce omitted. What is the minimum number of rooms? A. 3 B. 4 C. 5 D. 6 The omission is a material source discrepancy; do not silently insert ce into the GFG version.
Your answer
Answer & solution
Answer: None (no official key was published)
1. For the complete sequence, count a start as +1 and a finish as −1. The successive active counts are 1,2,3,2,3,2,3,4,3,2,3,2,1,2,1,0. The maximum is four, at fs with B,D,E,F simultaneously active. 2. Four rooms suffice constructively: assign room 1 to A,D,G; room 2 to B,H; room 3 to C,E; room 4 to F. Every reuse occurs after that room's previous finish. 4. Without ce, C may or may not still be running at fs, so the the paper sequence can require five rather than four. Preserve the baseline unanswered status for the defective primary version rather than guessing the missing event.
The maximum overlap is four, attained after F starts while B,D,E,F are active. The the paper omits C's finishing event. The incomplete the paper sequence cannot determine a unique answer without supplying the missing endpoint.
G is a directed n-vertex graph. A path may repeat vertices; a simple path has no repeated vertex. Initialize A[j,k]=1 when edge (j,k) exists, otherwise 0. Run in-place: for i=1,...,n: for j=1,...,n: for k=1,...,n: A[j,k]=max(A[j,k], A[j,i]+A[i,k]) Which is necessarily true at termination? A. A[j,k]≤n B. If A[j,j]≥n−1, G has a Hamiltonian cycle C. Whenever a path j→k exists, A[j,k] is its longest-path length D. Whenever a path j→k exists, every simple j→k path has at most A[j,k] edges
Your answer
Answer & solution
Answer: D (no official key was published)
1. Initially every one-edge path has its length represented by A[j,k]≥1. Updates only increase entries, so established lower bounds persist. 2. For a simple path with internal vertices, take its highest-numbered internal vertex i. Splitting there gives two subpaths whose internal vertices have smaller indices. Inductively their lengths are bounded above by A[j,i] and A[i,k] before processing i. 3. The update therefore makes A[j,k] at least the sum of those lengths, the length of the original path. This proves D for every simple path. 4. This is not a correct longest-simple-path algorithm: it never checks that the joined paths are disjoint. Cycles can repeatedly inflate values, and zero is an unsafe unreachable marker for maximizing lengths. Therefore exactness, an n bound and Hamiltonian-cycle inference do not follow.
Solution: The recurrence A[j,k]=max(A[j,k],A[j,i]+A[i,k]) gives option D. Induct on the largest-index internal vertex of a simple path: direct edges start at one; splitting a path at its largest-index internal vertex combines previously established lower bounds for the two pieces. Monotone updates cannot destroy them. Thus the final A[j,k] is at least the length of every simple j-to-k path. It need not equal a longest-path length: cycles and zero values used for nonexistent edges can inflate entries, so the other claims fail. For example, a directed two-vertex cycle with an isolated third vertex can produce values larger than n and large diagonal entries although there is no Hamiltonian cycle. Neither the claimed n bound nor the exact-longest-path interpretation is justified.
Step 1: Remove the powers of two from the argument.
Step 2: Writing out S(1)=4, S(2)=13, S(3)=40 reveals the repeated multiply-by-three pattern. In general the homogeneous contribution is 3kS(0), while the added ones contribute 1+3+…+3k−1. Evaluating that geometric sum gives the stated formula; at k=0 it correctly returns1.
Conclusion: Put S(k)=T(2k). Then S(k)=3S(k−1)+1 with S(0)=1. Iteration gives 3k+sum_(j=0)k−13j=(3k+1−1)/2, B.
An unsorted array A[1..n] contains n distinct values and contains x. A search repeatedly chooses i uniformly from 1..n, compares A[i] with x, stops on equality, and otherwise repeats the random choice. What is its expected comparison count before stopping? (A) n; (B) n−1; (C) 2n; (D) n/2.
Your answer
Answer & solution
Answer: A (no official key was published)
Step 1: Recognize independent repeated trials.
Step 2: After any failed draw, the algorithm restarts with the same success probability 1/n; it has not removed that position from future draws. Thus the comparison count is geometric, P(N=k)=(1−1/n)k−1/n. Its mean is 1/(1/n)=n, agreeing with the recurrence E=1+(1−1/n)E.
Conclusion: Each independently sampled index hits the unique target with probability 1/n. If E is the expected number of comparisons including the successful comparison, E=1+(1−1/n)E, giving E=n, A. Resampling already examined positions is allowed; this is not a random permutation scan.
For procedure A(n), if n≤2 return 1; otherwise return A(⌈√n⌉). Which listed bound best describes its running time? (A) O(n); (B) O(log n); (C) O(log log n); (D) O(1).
Your answer
Answer & solution
Answer: C (no official key was published)
Step 1: Take logarithms of the argument shrinkage.
Step 2: Let m=log₂n. Taking a square root approximately halves m, so the recursion needs about log₂m halvings to make m constant. Therefore the number of constant-work calls is Θ(log log n). This count concerns runtime, not the returned value, which is always 1. Arbitrary-precision root computation would require a different per-call cost model.
Conclusion: Ignoring integer rounding initially, after k calls the argument is n1/2^k. It becomes bounded once 2k is of order log n, so the recursion depth is Θ(log log n). Ceiling rounding changes only constants, and the small integer arguments reach the base case. With constant-time root/rounding operations per call, C is the tight listed growth bound, even though looser O(n) and O(log n) bounds are also true.
Complete a template computing all-pairs shortest-path lengths in a directed graph G. Its n×n adjacency matrix A has A[i,j]=1 for an edge i→j and 0 otherwise. Initialization loops over i=1..n and j=1..n and executes: if A[i,j]=0 then P[i,j]=____ else P[i,j]=____; The algorithm then has nested loops, in this exact order: for i=1..n, for j=1..n, for k=1..n, executing: P[____,____] = min{____,____}; Copy and complete the initialization line so that the algorithm is correct.
Shared context
For a directed unweighted graph, binary adjacency A[i,j] equals 1 for an edge i → j and 0 otherwise. Initialize a distance table P and run the printed loops in the order i outermost, then j, then k. Standard shortest-path distances permit an empty path of length 0.
Answer & solution
Answer: For i≠j: ∞ if A[i,j]=0, otherwise 1; for i=j: 0 (no official key was published)
1. Fix the graph interpretation. The adjacency entries are binary: A[i,j]=1 means a directed edge i→j of length 1, and A[i,j]=0 means that edge is absent.
2. Handle distinct vertices before any intermediate vertices are allowed. If i≠j and A[i,j]=1, the one-edge path has length 1, so initialize P[i,j]=1. If i≠j and A[i,j]=0, no direct path is available yet, so initialize P[i,j]=∞. Zero would incorrectly claim a free path between disconnected vertices.
3. Handle the diagonal separately. Standard shortest-path distance permits the empty path, so P[i,i]=0 whether or not A[i,i] contains a self-loop. A length-1 self-loop cannot beat that empty path.
4. Fill the original two blanks with expressions that incorporate these cases, without changing the printed outer condition:
if A[i,j] = 0 then P[i,j] = (0 if i = j else ∞)
else P[i,j] = (0 if i = j else 1);
Equivalently, initialize off-diagonal entries to ∞/1 and then explicitly set each P[i,i] to 0.
5. Check a small graph. If the only edge is 1→2, initialization gives rows [0,1] and [∞,0]. This correctly represents the direct path, lack of a reverse path, and both empty paths.
6. State the convention caveat. The abbreviated fills “∞,1” alone make a diagonal entry the length of a shortest nonempty closed walk, or ∞ if none exists, rather than the standard distance 0. That abbreviation suffices only if diagonal results are excluded or that other convention is intended. The conditional fill above is correct for every vertex pair under the standard convention and respects the template’s two blanks.
Complete the Floyd–Warshall update for the given loop order
Graph Algorithms
Tap to enlarge
Complete a template computing all-pairs shortest-path lengths in a directed graph G. Its n×n adjacency matrix A has A[i,j]=1 for an edge i→j and 0 otherwise. Initialization loops over i=1..n and j=1..n and executes: if A[i,j]=0 then P[i,j]=____ else P[i,j]=____; The algorithm then has nested loops, in this exact order: for i=1..n, for j=1..n, for k=1..n, executing: P[____,____] = min{____,____}; Copy and complete the line in the algorithm’s triple loop so that the algorithm is correct.
Shared context
For a directed unweighted graph, binary adjacency A[i,j] equals 1 for an edge i → j and 0 otherwise. Initialize a distance table P and run the printed loops in the order i outermost, then j, then k. Standard shortest-path distances permit an empty path of length 0.
Answer & solution
Answer: P[j,k] = min(P[j,k], P[j,i] + P[i,k]) (no official key was published)
1. Respect the printed loop order: i is outermost, j is next, and k is innermost. In Floyd–Warshall the outer loop must identify the newly allowed intermediate vertex. Therefore i is that intermediate, j is the source, and k the destination.
2. State the invariant. Before outer iteration i, P[j,k] is the shortest distance from j to k using only vertices 1,…,i−1 as internal vertices. Initialization supplies paths with no internal vertices: 0 on the diagonal, 1 for a direct edge, and ∞ otherwise.
3. Split paths into two exhaustive cases. A shortest path allowed after iteration i either avoids i internally, in which case its best length is the old P[j,k], or passes through i, in which case it can be split into a j→i portion and an i→k portion. Their best combined length is P[j,i]+P[i,k]. Nonnegative unit weights let us choose a shortest path without repeated positive-length cycles.
4. Take the better candidate and fill the line as:
P[j,k] = min(P[j,k], P[j,i] + P[i,k]);
For example, if the current j→k value is ∞ while P[j,i]=2 and P[i,k]=3, the update discovers a path of length 5. If P[j,k] were already 4, the minimum would retain 4.
5. Verify in-place and final correctness. During iteration i, the zero diagonal means an update through i does not lower the distances into or out of i; the in-place recurrence therefore preserves the invariant. After i=n, all vertices are allowed internally, so the table gives every shortest-path distance. Interpret ∞+x as ∞, or guard finite arithmetic against overflow.
6. Avoid a loop-order substitution error. The familiar form P[i,j]=min(P[i,j],P[i,k]+P[k,j]) assumes k is outermost. Under the source’s i,j,k loop order, using that form would generally be incorrect. Exhaustive comparison with BFS on every directed three-vertex graph, including self-loops, verifies the completed initialization and the stated j,k update.
Complete a template computing all-pairs shortest-path lengths in a directed graph G. Its n×n adjacency matrix A has A[i,j]=1 for an edge i→j and 0 otherwise. Initialization loops over i=1..n and j=1..n and executes: if A[i,j]=0 then P[i,j]=____ else P[i,j]=____; The algorithm then has nested loops, in this exact order: for i=1..n, for j=1..n, for k=1..n, executing: P[____,____] = min{____,____}; Complete the running-time expression O(____).
Shared context
For a directed unweighted graph, binary adjacency A[i,j] equals 1 for an edge i → j and 0 otherwise. Initialize a distance table P and run the printed loops in the order i outermost, then j, then k. Standard shortest-path distances permit an empty path of length 0.
Answer & solution
Answer: O(n³), more precisely Θ(n³) (no official key was published)
1. Count initialization work. There are n choices for the first index and n for the second, so initializing P visits n² entries. Each requires only a constant-time case selection and assignment, giving Θ(n²).
2. Count the algorithm’s updates. The source has three nested loops, over i, j, and k, each running from 1 to n. There is no data-dependent early termination. Thus the innermost statement executes n×n×n = n³ times.
3. Count work per update. Reading two candidate distances, adding, comparing with the old entry, and writing the minimum take constant time under the usual RAM model with constant-time distance arithmetic. Therefore the update phase costs Θ(n³).
4. Combine the phases. Θ(n²)+Θ(n³)=Θ(n³), since the cubic term dominates as n grows. The requested big-O blank is n³, so the answer is O(n³); the tighter bound is Θ(n³).
5. Keep time and space distinct. The distance table contains n² entries and uses Θ(n²) space. Its space requirement does not reduce the cubic number of updates, and an adjacency-matrix input does not make this particular triple-loop implementation linear in the number of edges.
Quicksort selects each pivot randomly. What is its worst-case sorting complexity on n values: O(n), O(n log n), O(n²), or O(n!)?
Your answer
Answer & solution
Answer: C (no official key was published)
Step 1: Random pivot selection improves the expected split quality, but it does not make extreme pivots impossible. A sequence selecting the minimum or maximum at every partition still has nonzero probability.
Step 2: That sequence performs(n−1)+(n−2)+…+1=n(n−1)/2 partition comparisons, yielding Θ(n²).
Thus C is the tight worst-case bound. Θ(n log n) is the expected runtime over the random choices, not the maximum possible runtime of a particular execution.
Compare f(n)=n² lg n and g(n)=n(lg n)^10. Which asymptotic relationship holds: only f=O(g), only g=O(f), neither, or both?
Your answer
Answer & solution
Answer: B (no official key was published)
Step 1: Divide f(n)=n² lg n by g(n)=n(lg n)10. The ratio is n/(lg n)9.
Step 2: Put t=lg n, so the ratio becomes 2t/t9, which tends to infinity because an exponential dominates every fixed power of t.
Therefore g=O(f), while f is not O(g), giving B. The logarithmic factor with exponent 10 cannot compensate asymptotically for the additional factor n in f.
In BFS from r in an undirected unweighted graph, vertex u is visited before v. Must d(r,u)<d(r,v), >, ≤, or none of these?
Your answer
Answer & solution
Answer: C (no official key was published)
Step 1: Breadth-first search’s FIFO queue processes all vertices at distance k before any vertex at distance k+1. Thus dequeue/discovery order is nondecreasing in distance from r.
Step 2: Two distinct vertices in the same layer can occur in either order, so visiting u first does not imply a strict inequality. A star centered at r supplies such an equal-distance example.
Therefore d(r,u)≤d(r,v), C, for vertices reached by this BFS. Unreachable vertices are not visited by the traversal from r.
Answer: {n1–n2,n1–n6,n2–n4,n3–n4,n4–n5}, weight 25. (no official key was published)
Step through it (10 steps)
Apply Kruskal in nondecreasing weight order. Take n1–n2 (2), then n1–n6 (3). The weight-4 edges n2–n4 and n4–n6 both connect n4 to the same component; take either, say n2–n4. Reject the other because it closes a cycle. Take n3–n4 (7), joining n3. Reject n1–n3 (8), which now closes a cycle. Take n4–n5 (9), joining the final vertex, and stop after five edges. Total weight is 2+3+4+7+9=25. The tree is connected and acyclic; Kruskal’s cut property establishes minimality.
The unique cheapest edge crossing cut {n2} is n1–n2 (2), so every MST contains it. Similarly cut {n6} forces n1–n6 (3), cut {n3} forces n3–n4 (7), and cut {n5} forces n4–n5 (9). These four edges leave two components, {n1,n2,n6} and {n3,n4,n5}. Their cheapest connecting edges are n2–n4 and n6–n4, both weight 4. Either one completes a tree of weight 25; choosing both would create a cycle and require losing a forced edge. Hence there are exactly two MSTs.
For a connected weighted undirected graph, compare the minimum edge weight present in different MSTs.
Answer & solution
Answer: Yes: every MST has minimum edge weight equal to the graph’s globally minimum edge weight. (no official key was published)
Let m be the minimum weight of any edge joining distinct vertices. Suppose an MST T had no edge of weight m. Add an edge e of weight m to T. A tree plus one edge contains a cycle, and every other edge on that cycle would be heavier than m. Removing any such edge yields a spanning tree lighter than T, a contradiction. Therefore every MST includes an edge of weight m. The identity of that edge need not be unique, but the numerical minimum is. For the given graph it is 2.
For a connected weighted undirected graph, compare the maximum edge weight present in different MSTs.
Answer & solution
Answer: Yes; for the given graph the invariant maximum is 9. (no official key was published)
Suppose MST T has maximum edge weight M, and another MST U has all edge weights less than M. Remove an edge of weight M from T, splitting its vertices into two components. Because U is connected, some U edge crosses this cut. Its weight is less than M; inserting it into T minus the removed edge produces a lighter spanning tree, contradicting minimality. Swapping T and U rules out either having a strictly larger maximum. This proves equality of the maximum value, not uniqueness of the heaviest edge or of the MST itself. In the supplied graph n5’s cheapest incident edge has weight 9, and the constructed MST’s largest weight is 9.
A sorted array s contains n integers. Determine whether two distinct elements sum to less than 1000. What is the most efficient asymptotic runtime, including choice O(1)?
Your answer
Answer & solution
Answer: A (no official key was published)
Step 1: In ascending order, the smallest sum of two distinct positions is s[1]+s[2]. Every other pair replaces one or both elements by values at least as large.
Step 2: If that sum is below 1000, a qualifying pair exists; otherwise no pair can qualify. Only two accesses, an addition, and a comparison are needed.
Thus Θ(1), option A, for n≥2 with random-access storage. For n<2 return false immediately. Searching all pairs or applying a two-pointer scan is unnecessary for this inequality-existence question.
For array s[1…n] and 1≤k≤n, execute reverse(s,1,k),reverse(s,k+1,n),reverse(s,1,n). Does this rotate left by k,leave unchanged,reverse everything,or none?
Your answer
Answer & solution
Answer: A (no official key was published)
Step 1: Split the original array into consecutive blocks A=s[1…k] and B=s[k+1…n], so it is AB. The first two operations produce AR BR.
Step 2: Reversing the whole concatenation reverses block order and each block: (AR BR)R=BA. This moves the first k entries to the end while preserving order within each block.
Thus A, a left rotation by k. For k=n, the second range is empty and must be treated as a no-op; the full rotation leaves the array unchanged.
Asymptotic comparison using logarithmic identities
Asymptotic Analysis & Recurrences
Tap to enlarge
Let f(n)=3n^(√n),g(n)=2^(√n log2 n),h(n)=n!. Which is true: h=O(f),h=O(g),g is not O(f),or f=O(g)?
Your answer
Answer & solution
Answer: D (no official key was published)
Step 1: Use 2log2 n=n to simplify g(n)=n√n. Hence f(n)=3g(n), so f and g are Θ-equivalent. This proves D and refutes the claim that g is not O(f).
Step 2: Factorial grows faster: n!≥(n/2)n/2, whose logarithm is(n/2)log(n/2), while log g=√n log n. Their ratio of logarithmic scales tends to infinity.
Connected undirected G has distinct edge weights. Which is false: every MST contains the minimum edge; if the maximum edge lies in an MST it is a bridge; no MST contains the maximum edge; G has a unique MST?
Your answer
Answer & solution
Answer: C (no official key was published)
Step 1: The globally lightest edge is the unique lightest edge across a cut separating one endpoint from the other, so the cut property forces it into the MST. Distinct weights also give a unique MST.
Step 2: If the maximum edge lies on a cycle, it is the unique heaviest edge there and the cycle property excludes it. Thus if it appears in an MST, it must be a bridge. But a bridge is mandatory, even when globally heaviest.
A graph that is itself a weighted tree supplies a counterexample to C. Therefore C is false, while B correctly handles the bridge case.
In undirected DFS, u is discovered and v is the next newly discovered vertex. Which is always true? The options assert a direct edge with ancestry, or that absent edge implies u is a leaf, or that absent edge implies the same parent.
Your answer
Answer & solution
Answer: C (no official key was published)
Step 1: If u has an unvisited neighbor when its exploration begins, DFS immediately follows an edge to such a neighbor. Then the next discovery v is adjacent and becomes a child of u.
Step 2: If the next discovery is not adjacent to u, DFS must have exhausted u without discovering any child and backtracked to an ancestor before reaching v. Therefore u is a leaf in the DFS tree, proving C.
The backtrack may cross several ancestors, so u and v need not share a parent. The two options requiring adjacency in every case are also too strong.
Let m,n be positive integers and let the line be y=(n/m)x. Define A=mq−np for endpoint (p,q), and B=ms−nr for endpoint (r,s). If A<0, is (p,q) above, below or on the line?
Answer & solution
Answer: Below the line. (no official key was published)
Because m>0, dividing mq−np<0 by m preserves the inequality and gives q<(n/m)p. At horizontal coordinate p, the line has height (n/m)p, whereas the point has smaller height q. Therefore the point is below the line. Equality A=0 would mean on the line, and A>0 would mean above. The assumption m>0 is essential when converting the sign to this vertical interpretation.
Let m,n be positive integers and let the line be y=(n/m)x. Define A=mq−np for endpoint (p,q), and B=ms−nr for endpoint (r,s). Complete clash: initialize false; line4 tests A [box] 0; line5 tests B [box] 0; line6 tests A [box] 0 and B [box] 0; line7 tests A [box] 0 and B [box] 0. Each successful test sets clash=true.
Answer & solution
Answer: Line4 =; line5 =; line6 < and >; line7 > and < (last two cases may be exchanged). (no official key was published)
A segment intersects the infinite line if either endpoint lies on it, or if its endpoints lie on opposite sides. The completed Pascal-style code is:
function clash(m,n,p,q,r,s: integer): Boolean;
begin
clash := false;
if (m*q-n*p) = 0 then clash := true; {line 4}
if (m*s-n*r) = 0 then clash := true; {line 5}
if (m*q-n*p) < 0 and (m*s-n*r) > 0 then clash := true; {6}
if (m*q-n*p) > 0 and (m*s-n*r) < 0 then clash := true; {7}
end;
For a point interpolated along the segment with parameter t in [0,1], the signed expression is (1−t)A+tB. If A and B have opposite signs, this linear continuous function has a zero in the interval. If both have the same nonzero sign, every convex combination has that sign and there is no intersection. Endpoint equality also handles a zero-length segment lying on the line and a whole segment coincident with it. Avoid multiplying A*B merely to test the signs: that introduces extra overflow risk. As mathematical pseudocode, the original arithmetic assumes exact integer results.
Array f[0..M] starts at zero. fib(n) checks n>M for error, returns 1 for n=0 or 1, then executes if([1]) return [2]; t=fib(n−1)+fib(n−2); [3]; return t. Assume 0<=n<=M and exact arithmetic. Fill the three boxes.
Answer & solution
Answer: (1) f[n]!=0; (2) f[n]; (3) f[n]=t; (no official key was published)
The completed function is:
fib(n) {
if (n > M) error();
if (n == 0) return 1;
if (n == 1) return 1;
if (f[n] != 0) return f[n];
t = fib(n-1) + fib(n-2);
f[n] = t;
return t;
}
Use a local t in each recursive activation. Since both base cases equal 1, every valid Fibonacci result is positive. Thus zero safely means “not computed” under the stated exact-arithmetic model. On a cache miss, recursively obtain the two predecessors, store their sum before returning, and reuse it whenever n is requested again. For example fib(4) obtains fib(3)=3, then reads the cached fib(2)=2, producing 5. The base cases need not be stored because they already take constant time. With overflowing machine arithmetic, zero might cease to be a valid sentinel; practical implementations can use an independent computed flag or arbitrary-precision values.
Array f[0..M] starts at zero. fib(n) checks n>M for error, returns 1 for n=0 or 1, then executes if([1]) return [2]; t=fib(n−1)+fib(n−2); [3]; return t. Assume 0<=n<=M and exact arithmetic. With memoization filled correctly, find the running time of the first fib(n) computation.
Answer & solution
Answer: Θ(n) time in the unit-cost arithmetic model; Θ(n) recursion depth and used cache cells. (no official key was published)
For each k from 2 through n there is at most one cache miss. That miss performs a constant number of comparisons, two recursive calls, one addition and one store. All later calls on the same k return from the cache in constant time. The subproblem dependency graph has n+1 possible arguments and two outgoing calls per non-base argument, so the total number of calls and primitive operations is O(n), not exponential. A first computation must actually compute each of fib(2),...,fib(n), giving Ω(n) work; therefore the tight bound is Θ(n). The descent n,n−1,...,1 can occupy Θ(n) stack frames. Initializing the provided whole array costs Θ(M) separately, but the stem says it is already initialized. If bit complexity is counted, Fibonacci numbers have Θ(n) bits, and the n additions have increasing cost; the conventional linear answer assumes constant-time arithmetic.
An array has four 0s, five 1s and three 2s, and is to be sorted increasingly using swaps. GFG Q64 p9 permits nonadjacent swaps; GateForum Q17 p16 requires adjacent swaps. Solve both distinct source versions. Find the maximum, over initial orders, of the minimum required swaps.
Answer & solution
Answer: 7 for arbitrary swaps; 47 for adjacent-only swaps. (no official key was published)
Arbitrary-swap version: partition the target positions into zones of sizes 4,5,3 for 0,1,2. A misplaced value j in zone i is a directed edge i→j. Incoming and outgoing edge counts balance at every zone. First cancel every opposite pair i→j,j→i with one swap, fixing two positions. Once opposite pairs are exhausted, remaining edges form consistently oriented 3-cycles, each fixed by two swaps. Let d be the number of canceled pairs and c the number of remaining 3-cycles. This uses d+2c swaps and moves M=2d+3c<=12 misplaced positions. Each 3-cycle uses one position in the 2-zone, so c<=3. For c=0,1,2,3, the bound d<=floor((12−3c)/2) gives d+2c<=6,6,7,7 respectively. Hence seven swaps always suffice. Attainment: use 1111|00222|001, where bars show target zones. Its opposite pairs are two 0/1 pairs and one 1/2 pair, and the remaining six misplaced entries form two 3-cycles, so seven suffice. To see six cannot suffice, all 12 positions are initially wrong. Six swaps would have to fix two positions each, and thus every swap would need to exchange an opposite pair without creating any new error. There are only three opposite pairs initially; after removing those, the remaining directed 3-cycles have no such pair. Six swaps are therefore impossible. The worst-case optimum is exactly 7. Adjacent-only version: the minimum number of swaps equals the inversion count because an adjacent swap changes that count by exactly 1, and swapping adjacent inverted pairs sorts while decreasing it each time. The largest inversion count is attained by descending groups 222111110000. Every unequal pair is then inverted: 3*5+3*4+5*4=15+12+20=47. Equal-value pairs contribute zero. This discrepancy is substantive; the paper is authenticated as the official wording.
An array has four 0s, five 1s and three 2s, and is to be sorted increasingly using swaps. GFG Q64 p9 permits nonadjacent swaps; GateForum Q17 p16 requires adjacent swaps. Solve both distinct source versions. Give an order attaining the worst-case minimum.
Answer & solution
Answer: Arbitrary: 111100222001. Adjacent-only: 222111110000. (no official key was published)
For arbitrary swaps, choose [1,1,1,1 | 0,0,2,2,2 | 0,0,1], with target-zone lengths 4,5,3. The counts are four 0s, five 1s, three 2s. Number positions 1 through 12. One seven-swap sorting sequence is (1,5),(2,6),(7,12),(3,10),(8,10),(4,11),(9,11). After the first three swaps, the unsorted portion consists of two cycles, each carrying a 1 in the 0-zone, a 2 in the 1-zone and a 0 in the 2-zone. Each takes two swaps. All 12 entries were initially misplaced, so six swaps would require every swap to fix two errors. Only three opposite pairs are available, and a residual 3-cycle cannot be fixed in that way. Thus seven are necessary as well as sufficient; the general upper bound is proved in part(a). For adjacent-only swaps, choose [2,2,2,1,1,1,1,1,0,0,0,0]. It has 3*5 inversions of type(2,1), 3*4 of type(2,0), and 5*4 of type(1,0), for 47. No array with these multiplicities can have more inversions, because every unequal pair is already inverted here. An adjacent inversion-removal sort takes exactly 47 swaps. This descending arrangement is not the arbitrary-swap witness: allowing distant exchanges changes the optimization problem.
Does stable sorting mean O(n log n) time, preservation of the order of equal keys, divide-and-conquer, or O(n) space?
Your answer
Answer & solution
Answer: B (no official key was published)
Label two records with equal key as (k,first) and (k,second), in that input order. A stable sort guarantees that first still precedes second afterward. That property matters when one field has already been sorted and a later stable pass sorts another field. Runtime, extra space and algorithmic paradigm are separate properties: a stable insertion sort may take quadratic time, while some fast sorts are unstable. Hence the definition is B.
Partition n array values so negatives precede positives. What is the minimum number of arbitrary exchanges in the worst case: n−1,n,n+1,or none?
Your answer
Answer & solution
Answer: D: floor(n/2) (no official key was published)
Suppose there are k negative values. Their final region is the first k positions. Let t positives currently lie in that region; exactly t negatives then lie outside it. Pair and swap each misplaced positive with a misplaced negative, requiring t exchanges. Every exchange fixes at most one misplaced negative in the target region, proving optimality. Since t≤min(k,n−k), the worst case over k is floor(n/2), attained by placing balanced sign groups in the wrong halves. Thus none of the listed formulas A–C is the general answer. This uses arbitrary swaps, not adjacent swaps.
Sort 20,47,15,8,9,4,40,30,12,17 by straight two-way merging. What is the order after the second pass?
Your answer
Answer & solution
Answer: B: 8,15,20,47,4,9,30,40,12,17 (no official key was published)
Step through it (10 steps)
Pass one merges singleton runs into pairs: [20,47], [8,15], [4,9], [30,40], [12,17]. Pass two merges adjacent pairs into four-element sorted runs. The first two yield [8,15,20,47]; the next two yield [4,9,30,40]. The final pair has no partner and remains [12,17]. Concatenating these runs gives B. The whole array is not yet sorted; later passes merge the length-four runs and the remaining tail.
For n a power of two, how many multiplications are minimally needed to compute a^n? Options log2 n, sqrt(n), n−1,n.
Your answer
Answer & solution
Answer: A (no official key was published)
Write n=2k. Repeated squaring computes a²,a⁴,…,a2^k, using exactly k multiplications. To prove minimality in the ordinary multiplication-only straight-line model, observe that one multiplication can at most double the largest exponent already available. Starting with exponent 1, after t multiplications every computed exponent is at most 2t. Reaching n therefore requires t≥log2 n=k. Construction and lower bound coincide, giving A; n=1 needs zero multiplications.
Merge file lengths 10,20,15,5,25 with pairwise merging; cost is records moved. Choose165,90,75,65.
Select all that apply
Answer & solution
Answer: A: 165 (no official key was published)
Always merge the two shortest remaining files, as in the optimal merge/Huffman construction. Merge5+10=15, costing 15; then 15+15=30, costing 30; then 20+25=45, costing 45; finally 30+45=75, costing 75. Total cost is 15+30+45+75=165. The greedy choice is optimal because two smallest weights can occupy deepest sibling leaves of an optimal merge tree, after which contracting them leaves the same problem on fewer files. Counting only 75 ignores repeated moves through intermediate merges.
M:T(n)=T(n−1)+n; N:T(n)=T(n/2)+n; O:T(n)=T(n/2)+n log n; P:T(n)=T(n−1)+log n. Match to U O(n),V O(n log n),W O(n²),X O(log² n).
Select all that apply
Answer & solution
Answer: B: M-W,N-U,O-V,P-V (no official key was published)
For M, summing 1+2+…+n gives Θ(n²). For N, the work is n+n/2+n/4+…=Θ(n). For O, the first term already gives n log n and the geometric weighted tail is O(n log n), hence Θ(n log n). For P, summing log k for k=2…n gives log(n!)=Θ(n log n): the upper bound is n log n and the last n/2 terms each exceed log(n/2). Thus M-W,N-U,O-V,P-V, option B. The listed big-O labels are interpreted as tight intended growth classes; loose upper bounds would not define a unique matching.
An n×n matrix A has every row and column in ascending order. Draw a decision tree finding its first, second, and third smallest entries using the minimum number of comparisons. Assume n≥2; count repeated values as separate entries.
Shared context
An n×n matrix A has every row and column in ascending order. Draw a decision tree finding its first, second, and third smallest entries using the minimum number of comparisons. Assume n≥2; count repeated values as separate entries.
Answer & solution
Answer: Two comparisons suffice and are necessary in the worst case. (no official key was published)
The first entry is always A₁₁. Set b=A₁₂ and c=A₂₁. Every remaining entry is at least b or c, so the second is min(b,c).
If b≤c, the only candidates for third are c and d=A₁₃. Other entries in the first row are at least d; entries outside the first row are at least c (including A₂₂). If c<b, the analogous candidates are b and e=A₃₁. When n=2, the missing d or e can be treated as +∞, so the third is simply the other one of b,c and just one comparison suffices for that special size.
For n≥3 the full decision tree is:
compare b ≤ c?
/ yes \ no
compare d ≤ c? compare e ≤ b?
/ yes \ no / yes \ no
(A₁₁,b,d) (A₁₁,b,c) (A₁₁,c,e) (A₁₁,c,b)
Each root-to-leaf path has two comparisons. The leaves give the first three entries in order. Ties can follow the ≤ branch: tied entries have equal values, so either identity order is valid.
Optimality for n≥3: all four strict order possibilities displayed at the leaves can occur in a row-and-column-sorted matrix. A single binary comparison has only two outcomes and cannot distinguish four possible ordered triples of positions; two comparisons are necessary in the worst case. For n=2 there are only the two orders of b,c and one comparison is both sufficient and necessary. For n=1 a third entry does not exist, so the task presupposes at least n=2.
Given the algorithm below, with procedure A taking O(1) time and B(n) taking O(1/n) time, derive its time complexity in O-notation. GFG retains the O symbols lost in GateForum.
what(n): if n = 1: call A else: what(n-1) call B(n)
Assume n is a positive integer.
Shared context
Given the algorithm below, with procedure A taking O(1) time and B(n) taking O(1/n) time, derive its time complexity in O-notation.
what(n): if n = 1: call A else: what(n-1) call B(n)
Assume n is a positive integer.
Answer & solution
Answer: Procedure-cost-only model: O(log n). With ordinary constant recursion/control overhead: Θ(n). (no official key was published)
In the idealized accounting suggested by the question, count only costs of A and B. Let their costs be a and b(k), with a=O(1) and b(k)=O(1/k). The recurrence is T(1)=a and T(n)=T(n−1)+b(n). Expanding gives T(n)=a+Σ(k=2..n)b(k)≤C₀+C₁Σ(k=2..n)1/k for suitable constants, absorbing finitely many small inputs into C₀.
The harmonic sum is bounded above by 1+ln n, by comparison with the integral of 1/x. Thus T(n)=O(log n). If the supplied procedure costs are actually Θ(1) and Θ(1/n), the lower integral bound gives Θ(log n), but upper bounds alone do not prove this tight classification.
Cost-model qualification: a real RAM implementation must perform a test, decrement, recursive call and return at each of n recursion levels. These contribute Θ(1) per level, giving T_RAM(n)=T_RAM(n−1)+Θ(1)+O(1/n)=Θ(n), with Θ(n) stack depth. Moreover a nonzero discrete instruction cost cannot asymptotically decrease as 1/n. Therefore O(log n) is the intended abstract procedure-cost result, not an unconditional full implementation running-time claim.
Which technique underlies the standard all-pairs shortest-path algorithm: dynamic programming, backtracking, greedy, divide-and-conquer?
Your answer
Answer & solution
Answer: A (no official key was published)
Floyd–Warshall defines Dk (i, j) as the best path using only the first k vertices as intermediates. It either avoids k or passes through it, yielding Dk (i, j)=min (Dk−1(i, j), Dk−1(i, k)+Dk−1(k, j)). Reusing these overlapping subproblem values is dynamic programming, A. The answer refers to this standard all-pairs algorithm; other algorithms can solve restricted graph classes, so the task name alone is not a proof that every possible implementation uses the same paradigm.
Match log n, n, n log n, n² to binary search, selection, merge sort, insertion sort.
Your answer
Answer & solution
Answer: B: 3, 1, 4, 2 (no official key was published)
Binary search halves a sorted interval each step, giving logarithmic search time. Selection of a specified rank can be done in linear worst-case time using median-of-medians. Merge sort has logarithmically many levels with linear work per level, giving n log n. Insertion sort can shift a quadratic number of elements on reverse-sorted input. Therefore the intended mapping is 3, 1, 4, 2, B. “Selection” means order-statistic selection, not selection sort, whose worst-case comparisons are quadratic.
How many nonempty substrings of all lengths can be formed from a length-n string? Choices include n, n², 2^n, n (n+1)/2.
Your answer
Answer & solution
Answer: D for positional occurrences (no official key was published)
A substring is determined by its starting and ending positions. For length k there are n−k+1 placements. Summing these counts from k=1 to n gives n+(n−1)+…+1=n (n+1)/2, D. This counts occurrences, even when their text is identical. If the phrase “different lengths” means counting length values alone, there are only n; if it means distinct substring contents, the answer depends on the string. The standard occurrence interpretation is explicitly used.
Match all-pairs shortest paths, quicksort, minimum spanning tree, connected components with dynamic programming, divide-and-conquer, greedy, DFS.
Your answer
Answer & solution
Answer: B: 3, 4, 1, 2 (no official key was published)
Floyd–Warshall solves all-pairs paths through dynamic-programming subproblems. Quicksort partitions around a pivot and recursively sorts subarrays, a divide-and-conquer strategy. Prim or Kruskal builds an MST using safe greedy edge choices. Repeated DFS visits each connected component. Thus the four matches are 3, 4, 1, 2, option B. These refer to standard representative algorithms rather than asserting that each task has only one possible solution paradigm.
T(1)=1 and T(n)=2T(floor (n/2))+sqrt (n) for n≥2. Choose O(sqrt n), O(n), O(log n), none.
Your answer
Answer & solution
Answer: B: Θ(n) (no official key was published)
At recursion depth j there are roughly 2j subproblems of size n/2j. Their combined nonrecursive work is sqrt (n)·2j/2, increasing geometrically toward the leaves. Summing through depth about log 2 n gives O(n), and there are Θ(n) leaves each contributing constant work, providing Ω(n). Hence T(n)=Θ(n), so B. Equivalently the Master theorem has nlog 2 2=n and toll n1/2, which is polynomially smaller; rounding does not change the asymptotic order.
The vertices are the n² integer lattice points (x,y), 1≤x,y≤n, n≥2. Distinct vertices are adjacent when BOTH |x1−x2|≤1 and |y1−y2|≤1; an edge has Euclidean length sqrt((x1−x2)²+(y1−y2)²). This is the GateForum p11 adjacency, including the second-coordinate bound omitted in GFG. Find the minimum spanning-tree weight.
Answer & solution
Answer: n²−1. (no official key was published)
There are n² vertices, so every spanning tree has exactly n²−1 edges. Distinct integer lattice points are at distance at least 1; hence every spanning tree has weight at least n²−1.
This bound is achievable without using any diagonals. In each row, connect its n vertices consecutively with n−1 horizontal unit edges. This uses n(n−1) edges and leaves n connected row paths. Connect consecutive rows by vertical unit edges along the first column, using n−1 more edges. The result is connected and has n(n−1)+(n−1)=n²−1 edges; equivalently, joining the disjoint row trees by a path cannot create a cycle. Its weight is exactly n²−1, matching the lower bound.
For n=2 this construction has three unit edges and weight 3. Using a diagonal would replace a unit edge by one of length √2 and cannot improve the minimum.
For this minimum, however, the same answer remains valid under that literal variant. All distinct vertices are still at least unit distance apart, and the unit-edge construction is still allowed. Thus this particular answer is robust even though the printed graph definitions differ.
The vertices are the n² integer lattice points (x,y), 1≤x,y≤n, n≥2. Distinct vertices are adjacent when BOTH |x1−x2|≤1 and |y1−y2|≤1; an edge has Euclidean length sqrt((x1−x2)²+(y1−y2)²). This is the GateForum p11 adjacency, including the second-coordinate bound omitted in GFG. Find the maximum spanning-tree weight; also distinguish the literal GFG graph that constrains only |x1−x2|≤1.
Answer & solution
Answer: (2n−2)√(1+(n−1)²)+(n−1)+nΣ_(j=2)^(n−1)√(1+max(j−1,n−j)²) (no official key was published)
In the stated king-move grid, every edge is either horizontal/vertical with weight 1 or diagonal with weight √2. We therefore want as many diagonal edges as a spanning tree can contain.
Color vertex (x,y) by the parity of x+y. A diagonal changes both coordinates by one, so it preserves this parity; a horizontal or vertical edge changes it. Both parity classes are nonempty for n≥2. A connected spanning tree must consequently include at least one unit edge to join the two classes. Since it has n²−1 edges in total, its weight is at most (n²−2)√2+1.
To attain the bound, observe that the diagonal-only graph has exactly two connected components, one of each parity. Here is a constructive connectivity argument. Repeatedly use an upward diagonal to reduce y until reaching the first row; at a side boundary choose the inward direction, always possible because n≥2. On the first row, vertices of a fixed parity can move two columns at a time through a vertex of the second row. Thus all vertices of each parity are connected by diagonals. Take a spanning tree inside each diagonal component. Together they use n²−2 diagonal edges. Add any unit edge between the components. This produces a spanning tree attaining the upper bound.
For n=2 the two diagonals, joined by one side, have weight 2√2+1. Under the paper's literal omission of the y-bound, longer edges are allowed when n≥3. Its maximum is instead
Here is a separate optimality proof for that literal graph. Call vertices on y=1 or y=n boundary vertices. For each interior vertex at row j, select an edge to a farthest boundary row in an adjacent column. Such a column always exists for n≥2. Its length is √(1+max(j−1,n−j)²), a maximum edge across the cut isolating that vertex. Add these edges while each interior vertex is still isolated; all chosen parents are boundary vertices, so no cycle arises. By the maximum-spanning-tree cut property, each addition is safe.
Next add all 2n−2 boundary diagonals with |dx|=1 and |dy|=n−1. They are globally maximum edges, each of length √(1+(n−1)²), and form two disjoint alternating-row paths on the 2n boundary vertices. Interior attachments do not join those paths. Finally join them by a same-column edge from y=1 to y=n, of length n−1. Every competing cross-component edge with an interior endpoint is at most √(1+(n−2)²)<n−1 for n≥3. Remaining boundary cross-edges have length at most n−1, so this last edge is also cut-safe. At n=2 there are no interior vertices and the bridge length is 1.
The safe selections form a spanning tree and give the displayed sum: n equal-length interior attachments for each row j, 2n−2 boundary diagonals, and one bridge. Thus both materially different printed graphs have an explicit maximum and a proof, rather than silently restoring a bound.
For positive integers n,m, consider the directly recursive, nonmemoized function function F(n,m:integer):integer; begin if (n<=0) or (m<=0) then F:=1 else F:=F(n-1,m)+F(n,m-1) end. Use C(s,t)=C(s−1,t)+C(s−1,t−1). How many calls to F occur when evaluating F(n,m), including the original call?
Answer & solution
Answer: 2C(n+m,n)−1. (no official key was published)
The execution forms a full binary recursion tree. Each nonbase call executes exactly two child calls, and each base call has no children. Every base call returns 1, while every internal call returns the sum of its two children's values. The root's return value is consequently the number L of leaf activations. From the recurrence solution, L=F(n,m)=C(n+m,n).
In a full binary tree with I internal nodes and L leaves, the number of edges is 2I because every internal node has two children. It is also I+L−1 because a tree has one fewer edge than nodes. Equating gives I=L−1, so the total number of call activations is I+L=2L−1. Therefore the requested count, including the root call, is
2C(n+m,n)−1.
For n=m=1, the root calls F(0,1) and F(1,0), giving three activations; the formula gives 2·2−1=3. For n=1,m=2 it gives five. If only calls initiated recursively were requested, one would subtract the original root and obtain 2C(n+m,n)−2, but that is not the wording here.
This counts the actual nonmemoized execution tree, including repeated argument pairs as separate calls. Counting only distinct states, or assuming a dynamic-programming implementation, would answer a different complexity question.
An array A[1..n], n≥1, contains positive integers, and M>0. Complete the boxes in this program so it prints the shortest nonempty contiguous-subarray length having sum at least M, or n+1 if none exists. The program uses one-based array indexing: 1 begin 2 i:=1; j:=1; 3 sum:=[B3]; 4 min:=n; finish:=false; 5 while not finish do 6 if [B6] then 7 if j=n then finish:=true 8 else 9 begin 10 j:=j+1; 11 sum:=[B11] 12 end 13 else 14 begin 15 if (j-i)<min then min:=j-i; 16 sum:=sum-A[i]; 17 i:=i+1 18 end; 19 writeln(min+1) 20 end
Answer & solution
Answer: B3=A[1]; B6=sum<M; B11=sum+A[j]. (no official key was published)
Fill line 3 with A[1], line 6 with sum<M, and line 11 with sum+A[j]. The invariant is that sum equals A[i]+…+A[j], with value zero if the current window is empty (i=j+1).
Initially i=j=1, so sum must be A[1]. If sum<M, the current window is too small. Removing positive elements cannot help it reach M, so extend the right endpoint. Line 10 has already incremented j, which is why line 11 adds A[j], not A[j+1]. If j=n, there is no further element to add and the loop can terminate.
If sum≥M, the current window is feasible. Its actual length is j−i+1, but min deliberately stores length minus one, so line 15 compares j−i. Remove A[i] and advance i to look for a shorter feasible window with the same right endpoint. Repeated shrinking examines the best ending-at-j choice before extending again. Positivity ensures that once a left endpoint is discarded, retaining it for later right endpoints cannot improve on a feasible length already considered.
For A=[2,3,1,2] and M=5, the first feasible window is [2,3], length 2. It stores min=1. After shrinking and extending, [3,1,2] is feasible but longer. The final print is 2. If no window reaches M, min stays n and the sentinel print is n+1. If one element alone reaches M, min becomes 0 and the answer is 1; removing that element creates a temporary empty window of sum zero, which safely forces extension or termination because M>0.
Both i and j only increase, giving O(n) time and O(1) auxiliary space. Negative array elements would invalidate the monotonic shrinking argument. The strict comparison at line 6 is essential: equality sum=M already satisfies the requested threshold. Full code and its statement numbering are reconstructed from the paper pp8–9, where the boxes and assignments remain visible.
Which asymptotic claim is false: (A) 100n log n=O(n log n/100); (B) sqrt(log n)=O(log log n); (C) for fixed 0<x<y, n^x=O(n^y); (D) 2^n is not O(n^k) for fixed k?
Your answer
Answer & solution
Answer: B (no official key was published)
Put t=log n. Then sqrt(log n)/(log log n)=sqrt(t)/log t tends to infinity, so no constant bounds the numerator by a multiple of the denominator eventually. Hence B is false. Multiplying n log n by fixed nonzero constants does not change its big-O class. For fixed x<y, nx/ny=nx−y tends to zero. Finally 2n eventually dominates every fixed-degree polynomial nk: the logarithm of their ratio is n log 2−k log n, which tends to infinity. Thus D is true, not the false statement sought.
Solve T(1)=2, T(n)=3T(n/4)+n asymptotically for powers of four.
Your answer
Answer & solution
Answer: A: Θ(n) (no official key was published)
At recursion depth j there are 3j subproblems of size n/4j, so the total nonrecursive work is n(3/4)j. Summing these decreasing geometric terms gives O(n), while the root alone costs n and proves Ω(n). More exactly, with k=log₄ n, the leaves contribute 2·3k and internal levels contribute 4n(1−(3/4)k). The total is 4n−2nlog₄3. Therefore the recurrence is linear, not n log n, because each successive level contributes less work than the preceding one.
A sought item is equally likely to occupy any of n positions in a sequentially searched list. Find the expected comparisons for a successful search.
Your answer
Answer & solution
Answer: D: (n+1)/2 (no official key was published)
If the item occupies position i, searching from the beginning requires i comparisons. Uniform success positions therefore give E[C]=(1+2+…+n)/n. The arithmetic-series sum is n(n+1)/2, so E[C]=(n+1)/2. This is not the unsuccessful-search cost n, because successful searches stop at their target. Nor is it a binary-search logarithm, since the stated algorithm scans sequentially rather than repeatedly halving a sorted range.
Compare quicksort comparisons for a list already ascending versus descending when no pivot or partition implementation is specified.
Your answer
Answer & solution
Answer: D in general; C for standard end-pivot worst-case counting (no official key was published)
With the first or last element chosen as pivot on every subarray, either monotone input can split into sizes 0 and n−1. Counting n−1 comparisons per partition gives n(n−1)/2 for both orientations, the usual equality answer C under that model. But the question does not specify pivot selection or partition code. A rule depending on input orientation can select balanced pivots in one case and extreme pivots in the other; even comparison-count conventions vary. Therefore no implementation-independent ordering follows, corresponding to D. The common equal-count result is conditional, not a universal theorem about every quicksort variant.
A complete undirected graph on vertices 0,1,…,n−1 has weight w(u,v)=|u−v| for distinct vertices. Draw a minimum spanning tree.
Answer & solution
Answer: Path 0—1—2—…—(n−1), total weight n−1. (no official key was published)
Every edge joins distinct integers, so its weight is at least 1. A spanning tree on n vertices contains exactly n−1 edges. Consequently every spanning tree has total weight at least n−1.
Connect consecutive vertices: (0,1),(1,2),…,(n−2,n−1). This is a connected path with no cycles, so it is a spanning tree. Each of its n−1 edges has weight 1, giving total n−1 and attaining the lower bound. Text diagram: 0 --1-- 1 --1-- 2 --1-- … --1-- (n−1), where the labels between dashes are edge weights.
For n≥2 it is also the unique MST. Achieving the lower bound requires every selected edge to have weight 1, and the only weight-1 edges in this graph are exactly the consecutive pairs. There are n−1 of them, so all must be selected. Alternatively, for the cut {0,…,k}|{k+1,…,n−1}, edge (k,k+1) is the unique minimum crossing edge and is mandatory by the cut property. When n=1 the empty tree has cost 0; the same n−1 formula applies.
A complete undirected graph on vertices 0,1,…,n−1 has weight w(u,v)=u+v for distinct vertices. Draw a minimum spanning tree.
Answer & solution
Answer: Star centered at 0, edges (0,v) for 1≤v<n; total n(n−1)/2. (no official key was published)
For each vertex v>0, consider the cut separating v from every other vertex. Its incident edges have weights v+u, with u≠v. The smallest possible u is 0, so (v,0) is the unique minimum-weight edge across this cut. By the cut property every MST must contain it.
Doing this for every v=1,…,n−1 gives exactly the star centered at 0. These n−1 edges connect all vertices and have no cycle, so the mandatory set itself is a spanning tree. Its weight is Σ_(v=1)n−1 v=n(n−1)/2. Text diagram: center 0 with a spoke to each v; spoke (0,v) has label v.
A second lower-bound proof roots any spanning tree at 0. Each nonroot vertex v has one parent p(v)≥0, so its parent edge costs v+p(v)≥v. Summing over all nonroot vertices gives total at least Σv. The star attains equality by taking every parent to be 0. This argument also shows uniqueness for n≥2: equality requires all parents 0. For n=1 there are no spokes and the minimum weight is 0. The complete graph assumption guarantees that every required spoke exists.
In the GFG p9 directed graph, edges with weights are A→B:6, A→C:90, A→F:2, A→E:70, B→D:41, C→B:12, C→E:10, D→C:12, F→B:22, F→C:60, F→D:50, E→F:15. GateForum p15 swaps the names E and F while keeping these positions and weights. Start at A. Give the Dijkstra settlement order.
Answer & solution
Answer: A, F, B, D, C, E (no official key was published)
Use the the paper labels first. Initialize d(A)=0 and all other labels to infinity. Settle A: tentative B=6,C=90,F=2,E=70. Settle F (2): B via F would be 24 and does not improve 6; C improves to 62 and D becomes 52. Settle B (6): D improves to 6+41=47. Settle D (47): C improves to 47+12=59. Settle C (59): E improves to 59+10=69; the edge back to B gives 71 and changes nothing. Finally settle E (69), whose edge to F gives 84 and changes nothing.
Thus the settlement order is A,F,B,D,C,E, with final distances 0,2,6,47,59,69 in that order. Predecessors for the E path are E←C←D←B←A, giving A→B→D→C→E and cost 6+41+12+10=69. This improves on the direct A→E cost 70 and the route A→F→C→E cost 72. All weights are nonnegative, so Dijkstra's settled distances are final.
A material the paper difference changes the answer to the named destination. Applying that relabelling, its settlement order is A,E,B,D,C,F. Its shortest A→E path is the direct edge of weight 2; the 69-cost bottom-vertex path ends at F there. The answers must remain tied to the chosen diagram. Decimal labels 90,60,50,70,10 contain zero glyphs, not an added symbolic variable.
In the GFG p9 directed graph, edges with weights are A→B:6, A→C:90, A→F:2, A→E:70, B→D:41, C→B:12, C→E:10, D→C:12, F→B:22, F→C:60, F→D:50, E→F:15. GateForum p15 swaps the names E and F while keeping these positions and weights. Start at A. Give the shortest A→E vertex sequence.
Answer & solution
Answer: A, B, D, C, E (no official key was published)
Use the the paper labels first. Initialize d(A)=0 and all other labels to infinity. Settle A: tentative B=6,C=90,F=2,E=70. Settle F (2): B via F would be 24 and does not improve 6; C improves to 62 and D becomes 52. Settle B (6): D improves to 6+41=47. Settle D (47): C improves to 47+12=59. Settle C (59): E improves to 59+10=69; the edge back to B gives 71 and changes nothing. Finally settle E (69), whose edge to F gives 84 and changes nothing.
Thus the settlement order is A,F,B,D,C,E, with final distances 0,2,6,47,59,69 in that order. Predecessors for the E path are E←C←D←B←A, giving A→B→D→C→E and cost 6+41+12+10=69. This improves on the direct A→E cost 70 and the route A→F→C→E cost 72. All weights are nonnegative, so Dijkstra's settled distances are final.
A material the paper difference changes the answer to the named destination. Applying that relabelling, its settlement order is A,E,B,D,C,F. Its shortest A→E path is the direct edge of weight 2; the 69-cost bottom-vertex path ends at F there. The answers must remain tied to the chosen diagram. Decimal labels 90,60,50,70,10 contain zero glyphs, not an added symbolic variable.
In the GFG p9 directed graph, edges with weights are A→B:6, A→C:90, A→F:2, A→E:70, B→D:41, C→B:12, C→E:10, D→C:12, F→B:22, F→C:60, F→D:50, E→F:15. GateForum p15 swaps the names E and F while keeping these positions and weights. Start at A. Give the shortest A→E cost.
Answer & solution
Answer: 69 (no official key was published)
Use the the paper labels first. Initialize d(A)=0 and all other labels to infinity. Settle A: tentative B=6,C=90,F=2,E=70. Settle F (2): B via F would be 24 and does not improve 6; C improves to 62 and D becomes 52. Settle B (6): D improves to 6+41=47. Settle D (47): C improves to 47+12=59. Settle C (59): E improves to 59+10=69; the edge back to B gives 71 and changes nothing. Finally settle E (69), whose edge to F gives 84 and changes nothing.
Thus the settlement order is A,F,B,D,C,E, with final distances 0,2,6,47,59,69 in that order. Predecessors for the E path are E←C←D←B←A, giving A→B→D→C→E and cost 6+41+12+10=69. This improves on the direct A→E cost 70 and the route A→F→C→E cost 72. All weights are nonnegative, so Dijkstra's settled distances are final.
A material the paper difference changes the answer to the named destination. Applying that relabelling, its settlement order is A,E,B,D,C,F. Its shortest A→E path is the direct edge of weight 2; the 69-cost bottom-vertex path ends at F there. The answers must remain tied to the chosen diagram. Decimal labels 90,60,50,70,10 contain zero glyphs, not an added symbolic variable.
Does merge sort use divide and conquer, backtracking, heuristic search, or a greedy approach?
Your answer
Answer & solution
Answer: A (no official key was published)
Merge sort divides an input into smaller portions, recursively sorts each portion, then combines the sorted results using a merge. This division into subproblems and combination of their solutions is divide and conquer. It does not search and undo candidate choices as backtracking does, and it is not a sequence of locally optimal choices justified by a greedy exchange property. The merge step is linear, leading to the familiar Θ(n log n) recurrence for balanced splits.
How many comparisons asymptotically suffice to merge sorted lists of sizes m and n into one sorted list?
Your answer
Answer & solution
Answer: C: O(m+n) (no official key was published)
Compare the two current front items, emit the smaller and advance that list. Every comparison emits one item, and once one list is exhausted the remaining items can be copied without further comparisons. At most m+n−1 comparisons are therefore needed when both lists are nonempty. Balanced interleavings can attain this bound, giving linear worst-case work. Merely searching in logarithmic time would not output the entire merged list; the standard merge exploits the existing order of both inputs.
For positive integers X,Y, repeatedly replace the larger by its difference from the smaller until X=Y, then print X. What is computed?
Your answer
Answer & solution
Answer: C: gcd of the original integers (no official key was published)
For X>Y, gcd(X,Y)=gcd(X−Y,Y), because the common divisors are unchanged by subtraction. The symmetric identity holds when Y>X. Thus every loop preserves the original gcd. Both variables remain positive, and their sum strictly decreases on each iteration, so the process terminates. At termination X=Y, whose gcd is that common value. The printed result is therefore the original gcd, not their lcm or the quotient of a single division.
Evaluate I more hash entries increase collisions; II recursive programs are efficient; III quicksort worst case O(n²); IV binary search on a linear linked list is efficient.
Your answer
Answer & solution
Answer: D: I and III under the usual fixed-table expected-collision interpretation (no official key was published)
Quicksort can repeatedly split off only one pivot, giving (n−1)+(n−2)+…+1=Θ(n²), so III holds. In a fixed-size table under uniform hashing, adding keys increases expected collision pressure, supporting I in the conventional sense. Recursion alone guarantees no efficiency bound, and a linked list lacks constant-time midpoint access, so II and IV are not general truths. Strictly, a particular inserted key can land in an empty bucket without adding a collision; “increases” in I is an expected trend or nondecreasing count, not a guaranteed strict increase at every insertion.
GET(A,B)=1 if B=0; otherwise GET(A,B)=0 if A<B; otherwise GET(A−1,B)+GET(A−1,B−1). Find GET(3,2).
Answer & solution
Answer: 3 (no official key was published)
Step through it (23 steps)
The base case with B=0 represents the single way to choose no elements. The A<B case represents the impossibility of choosing more elements than are available. The recursive case separates choices according to whether the last element is excluded or included; it is Pascal’s binomial recurrence.
Expand the requested call rather than assuming a closed form: GET(3,2)=GET(2,2)+GET(2,1). The first term is GET(1,2)+GET(1,1)=0+[GET(0,1)+GET(0,0)]=0+0+1=1. The second is GET(1,1)+GET(1,0)=1+1=2. Hence the result is 3, agreeing with the binomial coefficient C(3,2). The ordering of the tests matters at (0,0): B=0 is tested first and returns 1.
Use the usual left-to-right version: compare adjacent entries and swap whenever the left entry exceeds the right. After one full pass, the largest element of the active prefix has bubbled to its final rightmost position. Shorten the active prefix by one for the next pass.
Pass 1: 37,52,12,11,25,92. Pass 2: 37,12,11,25,52,92. Pass 3: 12,11,25,37,52,92. Pass 4: 11,12,25,37,52,92. Pass 5: 11,12,25,37,52,92. For example, in pass 1, 92 is successively swapped with 37,52,12,11,25. In pass 2, 52 moves to the penultimate position. A no-swap early-exit implementation would detect completion on pass 5 in this trace.
The source does not specify pass direction. The equally valid right-to-left version bubbles minima left and gives: [11,92,37,52,12,25], [11,12,92,37,52,25], [11,12,25,92,37,52], [11,12,25,37,92,52], [11,12,25,37,52,92]. Both reach the same sorted list; intermediate pass answers depend on the convention.
The weighted undirected graph has vertices A,B,C,D,E and edges AB=2, AE=3, BC=3, BD=4, CD=4, DE=5. Draw and count all minimum spanning trees. These are the edges visibly present in GFG p8. GateForum p15 omits the AB line while retaining a detached weight 2; also analyze that literal graph.
Answer & solution
Answer: 2 minimum spanning trees, each of weight 12: {AB, AE, BC, BD} and {AB, AE, BC, CD} (no official key was published)
A spanning tree on five vertices has four edges. Graph, AB is the unique cheapest edge crossing the cut {A}, so it belongs to every MST. AE is the unique cheapest edge crossing {E}, and BC is the unique cheapest edge crossing {C}; these too are forced by the cut property. The three edges AB,AE,BC form a tree on A,B,C,E, with D still isolated. Connect D using either BD or CD, each of weight 4. Using DE of weight 5 instead would cost more. Thus the optimum total is 2+3+3+4=12 and there are exactly two choices.
Draw tree1 as E−(3)−A−(2)−B−(3)−C, with an additional B−(4)−D branch. Draw tree2 as the path E−(3)−A−(2)−B−(3)−C−(4)−D. The edge sets in the answer uniquely specify every diagram and show that both graphs are connected and acyclic. Forced edges plus the only two minimum connectors prove completeness, rather than merely exhibiting two examples.
If interpreted literally, A has only neighbor E, and {A,E} connects to the rest only through ED. Consequently AE=3 and ED=5 are forced. In the remaining BCD triangle, choose BC=3 and either BD=4 or CD=4. This gives exactly two spanning trees of minimum weight 15. The count happens to remain 2, but the trees and weights differ.
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.
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 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.
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
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.
Classify Σ(k=1…n)O(n) among O(n),O(n²),O(n³),O(3n²),O(1.5n²).
Select all that apply
Answer & solution
Answer: B,C,D,E under a uniform O(n) bound (no official key was published)
If each summand has magnitude at most Cn with the same constant C, the sum has magnitude at most Cn². Thus it belongs to O(n²),and constant factors 3 or 1.5 do not change that class. O(n³) is also a valid looser upper bound,so C must be selected in a literal multiple-select reading. O(n) is not guaranteed because n terms each equal to n sum to n². The notation needs a uniform bound over k: if hidden constants depend unboundedly on k, such as terms kn, the sum can instead be Θ(n³). Big-O is an upper-bound class,not an assertion of tightness.
For integer A[0..n-1,0..n-1], complete four boxes in: max:=[A]; i:=0; j:=0; while [B] do begin if A[i,j]>max then max:=A[i,j]; if [C] then j:=j+1 else begin j:=0; i:=[D] end end. Use a single loop to find the largest entry. The source's comma/semicolon punctuation is defective; boxes A–D are one coordinated question.
Answer & solution
Answer: A=A[0,0]; B=i<n; C=j<n−1; D=i+1 (n>=1). (no official key was published)
For n>=1 choose box A=A[0,0], B=(i<n), C=(j<n-1), D=i+1. Initializing to the first entry rather than 0 is important: all entries may be negative. The fully punctuated Pascal-style segment is:
begin
max := A[0,0];
i := 0; j := 0;
while i < n do
begin
if A[i,j] > max then max := A[i,j];
if j < n-1 then
j := j+1
else
begin
j := 0;
i := i+1
end
end
end.
The pair (i,j) moves in row-major order: (0,0),(0,1),...,(0,n-1),(1,0),..., (n-1,n-1). At a row's last column, j is reset before proceeding to the next row. After the final element the state becomes (n,0); the guard stops before any invalid A[n,0] access.
Correctness invariant: immediately before processing each cell, max is the maximum of A[0,0] and every previously visited cell. The comparison incorporates the current cell and preserves this property. The rank n*i+j increases by exactly 1 per iteration and begins at 0, so exactly n2 cells are visited. On exit the invariant gives the maximum over the entire array. For n=1 the first entry is compared with itself once and the program exits correctly. Time is Theta(n2), extra space Theta(1). The n=0 case has no maximum and must be rejected or handled outside this segment; the printed task implicitly needs a nonempty array.
The printed procedure loops i=1 to n−1, tests A[i]>A[i+1], swaps adjacent entries if true, and then unconditionally calls bubblesort(n−1). It has no base-case guard and prints temp : A[i] instead of a valid assignment. Let an count executions of the if test. Give a recurrence and solve it.
Answer & solution
Answer: With base case a1=0, an=a(n−1)+n−1, giving n(n−1)/2 comparisons (the printed recurrence has no base case) (no official key was published)
First distinguish the literal source from its conventional intended algorithm. As printed, the procedure has no terminating case and contains a malformed temp assignment. It is not a valid terminating Pascal sort. After correcting assignment punctuation and adding a guard such as "if n<=1 then return", the standard comparison-count question is well-defined.
For the repaired algorithm, one call on n>=2 performs exactly n−1 tests A[i]>A[i+1], irrespective of the data or whether the consequent swap executes. It then calls the procedure once on n−1. Therefore a1=0 and an=a(n−1)+(n−1), n>=2. Equivalently a0=0 may be used with the guard. Repeated substitution gives an=(n−1)+(n−2)+...+1+a1=n(n−1)/2. An induction verifies the closed form: it is 0 at n=1; if a(n−1)=(n−1)(n−2)/2, adding n−1 yields n(n−1)/2. Thus the comparison count and running time are Theta(n2), even for sorted input, because there is no early-exit flag. The swaps, unlike tests, depend on data: zero for sorted input, up to n(n−1)/2 for reverse order with distinct entries.
A complete repaired algorithm is:
procedure bubblesort(A,n):
if n<=1: return
for i=1,...,n-1:
if A[i]>A[i+1]:
temp:=A[i]
A[i]:=A[i+1]
A[i+1]:=temp
bubblesort(A,n-1)
Each pass moves the largest of the first n entries to position n; recursion sorts the preceding prefix. Without the added guard the recursive calls proceed through n=1,0,−1,... (or fail because of the index type/stack), so the printed code does not successfully finish. The finite formula is explicitly for the repaired intended algorithm, not a claim that the literal program terminates.
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.
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.
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.
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.
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.
Pascal enters the loop only if i mod 2=0. While i≥0, it replaces i by i div 2, then subtracts 1 if the new i is odd, otherwise subtracts 2. Give an invariant.
Answer & solution
Answer: i is even at each loop test (no official key was published)
The outer test establishes evenness before the first loop test. Let j be the quotient after the division in an iteration. If j is odd, j−1 is even; if j is even, j−2 is even. Thus either branch reestablishes the invariant regardless of the parity produced by division. Nonnegativity is the loop guard, not an invariant after the body: for i=0 the body produces −2 and terminates. An even negative initial value skips the loop altogether. The invariant states a preserved property, not a complete description of all reachable values.
What minimum number of comparisons suffices to sort five arbitrary distinct keys?
Answer & solution
Answer: 7 in the optimal worst case (no official key was published)
There are 5!=120 possible strict orders, and a binary comparison tree of height six distinguishes at most 64 outcomes. Thus at least seven comparisons are necessary in the worst case. For sufficiency, sort two pairs (two comparisons), compare their larger elements (one), and rename them so a≤b≤d with c≤d. Insert the fifth key into a, b, d in at most two comparisons. Insert c into the prefix preceding d: at most three elements precede d, giving at most four possible positions and two further comparisons. Total: seven. This is a worst-case guarantee; a best-case successful path can be shorter.
fib(0)=fib(1)=1; for n≥2, fib(n)=fib(n−1)+fib(n−2), using ordinary recursive calls. Count all calls evaluating fib(7), including the initial call.
Answer & solution
Answer: 41 (no official key was published)
Step through it (23 steps)
Let C(n) count function invocations. Each base case requires one call, so C(0)=C(1)=1. A nonbase invocation counts itself plus both recursive subtrees: C(n)=1+C(n−1)+C(n−2). Successive values for n=2, …, 7 are 3, 5, 9, 15, 25, 41. This count includes repeated evaluation of identical arguments, as the supplied recursion does not memoize them. It is different from the numeric return value fib(7)=21; counting only leaves or only additions would also answer a different question.
For n vertices and m edges, choices are A O(n²), B O(mn), C O(m+n), D O(m log n), E O(m²). Identify Kruskal’s complexity.
Select all that apply
Answer & solution
Answer: D is the usual informative bound; B, D, E are valid upper bounds for connected simple graphs (no official key was published)
Comparison-sort Kruskal first sorts m edges in O(m log m), then processes them with disjoint-set operations. For a connected simple graph, n−1≤m≤n(n−1)/2, so log m=O(log n), yielding O(m log n). This supports D. Because big-O is an upper bound, the same algorithm is also O(mn) and O(m²), so B and E cannot be called false merely for being looser in a multiple-answer task. O(m+n) is not the generic comparison-sorting bound; O(n²) does not cover the usual sorting cost for dense arbitrary-weight inputs. Different integer-sorting or presorted-edge models can change the analysis.
GFG initializes i=0 and repeats i:=i+1 while i*i≤N, then returns i. Forum instead prints i*i<N. Determine the return for positive N.
Select all that apply
Answer & solution
Answer: B: floor(√N)+1 (no official key was published)
For the non-strict the guard, the loop exits at the smallest integer i whose square exceeds N. That is floor(√N)+1, including a perfect square N=k², which returns k+1. For nonsquares both expressions coincide. For example, N=4 distinguishes 3 from 2. The source change therefore matters and is not a harmless formatting variation. This arithmetic analysis assumes i*i and the increment do not overflow the Pascal integer range.
Give an optimal comparison-based algorithm, with pseudocode and analysis, to sort n numbers containing k distinct values; k is not known in advance.
Answer & solution
Answer: Use a balanced search tree of distinct values and counts, then inorder expansion: O(n log(k+1)) time and O(k) auxiliary space; worst-case optimal in the comparison model. (no official key was published)
Maintain one node per distinct key in a balanced binary search tree, storing a frequency counter. Unlike a simple unbalanced BST, an AVL or red-black tree guarantees height O(log(d+1)) when d distinct values have been encountered. The algorithm discovers k automatically.
SORT_FEW_DISTINCT(A):
T := empty balanced search tree
for x in A:
node := FIND(T,x)
if node exists: node.count := node.count + 1
else: INSERT_BALANCED(T, key=x, count=1)
output := empty sequence
for node in INORDER(T):
repeat node.count times: append node.key to output
return output
After each insertion, the tree contains exactly the distinct input values seen so far, with their correct multiplicities. Inorder traversal visits keys in increasing order, and expanding each count preserves all occurrences. Thus the output is a sorted permutation of the input.
Each of n updates costs O(log(k+1)); inorder traversal costs O(k), and emitting n values costs O(n). Total time is O(n log(k+1)), commonly written O(n log k) for k≥2. The +1 handles k=1, where the algorithm is linear. Auxiliary tree storage is O(k), excluding the n-element output; an array can be overwritten during the final traversal if the input need not be retained.
For worst-case comparison optimality at fixed n and k, consider balanced multiplicities among k ordered values. There are n!/(n1!…nk!) distinguishable orderings, where each ni is approximately n/k. A constant-branching comparison decision tree requires Ω(log(n!/(n1!…nk!)))=Ω(n log k) comparisons in the worst case for k≥2. Reading or writing the input/output also costs Ω(n), giving Ω(n log(k+1)) overall. This is a worst-case statement over multiplicities, not a claim of distribution-sensitive optimality for every frequency pattern. With bounded integer keys, counting/radix methods may bypass the comparison lower bound; without a key-universe assumption they are not a general replacement.