GATE Computer ScienceVery hardGATE CS (PYQ pattern)
int cand = -1, cnt = 0, ch = 0; int a[] = {3,3,4,2,4,4,2,4,3,3,3,1,3,2}; for (int i = 0; i < 14; i++) { if (cnt == 0) { cand = a[i]; cnt = 1; ch++; } else if (a[i] == cand) cnt++; else cnt--; } printf("%d %d %d", cand, cnt, ch); What is printed?
- A. 3 1 4
- B. 4 0 4
- C. 3 0 4
- D. 3 0 5
Correct answer: C. 3 0 4
Trace the pair-cancellation: the candidate changes 4 times, ending with candidate 3 and counter 0. (The candidate is not guaranteed to be a majority.)
Practise more Programming and Data Structures (GATE) questionsProgramming and Data Structures (GATE): notes and key points
More Programming and Data Structures (GATE) questions
- Dutch-national-flag partition on a = [2, 0, 1, 2, 1, 0, 0, 2, 1, 1, 0, 2]: lo = mid = 0, hi = 11; while mid <= hi: if a[mid] == 0 {…
- A heap with 2000 elements is stored in an array (complete binary tree, last level filled left to right). How many elements are in the left…
- How many structurally distinct AVL trees (left and right distinguished, shape only) have exactly 9 nodes?
- A binary tree is serialised in preorder with # for a null child: A B D # # E G # # # C # F # #. What is its inorder traversal and its…
- An undirected simple graph on 100 vertices is stored by keeping only the upper triangle (without the diagonal) of its adjacency matrix as…
- The 4 largest elements of the stream 14, 7, 22, 3, 18, 9, 30, 11, 25, 5, 17, 28, 2, 21 are found with a min-heap of size 4 holding the…