GATE Computer ScienceVery hardGATE CS (PYQ pattern)
void insert(Stack *s, int x) { if (empty(s) || top(s) <= x) { push(s, x); return; } int y = pop(s); insert(s, x); push(s, y); } void sort(Stack *s) { if (!empty(s)) { int x = pop(s); sort(s); insert(s, x); } } The stack holds (bottom to top) 3, 7, 1, 9, 4, 8. How many calls to insert (including recursive ones) are made while sort runs?
- A. 9
- B. 14
- C. 11
- D. 15
Correct answer: C. 11
sort pops from the top (8, 4, 9, 1, 7, 3 in turn) and inserts them back in reverse order into an already-sorted stack. Each insert makes 1 + (number of elements on the stack greater than x) calls; summing over the six insertions gives 11.
Practise more Programming and Data Structures (GATE) questionsProgramming and Data Structures (GATE): notes and key points
More Programming and Data Structures (GATE) questions
- Kahn's topological sort uses a FIFO queue seeded with all vertices of in-degree 0 in increasing order; vertices are dequeued, and…
- An undirected graph has edges 1-2, 2-3, 3-4, 4-5, 5-6, 6-1, 2-7, 7-8, 8-9, 9-7, 4-10, 10-11. Vertices are coloured by the parity of their…
- int range(Node n, int lo, int hi) { if (!n) return 0; int c = (lo <= n->k && n->k <= hi); if (lo < n->k) c += range(n->l, lo, hi); if…
- Keys 50, 30, 70, 20, 40, 60, 80, 10, 25, 35, 45, 55, 65, 75, 85, 5, 22, 33, 38 are inserted in this order into an empty BST, and every…
- bool f(Node n) { if (!n) return true; if (n->l && n->l->k > n->k) return false; if (n->r && n->r->k < n->k) return false; return f(n->l)…
- In the BST obtained by inserting 40, 20, 60, 10, 30, 50, 5, 15, 3, 1, 25, 55, 57, 56 in order, how many nodes have a balance factor…