GATE Data Science & AIGATE DA
Module 6 · Python & DSA

Python and data structures, the way GATE tests them

About 16 of the 85 subject marks come from programming and algorithms, and a growing share is “what does this Python code print?”. Those questions hinge on a few precise behaviours (mutable default arguments, closures, set operations, recursion), so this module teaches you to trace code exactly, then covers the data structures and algorithms in the syllabus.

You need: basic programming familiarity, plus logs and sums from the maths refreshers for the complexity chapter.

The route

    GATE DA’s code questions are short Python snippets with one question: what does this print? They’re won or lost on a handful of exact behaviours: aliasing versus copying, set operations, simultaneous assignment, / versus //, mutable default arguments, closures and recursion. This part teaches you to trace code the way the interpreter does, one line at a time, with a tracer that shows every variable as it changes.

    You need: nothing beyond basic programming familiarity. If you’ve never written Python, read slowly and use the tracer on every example.

    Values, lists, sets and loops: what the interpreter really does

    In Python a variable is a name attached to an object, so two names can point to the same list, and changing it through one name changes what the other sees.

    Code-tracing questions carry 4–7 marks a year and the share is growing. Most mistakes come from a few behaviours (aliasing, set algebra, simultaneous assignment, integer versus float division) that this chapter makes precise.

    It’s like two scorers sharing one scorebook: if one writes in it, the other sees the change, because there’s only one book. Making a photocopy is what A[:] does.

    Where it shows up in GATE DA

    “What does this print?” questions every year, plus list-method questions.

    2025 Q47 · set operations in a loop2025 Q23 · extend vs appendSample Q49 · continue and break2026 Q58 · bubble pass in Python
    Heat: every year, growing (4 → 5 → 7 marks for code tracing)
    TypeExampleMutable?Remember
    int, float7, 3.5no7 / 2 = 3.5 (always float), 7 // 2 = 3, 7 % 2 = 1
    str"six"noindexing and slicing like lists
    list[1, 2, 3]yesordered; append(x) adds one item, extend(L) adds each item of L
    tuple(1, 2)nolike a list you can’t change
    dict{"runs": 45}yeskey → value; k in d checks keys
    set{"a", "b"}yesno duplicates, no order; | union, & intersection, - difference
    1. Aliasing: B = A makes B another name for the same list. A[:] or list(A) makes a copy.
    2. Simultaneous assignment: in A, B = B, A (or A,B,C = A-B, B-C, C-A) the whole right side is evaluated first, using the old values, and only then assigned.
    3. Division: / always gives a float ((15-1)/2 is 7.0); // is integer division.
    4. Slicing a[i:j] includes index i and excludes j; a[::-1] reverses; a[-1] is the last item. range(1, 11) is 1 to 10.
    5. Loops: continue skips to the next iteration; break leaves the loop, and the loop variable keeps its last value.
    Try it

    Step through each program one line at a time. The highlighted line is about to run; the box on the right shows every variable’s current value. In “Aliasing”, watch B change when only B is touched, and C stay separate. Then step through GATE 2025 Q47 and watch the simultaneous assignments use the old values.

    GATE DA 2025 · Q47 · MCQ · 2 marks

    Consider the following Python code snippet.

    A={"this","that"}
    B={"that","other"}
    C={"other","this"}
    while "other" in C:
        if "this" in A:
            A,B,C=A-B,B-C,C-A
        if "that" in B:
            A,B,C=C|A,A|B,B|C

    When the above program is executed, at the end, which of the following sets contains “this”?

    1. Only A
    2. Only B
    3. Only C
    4. A, C
    1. Iteration 1, first if (“this” in A): with the old values, A−B = {this}, B−C = {that}, C−A = {other}. Now A = {this}, B = {that}, C = {other}.

      All three differences use the values from before this line. Updating A first and then using the new A would give a different answer.

    2. Second if (“that” in B, true): C|A = {other, this}, A|B = {this, that}, B|C = {that, other}. Now A = {other, this}, B = {this, that}, C = {that, other}.

      Again, all right-hand sides first.

    3. C still contains “other”, so loop again. First if (“this” in A, true): A−B = {other}, B−C = {this}, C−A = {that}. Second if: “that” in B = {this}? No.

      Check each condition against the current values.

    4. Now C = {that} has no “other”: the loop ends with A = {other}, B = {this}, C = {that}. Only B contains “this”: (B).

      The tracer above shows exactly these states. Official key: (B).

    GATE DA 2025 · Q23 · MCQ · 1 mark

    Consider the following Python declarations of two lists. A=[1,2,3] B=[4,5,6]. Which one of the following statements results in A= [1, 2, 3, 4, 5, 6]?

    1. A.extend(B)
    2. A.append(B)
    3. A.update(B)
    4. A.insert(B)

    One of these adds B as a single item; one isn’t a list method at all.

    extend adds each element of B. append(B) would give [1, 2, 3, [4, 5, 6]]. Lists have no update (that’s for sets and dicts), and insert needs an index and a value. Official key: (A).

    GATE DA 2024 sample paper · Q49 · MCQ · 2 marks

    What is the output of the following python program?

    i=1
    j=1
    for i in range(1, 11):
        if i % 3 != 0:
            j += 2
            continue
        if j % 3 == 0:
            break
    print(i + j)

    Track (i, j). For i not divisible by 3, j grows by 2 and the rest is skipped. At i = 3, 6, 9, check whether j is divisible by 3.

    i = 1, 2: j becomes 3, 5. i = 3: j = 5, not divisible by 3, so no break. i = 4, 5: j becomes 7, 9. i = 6: j = 9 is divisible by 3, so break with i = 6. Output $6 + 9 = 15$. (Sample paper, no official key; verified by running it.)

    With a = [10, 20, 30, 40, 50], what are sum(a[1:4]) and a[::-1][0]?

    a[1:4] is indices 1, 2, 3. a[::-1] is the reversed list.

    a[1:4] = [20, 30, 40], sum 90. Reversed list starts with 50.

    What does this print?

    A = [1, 2, 3]
    B = A
    B.append(4)
    print(A)

    Is B a copy of A, or another name for the same list?

    [1, 2, 3, 4]: B and A are the same list object.

    What does this program print?

    a = [3, 1, 4, 1, 5, 9, 2, 6]
    b = a
    c = a[:]
    b[2:5] = [0]
    c.append(b.pop())
    a += c[-3:]
    print(len(a) + sum(a))

    Decide first which names point to the same list and which hold a copy. Then remember that a slice assignment can change the length of a list, and that += on a list changes it in place.

    b = a makes b a second name for the same list; c = a[:] is a separate copy, [3, 1, 4, 1, 5, 9, 2, 6].

    b[2:5] = [0] replaces the three items at indices 2, 3, 4 (4, 1, 5) by the single item 0, so the shared list becomes [3, 1, 0, 9, 2, 6]. The copy c is untouched.

    b.pop() removes 6 from the shared list, leaving [3, 1, 0, 9, 2], and c.append(6) gives c = [3, 1, 4, 1, 5, 9, 2, 6, 6].

    c[-3:] is [2, 6, 6], and a += … extends the shared list: a = [3, 1, 0, 9, 2, 2, 6, 6].

    Length 8, sum 3 + 1 + 0 + 9 + 2 + 2 + 6 + 6 = 29. The program prints 8 + 29 = 37.

    What does this program print?

    words = ["kern", "heur", "back",
             "kern", "neur", "back",
             "kern"]
    d = {}
    for w in words:
        d[w] = d.get(w, 0) + 1
        if d[w] == 2:
            d[w[::-1]] = d[w]
    print(len(d), sum(d.values()))
    1. 4 7
    2. 6 12
    3. 6 11
    4. Nothing: it stops with a KeyError

    Keep a table of the dictionary after each word. When a count reaches 2, a second key is added: what is its value, and does it change later?

    d.get(w, 0) returns 0 for a new key, so no KeyError can occur.

    Counting: kern → 1, heur → 1, back → 1. The second “kern” makes kern 2, so d["nrek"] = 2. “neur” → 1. The second “back” makes back 2, so d["kcab"] = 2. The third “kern” makes kern 3; the test d[w] == 2 is false, so nothing else happens.

    d["nrek"] received the integer 2 at that moment. Integers are immutable, so it stays 2 when kern later becomes 3.

    Final dictionary: kern 3, heur 1, back 2, nrek 2, neur 1, kcab 2. That is 6 keys with values summing to 11. Answer (C).

    (A) ignores the reversed keys; (B) assumes nrek follows kern up to 3.

    Consider the following code.

    R = [[0] * 3] * 3
    S = [[0] * 3 for _ in range(3)]
    R[0][1] = 5
    S[0][1] = 5
    T = R[:]
    T[2] = [7, 7, 7]
    T[1][0] = 1

    After it runs, which of the following is/are correct?

    1. sum(map(sum, R)) is 18
    2. sum(map(sum, S)) is 15
    3. T[2] is [7, 7, 7] while R[2] is [1, 5, 0]
    4. R[0][0] is still 0, because T[1][0] = 1 changes only the copy T

    [row] * 3 repeats a reference to one inner list. R[:] copies the outer list only. For each line, ask whether it rebinds a slot of an outer list or changes an inner list.

    R holds the same inner list three times. S builds three separate inner lists.

    R[0][1] = 5 changes the one shared inner list, so every row of R reads [0, 5, 0]. S[0][1] = 5 changes only S’s first row.

    T = R[:] is a new outer list whose three slots point to the same shared inner list. T[2] = [7, 7, 7] rebinds T’s third slot only; R is not affected.

    T[1][0] = 1 goes through T’s second slot to the shared inner list, which becomes [1, 5, 0]. All three rows of R see it.

    (A) True: R is three rows of [1, 5, 0], sum 3 × 6 = 18. (B) False: S’s sum is 5, since only one row changed. (C) True. (D) False: the copy was shallow, so R[0][0] is 1.

    Correct: A, C.

    • Keep a small table of variable values and update it line by line.
    • For simultaneous assignment, compute every right-hand side with the old values first.
    • Note when / produces a float; it can change what gets printed.
    • Treating B = A as a copy.
    • Confusing append (adds one item) with extend (adds many).
    • Forgetting that range(a, b) stops at b − 1.
    1. Names point to objects: B = A aliases the list, while A[:] copies it. Lists, dicts and sets are mutable.
    2. In A, B = X, Y the right side is evaluated fully before assigning. Sets use |, & and −.
    3. / gives a float and // an integer; slices exclude the end index; continue skips and break exits.

    After a, b = 3, 5 then a, b = b, a + b, the values are

    a = 5, b = 10
    That uses the new a in a + b. The right side uses the old values.
    a = 5, b = 8
    Right side first: (5, 3 + 5).
    a = 3, b = 8
    a is assigned the old b, 5.

    {1, 2, 3} - {2, 3, 4} is

    {4}
    That’s the second set minus the first.
    {1}
    Elements of the first set that aren’t in the second.
    {1, 4}
    That’s the symmetric difference ^.

    print((15 - 1) / 2) prints

    7
    / always gives a float.
    7.0
    True division returns a float even when the result is whole. (This matters in 2025 Q63.)
    7.5
    14 / 2 is exactly 7.

    Functions, scope and recursion: the questions GATE loves to trick

    A default argument is created once, when the function is defined; an inner function remembers the variables of the call that created it; and a recursive function’s work is a tree of calls you can count.

    2026 alone had three questions on exactly these behaviours (Q16, Q39, Q50), and recursion-tracing questions appear every year.

    It’s like a team kit bag handed down season after season: if one player leaves a bat in the shared default bag, the next player finds it there. Bring your own bag (pass an argument) and you start empty.

    Where it shows up in GATE DA

    Every year: tracing function calls, closures, default arguments and recursive call counts.

    2026 Q16 · mutable default argument2026 Q50 · closures2026 Q39 · counting recursive calls2025 Q63 · recursion with /2024 Q38 · counting tree nodes2024 Q41 · recursive reverse
    Heat: every year, 2–6 marks
    • Arguments are passed as references to objects. If a function mutates a list argument (lst.append), the caller sees the change. If it rebinds the name (lst = [...]), the caller doesn’t.
    • Default values are evaluated once, when the def runs. A mutable default (lst=[]) is therefore shared by every call that doesn’t pass its own list.
    • Closures: an inner function can use variables of the enclosing function. Each call of the outer function creates fresh variables, so two closures from two calls don’t share them.
    • Recursion: each call gets its own frame on the call stack with its own local variables. It returns to the caller when done.
    Try it

    Step through each program. In “2026 Q16”, watch lst already contain 1 when the second call starts. In “2026 Q50”, notice that f1 and f2 each carry their own x. In the recursive ones, watch the call stack grow and shrink, and read each “returning” value.

    GATE DA 2026 · Q16 · MCQ · 1 mark

    Consider the given Python program.

    def append_to_lst(val, lst=[]):
        lst.append(val)
        return lst
    print(append_to_lst(1))
    print(append_to_lst(2))
    print(append_to_lst(3, []))

    Which of the following is the correct output of this program?

    1. [1] [2] [3]
    2. [1] [1, 2] [3]
    3. [1] [2] [1, 2, 3]
    4. [1] [1, 2] [1, 3]
    1. When def runs, Python creates one empty list and stores it as the default for lst.

      Defaults are evaluated once, at definition time, not on each call.

    2. Call 1 uses the default list: it becomes [1], which is printed. Call 2 uses the same default list, now [1]; it becomes [1, 2], which is printed.

      The default object persists between calls because it’s mutable and shared.

    3. Call 3 passes a brand-new empty list, so it prints [3], and the default list is untouched. Output (B).

      Official key: (B). (The usual fix is lst=None, then if lst is None: lst = [] inside.)

    Try it

    GATE 2026 Q39 asks how many calls mystery(4) makes, where mystery(n) calls mystery(n-1) and mystery(n-2) until $n \le 0$. Each dot is one call; orange dots are base cases. Change $n$ and watch the count grow almost as fast as the Fibonacci numbers.

    GATE DA 2026 · Q50 · MSQ · 2 marks

    Consider the given Python program.

    def outer():
        x = []
        def inner(val):
            x.append(val)
            return x
        return inner
    f1 = outer()
    f2 = outer()
    print(f1(10)) # Line P
    print(f1(20)) # Line Q
    print(f2(30)) # Line R
    print(f1(40)) # Line S

    Which of the following options is/are correct?

    1. f1 and f2 share the same list x
    2. Output of Line Q is [10, 20]
    3. Output of Line R is [10, 20, 30]
    4. Output of Line S is [10, 20, 40]

    Each call to outer() runs x = [] afresh. Which list does each closure hold?

    f1 and f2 come from separate calls, so each has its own x: (A) ✗. f1’s list: [10], then [10, 20] at Line Q ✓, then [10, 20, 40] at Line S ✓. f2’s list is [30] at Line R ✗. Official key: B; D.

    GATE DA 2026 · Q39 · MCQ · 2 marks

    A recursive function in Python is given.

    def mystery(n):
        if n <= 0:
            return 1
        else:
            return mystery(n-1) + mystery(n-2)

    Now, consider the following function call: mystery(4). Assume that a typical runtime stack is used to manage function calls. Each function call is pushed onto the stack and removed only after it finishes execution. Which of the following options denotes the total number of function calls (i.e., the total number of stack activations), including the initial call, to compute mystery(4)?

    Let T(n) be the number of calls. T(n) = 1 + T(n−1) + T(n−2) for n > 0, and T(0) = T(−1) = 1.

    T(0) = T(−1) = 1; T(1) = 1 + 1 + 1 = 3; T(2) = 1 + 3 + 1 = 5; T(3) = 1 + 5 + 3 = 9; T(4) = 1 + 9 + 5 = 15. Official key: (C) 15.

    GATE DA 2025 · Q63 · NAT · 2 marks

    Consider the following Python code snippet.

    def f(a,b):
        if (a==0):
            return b
        if (a%2==1):
            return 2*f((a-1)/2,b)
        return b+f(a-1,b)
    print(f(15,10))

    The value printed by the code snippet is ______ (Answer in integer)

    Unwind: f(15) = 2·f(7.0), f(7.0) = 2·f(3.0), f(3.0) = 2·f(1.0), f(1.0) = 2·f(0.0). Note that 7.0 % 2 == 1 is still true for floats.

    f(0.0, 10) = 10, so f(1.0) = 20, f(3.0) = 40, f(7.0) = 80, f(15) = 160. The / makes the arguments floats, but the arithmetic is unaffected, and the final value is the integer 2·80 = 160. Official key: 160.

    GATE DA 2024 · Q38 · MCQ · 2 marks

    Consider the following Python code:

    def count(child_dict, i):
        if i not in child_dict.keys():
            return 1
        ans = 1
        for j in child_dict[i]:
            ans += count(child_dict, j)
        return ans
    child_dict = dict()
    child_dict[0] = [1,2]
    child_dict[1] = [3,4,5]
    child_dict[2] = [6,7,8]
    print(count(child_dict,0))

    Which ONE of the following is the output of this code?

    child_dict describes a tree: 0 has children 1, 2; 1 has 3, 4, 5; 2 has 6, 7, 8. What does count add up?

    count returns 1 for a leaf and 1 + (sum over children) otherwise: it counts nodes in the subtree. Nodes 0–8: 9. Official key: (D) 9.

    What does this program print?

    def collect(n, acc=[]):
        if n == 0:
            return acc
        acc.append(n)
        return collect(n - 1, acc)
    
    x = collect(3)
    y = collect(2)
    z = collect(2, [])
    print(len(x) + len(y) + len(z))

    The recursive calls pass acc along explicitly, but the first call of each top-level line may not. Which list does each of x, y and z name when the last line runs?

    The default list is created once, when def runs. Call it D.

    collect(3) uses D and passes D down the recursion: D becomes [3, 2, 1], and x names D.

    collect(2) also uses D, which now becomes [3, 2, 1, 2, 1]; y names D too, so x and y are the same list.

    collect(2, []) uses a fresh list: z = [2, 1].

    When the print runs, len(x) = len(y) = 5 and len(z) = 2: total 12. (Treating every call as fresh gives 7; taking a snapshot of x after the first call gives 10.)

    What does this program print?

    fs = [lambda x: x + i for i in range(3)]
    print(sum(f(10) for f in fs))
    1. 30
    2. 33
    3. 36
    4. Nothing: it stops with a NameError, because i no longer exists

    A lambda’s body runs only when the lambda is called. At that moment, which value of i does it find?

    Each lambda is a closure over the comprehension’s variable i. It does not copy the value of i when it is created; it looks i up when it is called.

    The three lambdas are called only in the last line, after the comprehension has finished with i = 2. The variable still exists for them, because the closures keep it alive, so there is no NameError.

    Each call returns 10 + 2 = 12, and the sum is 3 × 12 = 36. Answer (C).

    (B) 33 = 10 + 11 + 12 is what you get if each lambda fixes its own i, for example with lambda x, i=i: x + i: a default value is evaluated when the lambda is created.

    What are the two values this program prints?

    calls = 0
    
    def g(n):
        global calls
        calls += 1
        if n <= 1:
            return n
        return g(n // 2) + g(n // 3)
    
    v = g(12)
    print(v, calls)

    Work bottom-up. Find g(0), g(1), g(2), g(3), g(4) and g(6) first, and alongside each one the number of calls it makes, including itself.

    Values: g(0) = 0 and g(1) = 1. Then g(2) = g(1) + g(0) = 1, g(3) = g(1) + g(1) = 2, g(4) = g(2) + g(1) = 2, g(6) = g(3) + g(2) = 3, and g(12) = g(6) + g(4) = 5.

    Calls: let C(n) be the number of calls made by g(n), itself included. C(0) = C(1) = 1 and C(n) = 1 + C(n // 2) + C(n // 3).

    C(2) = 1 + 1 + 1 = 3, C(3) = 1 + 1 + 1 = 3, C(4) = 1 + C(2) + C(1) = 5, C(6) = 1 + C(3) + C(2) = 7, C(12) = 1 + C(6) + C(4) = 13.

    The program prints 5 13.

    • Write each recursive call as a node in a tree and fill in return values bottom-up.
    • For call counts, set up the recurrence T(n) = 1 + (calls made by the children).
    • Ask “when was this object created?” for every default argument and closure variable.
    • Assuming a default list starts empty on every call.
    • Assuming two closures from separate calls share variables.
    • Forgetting the initial call when counting calls.
    1. Default arguments are created once at definition time: a mutable default is shared across calls.
    2. Each call of an outer function creates fresh local variables, so closures from different calls don’t share them.
    3. Recursion forms a call tree; count calls with T(n) = 1 + Σ T(children) and evaluate return values from the leaves up.

    GATE 2024 Q41: fun(D, s1, s2) swaps D[s1] and D[s2], then calls fun(D, s1+1, s2-1) while s1 < s2. It

    finds the smallest element between s1 and s2
    It never compares values.
    swaps only the two ends
    The recursive call keeps going inward.
    reverses D between indices s1 and s2
    Swap the ends, move inward, repeat. Official key: (C).

    A function receives a list L and runs L = L + [99]. In the caller, the original list

    gains 99
    L + [99] builds a new list, and L = just rebinds the local name.
    is unchanged
    Rebinding a parameter doesn’t affect the caller’s object. (L.append(99) would.)
    raises an error
    It’s valid Python.

    Using T(n) = 1 + T(n−1) + T(n−2) with T(0) = T(−1) = 1, the number of calls made by mystery(5) is

    17
    T(5) = 1 + T(4) + T(3).
    25
    1 + 15 + 9.
    31
    Recheck: T(4) = 15 and T(3) = 9.

    After x = [1, 2]; y = x[:]; y.append(3), what is x?

    [1, 2]
    x[:] made a copy, so y is a separate list.
    [1, 2, 3]
    That would happen with y = x.

    A function with a default d={} adds a key on each call (without passing d). After three calls, the default dict holds

    one key
    The same dict object is reused across calls.
    three keys
    Mutable defaults accumulate.
    no keys
    Mutations to the default persist.

    sum(range(1, 5)) // 3 evaluates to

    3.33
    // is integer division.
    3
    1 + 2 + 3 + 4 = 10, and 10 // 3 = 3.
    5
    range(1, 5) stops at 4.

    How fast is an algorithm, and how do you count its steps exactly? This part covers Big-O and recurrences, binary search (with exact comparison counts), the three simple sorts GATE loves to trace pass by pass, and the two divide-and-conquer sorts. Sorting and searching questions appear in every DA paper, usually as “how many swaps / comparisons / passes”.

    You need: Part 1 (tracing code), and logs and sums (Refreshers Parts 1–2).

    Complexity and binary search: counting steps that matter

    Big-O describes how an algorithm’s work grows with the input size, and binary search shows the power of halving: about $\log_2 n$ steps instead of $n$.

    Binary search has appeared in every DA paper (2024 Q40, 2025 Q27, 2026 Q31), and recurrence questions accompany the sorting algorithms.

    It’s like finding a name in a printed phone book: open the middle, decide which half, repeat. A thousand pages take only about ten looks.

    Where it shows up in GATE DA

    Binary search counts and recurrences every year; complexity facts in sorting questions.

    2026 Q31 · max comparisons, n = 10002024 Q40 · binary search recurrence2025 Q27 · when is binary search O(log n)?2026 Q15 · quicksort recurrence
    Heat: every year, 1–2 marks

    $f(n) = O(g(n))$ means $f$ grows no faster than a constant multiple of $g$ for large $n$ (an upper bound). $\Theta(g(n))$ means it grows at exactly that rate (upper and lower bound). Constants and lower-order terms are dropped: $3n^2 + 10n + 7 = \Theta(n^2)$. Growth order: $1 \lt \log n \lt n \lt n\log n \lt n^2 \lt n^3 \lt 2^n \lt n!$.

    RecurrenceSolutionTypical algorithm
    $T(n) = T(n/2) + c$$\Theta(\log n)$binary search
    $T(n) = 2T(n/2) + cn$$\Theta(n\log n)$merge sort, balanced quicksort
    $T(n) = T(n-1) + cn$$\Theta(n^2)$quicksort worst case, selection sort
    $T(n) = T(n-1) + c$$\Theta(n)$linear recursion over a list
    $T(n) = 2T(n-1) + c$$\Theta(2^n)$naive branching recursion

    Compare $y$ with the middle element. If equal, done; if smaller, search the left half; if larger, the right half. Each comparison removes about half. Needs: sorted data and constant-time access to the middle (an array, not a linked list).

    Worst case: $F(n) = F(\lfloor n/2\rfloor) + 1$ comparisons, which gives $\lfloor\log_2 n\rfloor + 1$ (counting each 3-way comparison once).

    Try it

    Choose the array size and a target (including a value not in the array). Step through binary search: the shaded window is what’s still possible, and each step halves it. Compare the comparison count with $\lfloor\log_2 n\rfloor + 1$.

    GATE DA 2026 · Q31 · NAT · 1 mark

    Let A be a sorted array containing 1000 distinct integers. You perform a recursive binary search on A to find an element y. Suppose each comparison checks whether the middle element computed during the current recursive step is equal to, less than, or greater than y. The maximum number of comparisons that may have to be performed if y is not an element of A is ______. (Answer in integer)

    1. Each step does one (3-way) comparison and leaves at most $\lfloor n/2\rfloor$ elements: $1000 \to 500 \to 250 \to 125 \to 62 \to 31 \to 15 \to 7 \to 3 \to 1 \to 0$.

      After comparing with the middle, the larger remaining half has $\lfloor n/2\rfloor$ elements.

    2. Count the steps that had a non-empty array to compare: 1000, 500, 250, 125, 62, 31, 15, 7, 3, 1, so 10 comparisons.

      This equals $\lfloor\log_2 1000\rfloor + 1 = 9 + 1 = 10$ (since $2^9 = 512 \le 1000 \lt 1024$).

    3. A failed search always goes all the way down, so this worst case is reached.

      Official key: 10.

    GATE DA 2024 · Q40 · MCQ · 2 marks

    Let $F(n)$ denote the maximum number of comparisons made while searching for an entry in a sorted array of size $n$ using binary search. Which ONE of the following options is TRUE?

    1. $F(n) = F(\lfloor n/2\rfloor) + 1$
    2. $F(n) = F(\lfloor n/2\rfloor) + F(\lceil n/2\rceil)$
    3. $F(n) = F(\lfloor n/2\rfloor)$
    4. $F(n) = F(n - 1) + 1$

    One comparison, then you continue in only one half.

    One comparison plus the worst case of the remaining half: (A). (B) searches both halves; (D) is linear search. Official key: (A).

    GATE DA 2025 · Q27 · MSQ · 1 mark

    For which of the following inputs does binary search take time $O(\log n)$ in the worst case?

    1. An array of $n$ integers in any order
    2. A linked list of $n$ integers in any order
    3. An array of $n$ integers in increasing order
    4. A linked list of $n$ integers in increasing order

    Two requirements: sorted, and jumping to the middle in O(1).

    Only (C). Unsorted data breaks the halving logic; a linked list needs O(n) just to reach the middle. Official key: C.

    How many times does the inner line run?

    n = 10
    for i in range(n):
        for j in range(i):
            work()

    For each i the inner loop runs i times: 0 + 1 + … + 9.

    $0 + 1 + \cdots + 9 = 45 = n(n-1)/2$: $\Theta(n^2)$.

    Solve $T(n) = 2T(n/2) + n$.

    About $\log_2 n$ levels of recursion, each doing $n$ total work.

    $\Theta(n\log n)$, the merge sort recurrence.

    The key 50 is not in the list. What are the two values printed?

    A = [4, 9, 13, 18, 22, 27, 31, 36,
         40, 45, 51, 58, 63, 70, 77]
    key = 50
    lo, hi, steps = 0, len(A) - 1, 0
    while lo <= hi:
        mid = (lo + hi) // 2
        steps += 1
        if A[mid] == key:
            break
        elif A[mid] < key:
            lo = mid + 1
        else:
            hi = mid - 1
    print(steps, lo)

    List the (lo, hi, mid) triples one iteration at a time. The loop stops when lo passes hi.

    Iteration 1: lo = 0, hi = 14, mid = 7, A[7] = 36 < 50, so lo = 8.

    Iteration 2: mid = (8 + 14) // 2 = 11, A[11] = 58 > 50, so hi = 10.

    Iteration 3: mid = (8 + 10) // 2 = 9, A[9] = 45 < 50, so lo = 10.

    Iteration 4: mid = 10, A[10] = 51 > 50, so hi = 9. Now lo > hi and the loop ends.

    It prints 4 10: 4 steps, and lo = 10, the index where 50 would be inserted to keep the list sorted. A list of 15 needs at most ⌊log₂ 15⌋ + 1 = 4 steps, so this search used the worst case.

    Consider the function below, where n ≥ 2 is an integer.

    def count(n):
        c = 0
        i = 1
        while i < n:
            j = n
            while j > i:
                c += 1
                j -= 2
            i *= 2
        return c

    Which of the following is/are correct?

    1. count(16) returns 25
    2. When n = 2k, the outer loop runs k + 1 times
    3. count(n) grows as Θ(n log n)
    4. count(n) grows as Θ(n), because i doubles and 1 + 2 + 4 + ⋯ stays below 2n

    Which values does i take? For one fixed i, how many times does the inner loop run? Then add.

    i takes the values 1, 2, 4, …, as long as i < n. For n = 2k these are 20, …, 2k−1: k values, not k + 1, so (B) is false.

    For a fixed i, j goes n, n − 2, n − 4, … while j > i, so the inner loop runs ⌈(n − i)/2⌉ times.

    n = 16: i = 1, 2, 4, 8 give 8 + 7 + 6 + 4 = 25. (A) is true.

    Each of the about log₂ n outer iterations has i ≤ n/2, so its inner loop runs at least n/4 and at most n/2 times. The total lies between (n/4)log₂ n and (n/2)log₂ n, which is Θ(n log n). (C) is true and (D) is false: the doubling makes the outer loop short, but the inner loop does not shrink with i the way a geometric sum would need.

    Correct: A, C.

    What does this program print?

    ops = 0
    
    def work(n):
        global ops
        if n <= 1:
            ops += 1
            return
        work(n // 2)
        work(n // 2)
        for _ in range(n):
            ops += 1
    
    work(32)
    print(ops)

    Let T(n) be the value work(n) adds to ops. Write a recurrence for T(n) from the code, with its base case, and unroll it from n = 1 upwards.

    A call with n ≤ 1 adds 1. A call with n ≥ 2 makes two calls on n // 2 and then adds n. So T(1) = 1 and T(n) = 2T(n/2) + n for powers of 2.

    T(2) = 2·1 + 2 = 4, T(4) = 2·4 + 4 = 12, T(8) = 2·12 + 8 = 32, T(16) = 2·32 + 16 = 80, T(32) = 2·80 + 32 = 192.

    Check with the closed form: each of the log₂ 32 = 5 levels adds 32, and the 32 leaves add 1 each, so T(32) = 32·5 + 32 = 192.

    The program prints 192. (Forgetting the leaves gives 160.)

    • Count the dominant operation (comparisons, swaps) exactly when asked; use Big-O otherwise.
    • For binary search worst case, repeatedly halve with floor and count the non-empty steps.
    • Match recurrences to the table instead of re-deriving them.
    • Using binary search on unsorted data or linked lists and expecting O(log n).
    • Off-by-one errors: for n = 1000 it’s 10 comparisons, not 9.
    • Keeping constants in Big-O: O(2n) is O(n).
    1. Big-O ignores constants and lower-order terms; know the growth order up to 2ⁿ and n!.
    2. Recurrences: T(n/2) + c → log n; 2T(n/2) + n → n log n; T(n−1) + n → n²; 2T(n−1) + c → 2ⁿ.
    3. Binary search needs a sorted array; worst case F(n) = F(⌊n/2⌋) + 1 = ⌊log₂ n⌋ + 1 comparisons.

    Which grows fastest?

    $n^3$
    Polynomials lose to exponentials eventually.
    $2^n$
    Exponential beats any polynomial.
    $n\log n$
    Between n and n².

    Binary search on a sorted array of 1 million elements needs at most about

    1000 comparisons
    That’s √n. Binary search is logarithmic.
    20 comparisons
    $2^{20} \approx 10^6$.
    500,000 comparisons
    That’s half the array, like linear search.

    $5n^2 + 100n\log n + 3$ is

    $\Theta(n\log n)$
    For large n, the n² term dominates.
    $\Theta(n^2)$
    Keep the fastest-growing term, drop its constant.
    $\Theta(5n^2)$
    Constants are dropped.

    Bubble, selection and insertion sort: counting passes, swaps and comparisons

    The three simple sorts differ in what one pass guarantees: bubble sort floats the largest to the end, selection sort brings the smallest to the front, insertion sort grows a sorted prefix by one.

    GATE asks for exact passes, swaps or comparisons every year (2024 Q45, 2025 Q29, 2026 Q49 and Q58). Knowing each sort’s invariant answers them in seconds.

    It’s like arranging batters by average: bubble swaps neighbours who are out of order; selection picks the best remaining batter for the next slot; insertion takes each new batter and slots them into the already-ordered list.

    Where it shows up in GATE DA

    Pass-by-pass traces, swap counts and comparison counts every year.

    2024 Q45 · sorted after two passes?2025 Q29 · insertion sort with two swaps2026 Q49 · comparisons: bubble vs insertion2026 Q58 · bubble passes in PythonSample Q21 · worst-case times
    Heat: every year, 2–4 marks
    SortOne pass guaranteesSwapsComparisonsBest / worst
    Bubblethe largest remaining element reaches the end= number of inversions$n(n-1)/2$ (plain version)$O(n)$ with early exit / $O(n^2)$
    Selectionthe smallest remaining element is placed at the frontat most $n - 1$always $n(n-1)/2$$O(n^2)$ / $O(n^2)$
    Insertionthe first $k+1$ elements are sorted (among themselves)= number of inversionsinversions + (up to) $n - 1$$O(n)$ / $O(n^2)$

    An inversion is a pair of positions $i \lt j$ with $a_i \gt a_j$. Every adjacent swap in bubble or insertion sort fixes exactly one inversion, so both make exactly as many swaps as there are inversions. For [5, 3, 4, 1, 2]: 5 beats 4 later elements, 3 beats 2, 4 beats 2, 1 beats 0, so 8 inversions and 8 swaps (2026 Q58).

    Try it

    Pick a sort and an array, then step one pass at a time (or one comparison at a time). Watch the invariant: bubble sort’s sorted tail grows from the right, selection’s sorted head from the left, insertion’s sorted prefix absorbs one new element per pass. The counters track comparisons and swaps; compare swaps with the inversion count.

    GATE DA 2024 · Q45 · MCQ · 2 marks

    Consider the following sorting algorithms: (i) Bubble sort (ii) Insertion sort (iii) Selection sort. Which ONE among the following choices of sorting algorithms sorts the numbers in the array [4, 3, 2, 1, 5] in increasing order after exactly two passes over the array?

    1. (i) only
    2. (iii) only
    3. (i) and (iii) only
    4. (ii) and (iii) only
    1. Bubble: pass 1 → [3, 2, 1, 4, 5]; pass 2 → [2, 1, 3, 4, 5]. Not sorted.

      Each pass only guarantees the next-largest element reaches its place.

    2. Insertion: after inserting 3 → [3, 4, 2, 1, 5]; after inserting 2 → [2, 3, 4, 1, 5]. Not sorted.

      Two passes only sort the first three elements.

    3. Selection: pass 1 swaps 1 to the front → [1, 3, 2, 4, 5]; pass 2 swaps 2 into place → [1, 2, 3, 4, 5]. Sorted. Answer (B).

      This array happens to need only two “minimum to the front” moves. Official key: (B).

    GATE DA 2025 · Q29 · MSQ · 1 mark

    Suppose that insertion sort is applied to the array [1, 3, 5, 7, 9, 11, x, 15, 13] and it takes exactly two swaps to sort the array. Select all possible values of x.

    1. 10
    2. 12
    3. 14
    4. 16

    Swaps = inversions. The pair (15, 13) is always one inversion. So x must create exactly one more.

    x = 10: inversion with 11 (+1) → total 2 ✓. x = 12: no inversions with earlier elements, none with later ones (12 < 13, 15) → total 1 ✗. x = 14: inversion with 13 (+1) → 2 ✓. x = 16: inversions with 15 and 13 (+2) → 3 ✗. Official key: A; C.

    GATE DA 2026 · Q49 · MSQ · 2 marks

    Consider the problem of sorting the given array in ascending order: P = [1, 2, 3, 5, 4]. Consider two sorting algorithms Bubble Sort (BS) and Insertion Sort (IS). Let N1 be the total number of comparisons done by BS on the elements of P and N2 be the total number of comparisons done by IS on the elements of P. Which of the following options is/are correct?

    1. N1 = 10, N2 = 4
    2. N1 > N2
    3. IS on P will perform only one swap
    4. Both BS and IS on P will make at least one unnecessary comparison (i.e., comparing elements that are already in correct order)

    One inversion (5, 4). Insertion sort compares each new element with its left neighbour(s): count carefully for inserting 4.

    Insertion: inserting 2, 3, 5 takes 1 comparison each (already in place); inserting 4 compares with 5 (swap) then with 3 (stop): 2 comparisons. N2 = 5, so (A) ✗. Bubble makes 10 comparisons (7 even with an early-exit check), so N1 > N2 (B) ✓. One inversion, one swap (C) ✓. Both compare already-ordered pairs like (1, 2) (D) ✓. Official key: B; C; D.

    GATE DA 2026 · Q58 · NAT · 2 marks

    Consider the given Python program.

    def fun(L, i=0):
        if i >= len(L)-1:
            return 0
        if L[i] > L[i+1]:
            L[i+1], L[i] = L[i], L[i+1]
            return 1+fun(L, i+1)
        else:
            return fun(L, i+1)
    data = [5, 3, 4, 1, 2]
    count = 0
    for _ in range(len(data)):
        count += fun(data)
    print(count)

    The output of the program is ______. (Answer in integer)

    fun is one bubble-sort pass that returns its swap count. Five passes fully sort the list. Total swaps = ?

    Bubble sort’s total swaps equal the inversions of [5, 3, 4, 1, 2]: 4 + 2 + 2 + 0 = 8. Official key: 8.

    How many comparisons does selection sort make on any array of 5 elements?

    Pass 1 compares 4 times, pass 2 three times, …

    $4 + 3 + 2 + 1 = 10$, regardless of the input order.

    This insertion sort counts every comparison A[j] > key. What does it print?

    A = [7, 3, 9, 1, 8, 2]
    comps = 0
    for i in range(1, len(A)):
        key = A[i]
        j = i - 1
        while j >= 0:
            comps += 1
            if A[j] > key:
                A[j + 1] = A[j]
                j -= 1
            else:
                break
        A[j + 1] = key
    print(comps)

    Each shift costs one comparison. An element that stops before reaching the front costs one extra comparison: the one that told it to stop.

    i = 1, key 3: compare with 7 (shift); j reaches −1. 1 comparison. Array [3, 7, 9, 1, 8, 2].

    i = 2, key 9: compare with 7, stop. 1 comparison.

    i = 3, key 1: compare with 9, 7, 3 (three shifts), j reaches −1. 3 comparisons. Array [1, 3, 7, 9, 8, 2].

    i = 4, key 8: compare with 9 (shift), then 7, stop. 2 comparisons. Array [1, 3, 7, 8, 9, 2].

    i = 5, key 2: compare with 9, 8, 7, 3 (four shifts), then 1, stop. 5 comparisons.

    Total 1 + 1 + 3 + 2 + 5 = 12. Equivalently: 9 inversions (one per shift) plus 3 stopping comparisons, for the keys that did not reach the front.

    The loop below runs only the first three passes of selection sort. What does it print?

    A = [5, 2, 8, 2, 9, 1, 6]
    swaps = 0
    for i in range(3):
        m = i
        for j in range(i + 1, len(A)):
            if A[j] < A[m]:
                m = j
        if m != i:
            A[i], A[m] = A[m], A[i]
            swaps += 1
    print(A, swaps)
    1. [1, 2, 2, 8, 9, 5, 6] 2
    2. [1, 2, 2, 8, 9, 5, 6] 3
    3. [1, 2, 2, 5, 9, 8, 6] 3
    4. [1, 2, 8, 2, 9, 5, 6] 1

    range(3) gives i = 0, 1, 2. In each pass, note which index ends up in m. A swap is counted only when m differs from i.

    Pass i = 0: the minimum of the whole list is 1 at index 5. Swap with index 0: [1, 2, 8, 2, 9, 5, 6], swaps = 1.

    Pass i = 1: A[1] = 2. The test is a strict <, so the other 2 at index 3 does not replace it and m stays 1. No swap.

    Pass i = 2: the minimum of [8, 2, 9, 5, 6] is 2 at index 3. Swap: [1, 2, 2, 8, 9, 5, 6], swaps = 2.

    It prints [1, 2, 2, 8, 9, 5, 6] 2: (A).

    (B) counts a swap in pass 1 as well (as with <= or an unconditional swap), (C) runs four passes, and (D) stops after two.

    Bubble sort with an early exit returns its numbers of comparisons and swaps.

    def bubble(A):
        comps = swaps = 0
        n = len(A)
        for p in range(n - 1):
            swapped = False
            for j in range(n - 1 - p):
                comps += 1
                if A[j] > A[j + 1]:
                    A[j], A[j + 1] = A[j + 1], A[j]
                    swaps += 1
                    swapped = True
            if not swapped:
                break
        return comps, swaps
    
    P = [2, 3, 4, 5, 6, 1]
    Q = [6, 1, 2, 3, 4, 5]

    Which of the following is/are correct?

    1. bubble(P) returns (15, 5)
    2. bubble(Q) returns (5, 5), since one pass carries 6 to the end and leaves Q sorted
    3. bubble(P) and bubble(Q) make the same number of swaps
    4. On Q, insertion sort (counting each A[j] > key test, as in the first question of this set) makes fewer comparisons than bubble(Q)

    A pass moves a large element far to the right but a small element only one place to the left. And the early exit needs a pass with no swaps before it stops.

    P: the 1 at the end moves one place left per pass, so passes 1 to 5 each make one swap. Comparisons 5 + 4 + 3 + 2 + 1 = 15. The loop ends because p has run out, with no extra pass. (15, 5): (A) true.

    Q: pass 1 carries 6 to the end with 5 swaps and 5 comparisons, and Q is sorted. But the code only knows that after pass 2 (4 comparisons, no swaps) triggers the break. (9, 5): (B) false.

    Both make 5 swaps, one per inversion (each list has 5 inversions): (C) true.

    Insertion sort on Q: key 1 makes 1 comparison and reaches the front; keys 2, 3, 4, 5 each make 2 (shift 6, stop). Total 1 + 4·2 = 9, the same as bubble’s 9: (D) false.

    Correct: A, C.

    • Count inversions for swap questions about bubble and insertion sort.
    • Use each sort’s pass invariant to predict the array after k passes.
    • Clarify whether a comparison count includes the extra “stop” comparison in insertion sort.
    • Assuming selection sort’s swap count depends on inversions. It’s at most n − 1.
    • Forgetting that plain bubble sort keeps comparing even when the array is already sorted.
    • Confusing “pass” across the three sorts; define it as the algorithm does.
    1. Bubble: largest to the end each pass. Selection: smallest to the front. Insertion: sorted prefix grows by one.
    2. Bubble and insertion sort make exactly (number of inversions) swaps; selection makes at most n − 1.
    3. Selection always does n(n−1)/2 comparisons; insertion is O(n) on sorted input and O(n²) in the worst case.

    How many inversions does [3, 1, 2] have?

    1
    3 is bigger than both later elements.
    2
    (3, 1) and (3, 2).
    3
    (1, 2) is in order.

    Which sort is fastest on an already-sorted array?

    Selection sort
    It always scans for the minimum: n(n−1)/2 comparisons.
    Insertion sort
    Each element needs one comparison: O(n).
    Plain bubble sort
    Without an early-exit flag, it does all n(n−1)/2 comparisons.

    After k passes of bubble sort (ascending), which is guaranteed?

    The first k elements are the smallest, in order
    That’s selection sort’s guarantee.
    The last k elements are the k largest, in order
    Each pass bubbles the largest remaining element to the end.
    The whole array is sorted
    That needs up to n − 1 passes.

    Merge sort and quicksort: divide and conquer

    Divide and conquer splits a problem into halves, solves each recursively, and combines the answers. Merge sort does the work when combining; quicksort does it when splitting.

    Both are named in the syllabus; GATE has asked for quicksort’s swap count on a sorted array (2024 Q30) and its expected-time recurrence (2026 Q15).

    It’s like sorting a stack of scorecards with friends: split the pile, each sorts half, then merge the two sorted piles by repeatedly taking the smaller top card.

    Where it shows up in GATE DA

    Recurrences, best/worst cases and partition behaviour.

    2026 Q15 · expected-time recurrence of quicksort2024 Q30 · quicksort swaps on a sorted arraySample Q21 · worst-case running times
    Heat: every year, 1–2 marks

    Split the array in half, sort each half recursively, then merge: repeatedly take the smaller front element of the two sorted halves. Merging lists of sizes $m$ and $k$ takes at most $m + k - 1$ comparisons. $T(n) = 2T(n/2) + \Theta(n) = \Theta(n\log n)$ in every case. Needs $O(n)$ extra space; stable.

    Pick a pivot, partition so smaller elements go left and larger go right (the pivot lands in its final place), then recurse on both sides. Balanced splits give $\Theta(n\log n)$; the average over random inputs is also $\Theta(n\log n)$. If the pivot is always the smallest or largest (e.g. last-element pivot on sorted input), splits are $0$ and $n - 1$: $T(n) = T(n-1) + \Theta(n) = \Theta(n^2)$. In place, not stable.

    Try it

    Watch quicksort’s partition step (last element as pivot, the Lomuto scheme): the pointer scans left to right, swapping smaller elements into the growing “less than pivot” zone, then the pivot drops into place. Try an already-sorted array and see how lopsided the splits become, and how few real swaps happen.

    GATE DA 2026 · Q15 · MCQ · 1 mark

    Consider that the quick sort algorithm is used to sort an array of $n$ distinct randomly ordered elements. In every call, the pivot is chosen as the first element of the current subarray. Let $T(n)$ denote the expected time to sort the array. Assume that the time to partition is linear in the size of the current subarray. Which of the following recurrence relations correctly represents $T(n)$ in this scenario?

    1. $T(n) = T(1) + T(n-1) + O(n)$
    2. $T(n) = T(\frac n4) + T(\frac{3n}{4}) + O(n)$
    3. $T(n) = 2T(\frac n2) + O(n)$
    4. $T(n) = \frac1n\sum_{k=0}^{n-1}\left[T(k) + T(n-k-1)\right] + O(n)$
    1. With randomly ordered input, the first element is equally likely to be the smallest, 2nd smallest, …, largest: rank $k + 1$ with probability $\frac1n$ for $k = 0, \ldots, n-1$.

      “Expected time” means averaging over these equally likely cases.

    2. If the pivot has rank $k + 1$, the recursive calls are on $k$ and $n - k - 1$ elements, after linear partitioning: cost $T(k) + T(n-k-1) + O(n)$.

      The pivot itself is excluded from both sides.

    3. Average over $k$: $T(n) = \frac1n\sum_{k=0}^{n-1}[T(k) + T(n-k-1)] + O(n)$. Answer (D).

      (A) is the worst case, (C) the best case, and (B) one particular split. This recurrence solves to $\Theta(n\log n)$. Official key: (D).

    GATE DA 2024 · Q30 · NAT · 1 mark

    Consider sorting the following array of integers in ascending order using an in-place Quicksort algorithm that uses the last element as the pivot. 60 70 80 90 100. The minimum number of swaps performed during this Quicksort is ______.

    Each pivot is the largest element of its subarray, so every other element already sits on the correct side. Does anything need to move?

    At every level the pivot (100, then 90, …) is already in its final place and all others are smaller and to its left. An implementation that skips swapping an element with itself performs no swaps at all: 0. (The time is still Θ(n²) because of the lopsided splits.) Official key: 0.

    What’s the maximum number of comparisons to merge two sorted lists of lengths 4 and 5?

    Each comparison outputs one element; the last element needs no comparison.

    $4 + 5 - 1 = 8$.

    Quicksort with the last element as pivot runs on an array sorted in descending order. Which recurrence describes its running time?

    The pivot is always the smallest element of its subarray.

    Every split is 0 and n − 1: $T(n) = T(n-1) + O(n) = \Theta(n^2)$, the worst case.

    Which are true? (A) Merge sort is $\Theta(n\log n)$ on every input. (B) Quicksort is $\Theta(n\log n)$ on every input. (C) Insertion sort’s worst case is $O(n^2)$. (D) Merge sort sorts in place with $O(1)$ extra memory.

    Which sort has an input-dependent worst case, and which needs a buffer?

    (A) ✓. (B) ✗: worst case Θ(n²). (C) ✓. (D) ✗: standard merge sort needs O(n) extra space. (The 2024 sample paper’s Q21 asks this kind of question.)

    This is the Lomuto partition used by quicksort with the last element as pivot.

    def partition(A, lo, hi):
        pivot = A[hi]
        i = lo - 1
        for j in range(lo, hi):
            if A[j] <= pivot:
                i += 1
                A[i], A[j] = A[j], A[i]
        A[i + 1], A[hi] = A[hi], A[i + 1]
        return i + 1
    
    A = [8, 3, 11, 5, 14, 2, 9, 6]
    p = partition(A, 0, len(A) - 1)

    What is p, and how many times in total do the two swap lines run during this call?

    Track i and the list each time A[j] <= pivot holds. Don’t forget the final swap that puts the pivot in place.

    pivot = 6, i = −1.

    j = 0 (8): no. j = 1 (3): i = 0, swap A[0] and A[1]: [3, 8, 11, 5, 14, 2, 9, 6].

    j = 2 (11): no. j = 3 (5): i = 1, swap A[1] and A[3]: [3, 5, 11, 8, 14, 2, 9, 6].

    j = 4 (14): no. j = 5 (2): i = 2, swap A[2] and A[5]: [3, 5, 2, 8, 14, 11, 9, 6]. j = 6 (9): no.

    Final swap of A[3] and A[7]: [3, 5, 2, 6, 14, 11, 9, 8], and the function returns i + 1 = 3.

    So p = 3 and the swap lines run 3 + 1 = 4 times. Quicksort now recurses on the 3 items left of index 3 and the 4 items right of it.

    What does this merge sort print?

    comps = 0
    
    def msort(A):
        global comps
        if len(A) <= 1:
            return A
        m = len(A) // 2
        L, R = msort(A[:m]), msort(A[m:])
        out, i, j = [], 0, 0
        while i < len(L) and j < len(R):
            comps += 1
            if L[i] <= R[j]:
                out.append(L[i]); i += 1
            else:
                out.append(R[j]); j += 1
        return out + L[i:] + R[j:]
    
    msort([6, 2, 7, 3, 1, 8, 4, 5])
    print(comps)
    1. 12
    2. 16
    3. 17
    4. 24

    Draw the recursion: four merges of two single items, two merges of pairs, one final merge. A merge stops comparing as soon as one side is empty.

    Level 1: [6] with [2], [7] with [3], [1] with [8], [4] with [5]: 1 comparison each, 4 in all. Results [2, 6], [3, 7], [1, 8], [4, 5].

    Level 2: [2, 6] with [3, 7] compares 2–3, 6–3, 6–7 and then [7] is copied: 3 comparisons. [1, 8] with [4, 5] compares 1–4, 8–4, 8–5: 3 comparisons. Results [2, 3, 6, 7] and [1, 4, 5, 8].

    Level 3: the two lists interleave completely (1, 2, 3, 4, 5, 6, 7, 8 alternate sides), so all 8 − 1 = 7 comparisons happen.

    Total 4 + 6 + 7 = 17: (C). This input hits the worst case for n = 8, which is n log₂ n − n + 1 = 24 − 8 + 1 = 17, the solution of C(n) = 2C(n/2) + (n − 1) with C(1) = 0.

    (A) 12 is the best case (each merge stops after n/2 comparisons), (D) 24 charges n comparisons per merge, and (B) 16 = n log₂ n − n forgets the + 1.

    Quicksort uses the Lomuto partition (last element as pivot, test A[j] <= pivot) and recurses on both sides of the pivot. Which of the following is/are correct for arrays of 8 elements?

    1. On [1, 2, 3, 4, 5, 6, 7, 8] it makes 28 comparisons A[j] <= pivot
    2. On eight equal values [5, 5, 5, 5, 5, 5, 5, 5] it makes only 7 comparisons, since nothing needs to move
    3. Its worst-case running time satisfies T(n) = T(n − 1) + Θ(n), which solves to Θ(n²)
    4. On [8, 7, 6, 5, 4, 3, 2, 1] it makes fewer comparisons than on [1, 2, …, 8], because the first pivot, 1, goes straight to the front

    A partition of a subarray of size m makes m − 1 comparisons. For each input, how large is the bigger side after the first partition?

    (A) True. On sorted input the pivot is the largest item each time, so every partition leaves one side of size m − 1 and the other empty. Comparisons 7 + 6 + ⋯ + 1 = 28.

    (B) False. With <=, every equal value goes left of the pivot, so the pivot lands at the end and the split is again m − 1 and 0. That is also 28 comparisons. Nothing visibly moves, but the comparisons still happen.

    (C) True. The worst case is a split of n − 1 and 0 every time: T(n) = T(n − 1) + (n − 1), which sums to n(n − 1)/2 = Θ(n²).

    (D) False. The pivot 1 lands at the front, but the other side then has 7 items, and the same lopsided split repeats on it (with 8 and 2 trading places along the way). Again 28 comparisons.

    Correct: A, C.

    • Write the recurrence from the split sizes: balanced halves → n log n, one-sided → n².
    • Check how the pivot relates to the data (sorted input + end pivot = worst case).
    • Remember merge sort’s guarantees: always n log n, stable, extra space.
    • Saying quicksort is always n log n.
    • Forgetting that partitioning places the pivot in its final position.
    • Counting a swap of an element with itself when the question asks for the minimum swaps.
    1. Merge sort: split, sort the halves, merge (at most m + k − 1 comparisons); Θ(n log n) always, stable, O(n) extra space.
    2. Quicksort: partition around a pivot, then recurse; Θ(n log n) on average, Θ(n²) when pivots are extreme.
    3. Expected quicksort: T(n) = (1/n)Σ[T(k) + T(n−k−1)] + O(n), averaging over the pivot’s rank.

    Merge sort’s recursion tree has about how many levels for n elements?

    n
    Each level halves the size.
    log₂ n
    Halving until size 1 takes log₂ n levels, each doing Θ(n) merging.
    √n
    Halving gives a logarithm, not a square root.

    After one partition step of quicksort, the pivot is

    at index 0
    Only if it was the smallest element.
    in its final sorted position
    Everything left is smaller, everything right is larger.
    still where it started
    It moves to its final place.

    Which choice of pivot makes quicksort’s worst case unlikely on any input?

    Always the first element
    Sorted input then gives Θ(n²).
    A uniformly random element
    Expected Θ(n log n) on every input.
    Always the last element
    Sorted input then gives Θ(n²).

    Max comparisons for an unsuccessful binary search in a sorted array of 100 elements

    6
    $2^6 = 64 \le 100$, so add 1.
    7
    $\lfloor\log_2 100\rfloor + 1 = 6 + 1$.
    100
    That’s linear search.

    Insertion sort on [2, 1, 4, 3] makes how many swaps?

    1
    Count inversions: (2, 1) and (4, 3).
    2
    Two inversions, two swaps.
    4
    Only out-of-order pairs cost a swap.

    Which sort’s running time does not depend on the input order?

    Quicksort
    It depends heavily on the pivots.
    Merge sort
    Always Θ(n log n).
    Insertion sort
    O(n) sorted, O(n²) reversed.

    The data structures named in the syllabus: stacks, queues and linked lists for ordered access, hash tables for instant lookup, and trees for hierarchy and ordered search. GATE asks you to simulate them (what’s on the stack now? which slot does key 15 land in?) and to reason about their properties (traversals, node counts).

    You need: Parts 1–2.

    Stacks, queues and linked lists: order of access

    A stack gives back the most recent item first (LIFO), a queue the oldest first (FIFO), a deque lets you add and remove at both ends, and a linked list chains items with pointers so insertions are cheap but random access isn’t.

    GATE simulates these every year: a deque sequence (2024 Q32), a stack loop (2025 Q64), FIFO/LIFO matching (2024 Q16), building a stack from two queues (sample paper).

    It’s like plates and a ticket queue: you take the top plate off a stack (the last one put there), but the person at the front of the queue (who arrived first) gets served first.

    Where it shows up in GATE DA

    Simulation questions most years; properties in matching questions.

    2025 Q64 · stack pseudocode2024 Q32 · deque operations2024 Q16 · FIFO / lookup / LIFOSample Q50 · stack from two queues2026 Q39 · the call stack
    Heat: every year, 1–2 marks
    StructureOperationsOrderTypical use
    Stackpush, pop, top: all $O(1)$LIFOfunction calls, undo, DFS, matching brackets
    Queueenqueue (back), dequeue (front): $O(1)$FIFOBFS, scheduling, buffers
    Dequeinsert/remove at both ends: $O(1)$eithersliding windows
    Linked listinsert/delete at a known node $O(1)$; search $O(n)$; no indexingchain of nodesstacks and queues, when sizes change often
    Try it

    A deque you can drive with buttons: insert or remove at the front or back. Use “Replay 2024 Q32” to watch that exact sequence of operations and see what a holds after each step. Then try making it behave as a stack (use one end only) and as a queue (insert at one end, remove at the other).

    GATE DA 2025 · Q64 · NAT · 2 marks

    Consider the following pseudocode.

    Create empty stack S
    Set x=0, flag=0, sum=0
    Push x onto S
    while (S is not empty){
        if (flag equals 0){
            Set x = x+1
            Push x onto S}
        if (x equals 8):
            Set flag=1
        if (flag equals 1){
            x = Pop(S)
            if (x is odd):
                Pop(S)
            Set sum = sum + x}
    }
    Output sum

    The value of sum output by a program executing the above pseudocode is ______ (Answer in integer)

    1. Phase 1 (flag = 0): each loop pushes the next x. Once 8 is pushed, flag becomes 1 in the same iteration. The stack is now 0, 1, …, 8 (8 on top).

      The push happens before the check, so 8 does get pushed.

    2. Phase 2 (flag = 1, no more pushes): pop 8 (even), so sum = 8. Pop 7 (odd), pop and discard 6, sum = 15.

      Odd values trigger an extra pop that throws away the next value.

    3. Continue: pop 5 (discard 4), sum = 20; pop 3 (discard 2), sum = 23; pop 1 (discard 0), sum = 24. The stack is empty, so the loop ends. Output 24.

      8 + 7 + 5 + 3 + 1 = 24. Official key: 24.

    GATE DA 2024 · Q32 · NAT · 1 mark

    The fundamental operations in a double-ended queue D are: insertFirst(e), insertLast(e), removeFirst() and removeLast(). In an empty double-ended queue, the following operations are performed: insertFirst(10), insertLast(32), a ← removeFirst(), insertLast(28), insertLast(17), a ← removeFirst(), a ← removeLast(). The value of a is ______.

    Write the deque after each operation, front on the left.

    [10] → [10, 32] → remove 10 → [32] → [32, 28] → [32, 28, 17] → remove 32 → [28, 17] → remove 17. So a = 17. Official key: 17.

    GATE DA 2024 · Q16 · MCQ · 1 mark

    Match the items in Column 1 with the items in Column 2: (p) First In First Out, (q) Lookup Operation, (r) Last In First Out; with (i) Stacks, (ii) Queues, (iii) Hash Tables.

    1. (p) − (ii), (q) − (iii), (r) − (i)
    2. (p) − (ii), (q) − (i), (r) − (iii)
    3. (p) − (i), (q) − (ii), (r) − (iii)
    4. (p) − (i), (q) − (iii), (r) − (ii)

    FIFO is a queue, LIFO is a stack, and fast lookup is a hash table.

    (A). Official key: (A).

    GATE DA 2024 sample paper · Q50 · MCQ · 2 marks

    Assume that S is a stack and Q1 and Q2 are two Queues which support the Enqueue and Dequeue operations. Consider the following pseudo code for implementing the Pop and Push operation on S. [Note: Swap(x,y) exchanges the two queues x and y.]

    Push(S,x)
        A(Q2,x)
        while(Q1 not empty)
            B(Q2, C(Q1));
        Swap(Q1, Q2)
    Pop(S)
        return(D(Q1))

    Which of the following options for the functions A, B, C, and D correspond to correctly implementing the Push and Pop operations on the stack S?

    1. A,B - Enqueue; C,D - Dequeue
    2. A,C - Enqueue; B,D - Dequeue
    3. A,C - Dequeue; B,D - Enqueue
    4. A,D - Enqueue; B,C - Dequeue

    Push puts x into the empty Q2 first, then moves everything from Q1 behind it, so x ends up at the front. Which operations put in, and which take out?

    A adds x to Q2 (Enqueue). C takes from Q1 (Dequeue) and B adds that to Q2 (Enqueue). After the swap, the newest element is at Q1’s front, so Pop is a Dequeue (D). Answer (A). (Sample paper, no official key.)

    Starting from an empty stack: push 1, push 2, pop, push 3, push 4, pop, pop. What did the last pop return?

    Track the stack after each operation (top on the right).

    [1] → [1, 2] → pop 2 → [1] → [1, 3] → [1, 3, 4] → pop 4 → pop 3. Answer 3.

    A stack evaluates the postfix expression 6 2 3 + * 8 4 / - 5 2 * +. On an operator it pops b, then pops a, and pushes a op b (here every division is exact). What is the final value, and what is the largest number of items the stack ever holds?

    Write the stack after every token, top on the right. Mind the order: the first item popped is the right-hand operand.

    6 → [6]; 2 → [6, 2]; 3 → [6, 2, 3]; + → [6, 5]; * → [30].

    8 → [30, 8]; 4 → [30, 8, 4]; / pops b = 4, a = 8 and pushes 8/4 = 2 → [30, 2]; − pops b = 2, a = 30 → [28].

    5 → [28, 5]; 2 → [28, 5, 2]; * → [28, 10]; + → [38].

    Final value 38; the stack was largest, with 3 items, after reading 3 and again after reading 4 and the second 2. (Taking the operands in the wrong order would give 4/8 and 2 − 30 instead.)

    A queue is built from two Python lists used as stacks. What does the program print?

    inbox, outbox = [], []
    moves = 0
    
    def enqueue(x):
        inbox.append(x)
    
    def dequeue():
        global moves
        if not outbox:
            while inbox:
                outbox.append(inbox.pop())
                moves += 1
        return outbox.pop()
    
    enqueue(1); enqueue(2); enqueue(3)
    a = dequeue()
    enqueue(4); enqueue(5)
    b = dequeue(); c = dequeue()
    enqueue(6)
    d = dequeue()
    print(a, b, c, d, moves)
    1. 1 2 3 4 6
    2. 1 2 3 4 4
    3. 1 4 5 6 6
    4. 3 2 1 6 6

    outbox is refilled only when it is empty. When it is refilled, in what order do the items come off it?

    After three enqueues, inbox = [1, 2, 3]. The first dequeue finds outbox empty and moves 3, 2, 1 across (3 moves): outbox = [3, 2, 1], so the pop returns a = 1.

    Enqueue 4, 5: inbox = [4, 5]. outbox = [3, 2] is not empty, so b = 2 and c = 3 with no moves.

    Enqueue 6: inbox = [4, 5, 6]. The last dequeue finds outbox empty and moves 6, 5, 4 (3 more moves): outbox = [6, 5, 4], so d = 4.

    It prints 1 2 3 4 6: (A). The values come out in FIFO order, as a queue should, and each item is moved at most once.

    (B) counts only the moves of items already dequeued. (C) refills outbox at every dequeue even when it is not empty, which breaks the order. (D) moves the items across without reversing them.

    Here q is used as a queue and s as a stack. What does the program print?

    q = [10, 20, 30, 40, 50]
    s = []
    for k in range(4):
        x = q.pop(0)
        if x % 20 == 0:
            s.append(x)
        else:
            y = x + s.pop() if s else x * 2
            q.append(y)
    print(sum(q) + len(s))

    Read the line that sets y carefully: a conditional expression binds more loosely than +, so it means (x + s.pop()) if s else (x * 2). Trace the four iterations.

    k = 0: x = 10, not a multiple of 20; s is empty, so append 10 × 2 = 20. q = [20, 30, 40, 50, 20].

    k = 1: x = 20, a multiple of 20: push it. s = [20], q = [30, 40, 50, 20].

    k = 2: x = 30; s is non-empty, so append 30 + s.pop() = 50. s = [], q = [40, 50, 20, 50].

    k = 3: x = 40: push it. s = [40], q = [50, 20, 50].

    sum(q) = 120 and len(s) = 1, so it prints 121.

    • Write the structure’s contents after every operation; mark which end is the front or top.
    • Read pseudocode conditions in order within each loop iteration.
    • Match stack ↔ LIFO ↔ DFS/recursion, and queue ↔ FIFO ↔ BFS.
    • Forgetting that a pop also removes the item, not just reads it.
    • Mixing up the ends of a deque.
    • Assuming linked lists allow O(1) indexing.
    1. Stack = LIFO (push/pop at the top); queue = FIFO (enqueue at the back, dequeue at the front); deque = both ends.
    2. All core operations are O(1); linked lists trade O(n) search for O(1) insertion at a known node.
    3. Simulate carefully: one state per operation, with the order of checks inside loops respected.

    Which structure does BFS use?

    Stack
    A stack gives DFS’s “go deep first” behaviour.
    Queue
    FIFO visits vertices level by level.
    Hash table
    BFS may use one to mark visited vertices, but its ordering comes from a queue.

    Push 5, 6, 7 onto a stack, then pop twice. What’s on top?

    7
    7 was popped first.
    5
    7 and 6 are removed; 5 remains.
    6
    6 was the second pop.

    Accessing the k-th element of a singly linked list takes

    O(1)
    There’s no index; you follow pointers from the head.
    O(k)
    Walk k links from the head.
    O(log k)
    Linked lists don’t support halving.

    Hash tables: lookup in (expected) constant time

    A hash table uses a hash function to turn each key into a slot number, so finding a key takes about one step, unless two keys want the same slot (a collision), which chaining or probing resolves.

    GATE asks you to insert keys with linear probing (2025 Q18) and to know the expected number of probes (2024 Q21). Python’s dict and set are hash tables.

    It’s like a stadium with numbered seats printed on each ticket: you walk straight to your seat. If someone is already sitting there, linear probing says “try the next seat along”.

    Where it shows up in GATE DA

    Insertion simulations and expected-probe formulas.

    2025 Q18 · linear probing with h(x) = 3x mod 102024 Q21 · expected probes for insertion2024 Q16 · lookup ↔ hash table
    Heat: every year, 1 mark
    • A hash function $h$ maps a key to a slot in $\{0, 1, \ldots, m-1\}$, e.g. $h(x) = x \bmod m$.
    • Load factor $\alpha = n/m$ ($n$ keys, $m$ slots).
    • Chaining: each slot holds a list of keys; the expected chain length is $\alpha$.
    • Open addressing: every key sits in the table itself; on a collision, probe other slots. Linear probing tries $h(x), h(x)+1, h(x)+2, \ldots$ (wrapping around). It’s simple but causes clustering: long runs of filled slots.
    • Unsuccessful search: at most $\dfrac{1}{1-\alpha}$ probes.
    • Insertion = an unsuccessful search for the key followed by placing it in the empty slot found: also at most $\dfrac{1}{1-\alpha}$.
    • Successful search: at most $\dfrac1\alpha\ln\dfrac{1}{1-\alpha}$.
    Try it

    Insert keys into a 10-slot table with linear probing. The hash function is $h(x) = (a\cdot x) \bmod 10$; set $a = 3$ and use “Replay 2025 Q18” to watch keys 14 and 15 bump along to their slots. The readout counts probes for each insertion, and the clusters of filled slots show why linear probing slows down as the table fills.

    GATE DA 2025 · Q18 · MCQ · 1 mark

    Consider a hash table of size 10 with indices $\{0, 1, \ldots, 9\}$, with the hash function $h(x) = 3x \pmod{10}$, where linear probing is used to handle collisions. The hash table is initially empty and then the following sequence of keys is inserted into the hash table: 1, 4, 5, 6, 14, 15. The indices where the keys 14 and 15 are stored are, respectively

    1. 2 and 5
    2. 2 and 6
    3. 4 and 5
    4. 4 and 6
    1. Home slots: 1 → 3, 4 → 12 mod 10 = 2, 5 → 5, 6 → 18 mod 10 = 8. All free, so the table holds 4 at slot 2, 1 at 3, 5 at 5 and 6 at 8.

      Compute 3x mod 10 for each key in order.

    2. 14 → 42 mod 10 = 2: occupied (by 4). Probe 3: occupied (by 1). Probe 4: free, so 14 goes to slot 4.

      Linear probing steps one slot at a time.

    3. 15 → 45 mod 10 = 5: occupied. Probe 6: free, so 15 goes to slot 6. Answer (D) 4 and 6.

      Options (A) and (C) list the home slots, forgetting the collisions. Official key: (D).

    GATE DA 2024 · Q21 · MCQ · 1 mark

    Consider performing uniform hashing on an open address hash table with load factor $\alpha = \frac nm \lt 1$, where $n$ elements are stored in the table with $m$ slots. The expected number of probes in an unsuccessful search is at most $\frac{1}{1-\alpha}$. Inserting an element in this hash table requires at most ______ probes, on average.

    1. $\ln\left(\frac{1}{1-\alpha}\right)$
    2. $\frac{1}{1-\alpha}$
    3. $1 + \frac\alpha2$
    4. $\frac{1}{1+\alpha}$

    To insert, you search until you find an empty slot. What kind of search is that?

    Insertion probes exactly like an unsuccessful search, then fills the empty slot: at most $\frac{1}{1-\alpha}$. Official key: (B).

    With $h(x) = x \bmod 10$ and linear probing, keys 12, 22, 32 are inserted into an empty table. In which slot does 32 land?

    All three hash to slot 2.

    12 → 2, 22 → 3 (after one collision), 32 → 4 (after two collisions).

    An open-addressing table is 90% full ($\alpha = 0.9$). What’s the bound on the expected number of probes to insert a new key?

    $1/(1-\alpha)$.

    $1/0.1 = 10$. (At α = 0.5 it would be only 2, which is why tables are resized before they get too full.)

    A chained hash table has 20 slots and holds 50 keys. What is the expected length of a chain?

    The load factor α = n/m.

    $50/20 = 2.5$.

    The keys 23, 41, 12, 34, 56, 45, 9, 20 are inserted in that order into an empty table with 11 slots (0 to 10), using $h(k) = k \bmod 11$ and linear probing. In which slot does 20 land? And how many probes do the eight insertions take in total, counting the look at the home slot as one probe?

    Compute every home slot first. Several keys share one; each later one walks right past the cluster that has built up, wrapping from 10 to 0 if needed.

    Home slots: 23 → 1, 41 → 8, 12 → 1, 34 → 1, 56 → 1, 45 → 1, 9 → 9, 20 → 9.

    23 → slot 1 (1 probe). 41 → slot 8 (1). 12: slot 1 is full, slot 2 (2 probes). 34: slots 1, 2 full, slot 3 (3). 56: slot 4 (4). 45: slot 5 (5).

    9 → slot 9 (1). 20: slot 9 is full, slot 10 is free (2 probes). 20 lands in slot 10.

    Total probes 1 + 1 + 2 + 3 + 4 + 5 + 1 + 2 = 19. The five keys hashing to 1 cost 1 + 2 + 3 + 4 + 5: that is primary clustering at work.

    The keys 18, 29, 7, 40, 51, 16 are inserted in that order into an empty table of 11 slots (0 to 10) with $h(k) = k \bmod 11$. Collisions are resolved either by linear probing, slot $(h(k) + t) \bmod 11$, or by quadratic probing, slot $(h(k) + t^2) \bmod 11$, for $t = 0, 1, 2, \ldots$ Which of the following is/are correct?

    1. With linear probing, 51 lands in slot 0
    2. With quadratic probing, 51 lands in slot 1
    3. With quadratic probing, 16 lands in its home slot 5
    4. Linear probing uses more probes in total than quadratic probing for these six keys

    Five of the six keys have the same home slot. Under quadratic probing, check where each of them goes before you place 16.

    Home slots: 18, 29, 7, 40, 51 all → 7; 16 → 5.

    Linear: 18 → 7, 29 → 8, 7 → 9, 40 → 10, 51 tries 7, 8, 9, 10 and wraps to 0. 16 → 5. (A) true. Probes 1 + 2 + 3 + 4 + 5 + 1 = 16.

    Quadratic: 18 → 7; 29: 7, then 8. 7: 7, 8, then 7 + 4 = 11 → 0. 40: 7, 8, 0, then 7 + 9 = 16 → 5. 51: 7, 8, 0, 5, then 7 + 16 = 23 → 1. (B) true.

    16: its home slot 5 is already taken by 40, so it moves on to 5 + 1 = 6. (C) false. Probes 1 + 2 + 3 + 4 + 5 + 2 = 17.

    (D) false: 16 against 17, quadratic probing uses one more here.

    Correct: A, B.

    The keys 19, 30, 41, 8, 52 are inserted in that order into an empty table of 11 slots (0 to 10) using double hashing: probe $t$ looks at slot $(h_1(k) + t \cdot h_2(k)) \bmod 11$ for $t = 0, 1, 2, \ldots$, where $h_1(k) = k \bmod 11$ and $h_2(k) = 1 + (k \bmod 9)$. In which slot does 52 land? In which slot would it land if the same keys were inserted with linear probing, $(h_1(k) + t) \bmod 11$, instead?

    All five keys have the same $h_1$. Work out $h_2$ for each key; it is the step size of that key’s probe sequence.

    $h_1$ is 8 for every key (19, 30, 41, 8, 52 all leave remainder 8 on division by 11).

    Double hashing: 19 → 8. 30: $h_2 = 1 + 3 = 4$, so 8, then 12 mod 11 = 1. 41: $h_2 = 1 + 5 = 6$, so 8, then 14 mod 11 = 3. 8: $h_2 = 1 + 8 = 9$, so 8, then 17 mod 11 = 6. 52: $h_2 = 1 + 7 = 8$, so 8, then 16 mod 11 = 5, which is free. 52 lands in slot 5.

    Linear probing: 19 → 8, 30 → 9, 41 → 10, 8 wraps to 0, and 52 tries 8, 9, 10, 0 and lands in slot 1, on its fifth probe. Double hashing spread the keys out and placed 52 on its second probe.

    • Compute every home slot first, then resolve collisions in insertion order.
    • Remember insertion costs the same as an unsuccessful search.
    • Keep α well below 1 for open addressing.
    • Forgetting to wrap around from slot m − 1 to slot 0.
    • Inserting keys out of the given order (later keys depend on earlier ones).
    • Confusing chaining (α can exceed 1) with open addressing (α < 1 always).
    1. A hash function maps keys to slots; collisions are resolved by chaining or by probing (open addressing).
    2. Linear probing tries h(x), h(x)+1, … with wrap-around, which causes clustering.
    3. With load factor α: unsuccessful search and insertion take ≤ 1/(1−α) probes on average; chains average α keys.

    Python’s dict lookup is, on average,

    O(log n)
    That’s a balanced search tree.
    O(1)
    It’s a hash table.
    O(n)
    Only in pathological collision cases.

    Primary clustering is a problem of

    chaining
    Chaining stores collisions in lists, not neighbouring slots.
    linear probing
    Filled runs grow, and every key hashing into a run lengthens it.
    binary search
    Unrelated.

    As α → 1 with open addressing, the expected insertion cost

    approaches 1
    $1/(1-\alpha)$ grows as α approaches 1.
    blows up
    $1/(1-\alpha) \to \infty$: almost every slot is taken.
    stays constant
    It depends strongly on α.

    Binary trees: traversals, counting and search trees

    A binary tree gives each node up to two children; visiting nodes in pre-, in- or post-order gives three different listings, and two of them together pin the tree down.

    GATE asks traversal-reconstruction questions (2024 Q28, 2026 Q25) and counting facts about heights and leaves (2024 Q52). Binary search trees power ordered lookup.

    It’s like a tournament bracket read three ways: announce each match before its sub-matches (pre-order), between them (in-order), or after them (post-order).

    Where it shows up in GATE DA

    Traversals and reconstruction most years; counting bounds; tree recursion in code.

    2026 Q25 · rebuild from pre-order + in-order2024 Q28 · which pairs determine a full binary tree2024 Q52 · bounds on H, I, L, N2024 Q38 · counting subtree nodes
    Heat: every year, 1–4 marks
    • Root, leaf (no children), internal node (at least one child). Height H = the number of edges on the longest root-to-leaf path (a single node has height 0).
    • Full binary tree: every internal node has exactly 2 children. Then $L = I + 1$. In any binary tree, $L \le I + 1$.
    • Node count: $H + 1 \le N \le 2^{H+1} - 1$ (a path at one extreme, a perfect tree at the other).
    • Binary search tree (BST): everything in a node’s left subtree is smaller, everything in its right subtree larger. Search, insert and delete take $O(h)$; in-order traversal lists the keys in sorted order.
    • Pre-order: node, left subtree, right subtree. (The root comes first.)
    • In-order: left, node, right. (The root splits left from right.)
    • Post-order: left, right, node. (The root comes last.)
    • Level-order: by depth, left to right (BFS with a queue).

    Reconstruction: in-order + pre-order (or in-order + post-order) determines any binary tree with distinct labels. Pre-order + post-order alone is ambiguous in general, but determines a full binary tree.

    Try it

    Build a binary search tree by inserting keys (or load a preset), then run each traversal and watch the order in which nodes light up. Check that the in-order traversal of a BST always comes out sorted. Load “2026 Q25” to see the tree that question describes.

    GATE DA 2026 · Q25 · MSQ · 1 mark

    You are given the following Pre-order and In-order traversals of a Binary Tree T with nodes E, F, G, P, Q, R, S. Pre-order: P Q S E R F G. In-order: S Q E P F R G. Which of the following statements is/are true about the Binary Tree T?

    1. Node P is the root of T
    2. The Post-order traversal of T is: S E Q F G R P
    3. Node Q has only one child
    4. The left subtree of node R contains the node G
    1. Pre-order starts with the root: P. In the in-order list, P splits the rest: left subtree {S, Q, E}, right subtree {F, R, G}.

      Pre-order gives the root; in-order tells you who’s on which side.

    2. Left part: pre-order order is Q, S, E, so Q is the left subtree’s root; in-order S Q E puts S on Q’s left and E on its right. Right part: pre-order R, F, G gives root R; in-order F R G puts F left and G right.

      Apply the same rule recursively.

    3. Post-order (left, right, root): S E Q, then F G R, then P, which gives S E Q F G R P. So (A) ✓, (B) ✓; Q has two children (C ✗); G is in R’s right subtree (D ✗). Answer: A, B.

      Official key: A; B.

    GATE DA 2024 · Q28 · MSQ · 1 mark

    Consider the following tree traversals on a full binary tree: (i) Preorder (ii) Inorder (iii) Postorder. Which of the following traversal options is/are sufficient to uniquely reconstruct the full binary tree?

    1. (i) and (ii)
    2. (ii) and (iii)
    3. (i) and (iii)
    4. (ii) only

    In-order plus either other traversal always works. Pre + post works when every internal node has exactly two children. One traversal alone is never enough.

    (A), (B) ✓ always. (C) ✓ because the tree is full: after the root, the next pre-order element must be the left child, and post-order tells where its subtree ends. (D) ✗: many trees share an in-order. Official key: A; B; C.

    GATE DA 2024 · Q52 · MSQ · 2 marks

    Let H, I, L, and N represent height, number of internal nodes, number of leaf nodes, and the total number of nodes respectively in a rooted binary tree. Which of the following statements is/are always TRUE?

    1. $L \le I + 1$
    2. $H + 1 \le N \le 2^{H+1} - 1$
    3. $H \le I \le 2^H - 1$
    4. $H \le L \le 2^{H-1}$

    Test each bound on two extremes: a path (every node has one child) and a perfect tree.

    (A) ✓ (equality for full trees; fewer leaves otherwise). (B) ✓ (path: H + 1 nodes; perfect: $2^{H+1} - 1$). (C) ✓ (a path has H internal nodes; a perfect tree has $2^H - 1$). (D) ✗: a path of height H has only 1 leaf, which is less than H when H > 1. Official key: A; B; C.

    A full binary tree has 5 leaves. How many nodes does it have in total?

    In a full binary tree, L = I + 1.

    I = 4, so N = 4 + 5 = 9.

    Insert 50, 30, 70, 20, 40, 60, 80, 35 (in that order) into an empty BST. What is its post-order traversal?

    Draw the tree. 35 goes left of 40. Post-order lists children before parents.

    Left subtree of 50: 30 with children 20 and 40 (and 35 under 40). Right subtree: 70 with 60, 80. Post-order: 20 35 40 30 60 80 70 50. (The first option is pre-order; the second, sorted, is in-order.)

    Insert 45, 25, 70, 15, 35, 60, 85, 30, 40, 65, 32 in that order into an empty binary search tree. Then delete 25 and then delete 45, each time replacing a node that has two children by its in-order successor. What is the pre-order traversal of the final tree?

    1. 60 30 15 35 32 40 70 65 85
    2. 40 15 35 30 32 70 60 65 85
    3. 15 30 32 35 40 60 65 70 85
    4. 60 30 15 35 40 70 65 85

    The in-order successor of a node with two children is the smallest key in its right subtree. That key may itself have a right child, which has to be reattached.

    The tree: 45 is the root with children 25 and 70. 25 has children 15 and 35; 35 has children 30 and 40; 30 has a right child 32. 70 has children 60 and 85; 60 has a right child 65.

    Delete 25: its successor is the smallest key in its right subtree, 30. Copy 30 into 25’s node and remove the old 30, whose right child 32 takes its place as 35’s left child. The left subtree is now 30 with children 15 and 35, and 35 has children 32 and 40.

    Delete 45: its successor is 60. Copy 60 to the root and remove the old 60; its right child 65 becomes 70’s left child.

    Pre-order (node, left, right): 60, 30, 15, 35, 32, 40, 70, 65, 85: (A).

    (B) uses in-order predecessors instead, (C) is the in-order traversal, and (D) loses 32 when 30 is moved.

    The pre-order traversal of a binary search tree is 10, 6, 3, 1, 4, 8, 7, 15, 12, 13, 20, 18. How many leaves does the tree have, and what is its height (the number of edges on the longest path from the root to a leaf)?

    For a BST the in-order traversal is the sorted list, so the pre-order alone fixes the tree. The first key is the root; the keys after it that are smaller form the left subtree.

    Root 10. Left subtree from 6, 3, 1, 4, 8, 7; right subtree from 15, 12, 13, 20, 18.

    Left: 6 is its root; 3, 1, 4 go left of 6 (3 with children 1 and 4) and 8, 7 go right (8 with left child 7).

    Right: 15 is its root; 12, 13 go left (12 with right child 13) and 20, 18 go right (20 with left child 18).

    Leaves: 1, 4, 7, 13, 18, so 5 leaves. Longest root-to-leaf paths have 3 edges, for example 10 → 6 → 3 → 1 or 10 → 15 → 12 → 13, so the height is 3.

    A binary tree is stored as nested tuples (key, left, right), with None for an empty subtree.

    def node(k, l=None, r=None):
        return (k, l, r)
    
    T = node(8,
             node(3, node(1),
                  node(6, node(4))),
             node(10, None,
                  node(14, node(13))))
    
    def walk(t, out):
        if t is None:
            return 0
        k, l, r = t
        a = walk(l, out)
        out.append(k)
        b = walk(r, out)
        return 1 + max(a, b)
    
    out = []
    h = walk(T, out)

    Which of the following is/are correct?

    1. out is [1, 3, 4, 6, 8, 10, 13, 14]
    2. h is 3
    3. If out.append(k) is moved to just before a = walk(l, out), out becomes [8, 3, 1, 6, 4, 10, 14, 13]
    4. If out.append(k) is moved to just after b = walk(r, out), out ends with 13

    Draw the tree from the tuples first. Then ask which traversal each position of out.append(k) gives, and what walk returns for a single leaf.

    The tree: 8 at the root; 3 on its left with children 1 and 6, and 6 has a left child 4; 10 on its right with right child 14, and 14 has a left child 13.

    As written, the key is recorded between the two subtrees: an in-order traversal. This tree is a BST, so the result is sorted: (A) true.

    walk returns 0 for an empty tree and 1 for a leaf, so it counts the nodes on the longest root-to-leaf path. 8 → 3 → 6 → 4 has 4 nodes, so h = 4: (B) false (3 is the height in edges).

    Recording the key before the left subtree gives pre-order: 8, 3, 1, 6, 4, 10, 14, 13. (C) true.

    Recording it after both subtrees gives post-order, which always ends with the root: 1, 4, 6, 3, 13, 14, 10, 8. (D) false.

    Correct: A, C.

    • Use pre-order for the root, then in-order to split left and right; recurse.
    • Test “always true” bounds on a path and on a perfect tree.
    • Use in-order = sorted as a quick BST check.
    • Counting height in nodes instead of edges (or vice versa). Check the question’s convention.
    • Claiming pre-order + post-order reconstructs every binary tree.
    • Assuming BST operations are O(log n) without balance; a skewed BST is O(n).
    1. Pre-order: root first; in-order: root in the middle; post-order: root last; level-order uses a queue.
    2. In-order + (pre or post) determines a binary tree; pre + post works for full binary trees.
    3. L ≤ I + 1 (equality when full), H + 1 ≤ N ≤ 2^(H+1) − 1; BSTs give O(h) search and a sorted in-order.

    The in-order traversal of a BST with keys {5, 2, 8, 1} is

    5 2 1 8
    That’s pre-order (if 5 is the root).
    1 2 5 8
    In-order of a BST is always sorted.
    1 2 8 5
    That’s post-order.

    A perfect binary tree of height 3 has how many nodes?

    8
    That’s the number of leaves.
    15
    $2^{3+1} - 1$.
    7
    That’s height 2.

    The last node in a post-order traversal is always

    a leaf
    Post-order lists children before their parent.
    the root
    The root is listed after both subtrees.
    the smallest key
    That’s the first in-order node of a BST.

    Enqueue 1, 2, 3 into a queue, dequeue once, then enqueue 4. The front is

    1
    1 was dequeued.
    2
    FIFO: after removing 1, 2 is next.
    4
    4 joined at the back.

    With $h(x) = x \bmod 7$ and linear probing, inserting 3, 10, 17 places 17 in slot

    3
    Slot 3 holds 3.
    4
    10 took slot 4.
    5
    All hash to 3; they fill 3, 4, 5.

    Searching a BST built by inserting 1, 2, 3, …, n in order takes, in the worst case,

    O(log n)
    Sorted insertions make a chain, not a balanced tree.
    O(n)
    The tree is a path of height n − 1.
    O(1)
    You may need to walk the whole chain.

    Graphs model anything with connections: cities and roads, web pages and links, tasks and prerequisites. The syllabus asks for an introduction to graph theory, traversals (BFS and DFS) and shortest paths. GATE asks which vertices a traversal visits and in what order, what kind of edge DFS creates, which orderings are valid topological sorts, and what shortest-path facts imply.

    You need: Part 3 (stacks and queues).

    Graph traversals: BFS, DFS and topological sort

    BFS explores a graph in rings of increasing distance using a queue; DFS dives as deep as possible before backtracking, using a stack (or recursion); a topological sort lines up a DAG’s vertices so every edge points forward.

    A traversal question appears in every DA paper: DFS edge types (2024 Q14), BFS vs DFS expansions (2024 Q44), topological orders (2024 Q51), DFS discovery order (2025 Q65), reachability in reversed graphs (2026 Q40).

    It’s like exploring a new city: BFS visits every place one stop away, then two stops away; DFS follows one road as far as it goes before backtracking to the last junction.

    Where it shows up in GATE DA

    Every year, often two questions; the AI module’s search algorithms build on the same ideas.

    2024 Q51 · valid topological orders2024 Q14 · DFS edge types2024 Q44 · BFS vs DFS expansions2025 Q65 · DFS discovery order2026 Q40 · reachability in Gᴿ
    Heat: every year, 2–4 marks
    • A graph has vertices and edges, either undirected or directed. The degree of a vertex is its number of edges (in-degree and out-degree for directed graphs).
    • Adjacency list: each vertex stores its neighbours; $O(V + E)$ space, best for sparse graphs. Adjacency matrix: $V\times V$ table; $O(V^2)$ space, $O(1)$ edge lookup.
    • A DAG is a directed acyclic graph: directed, with no cycles.

    BFS: put the start in a queue; repeatedly dequeue a vertex and enqueue its unvisited neighbours. Vertices come out in order of distance (number of edges) from the start, so BFS finds shortest paths in unweighted graphs.

    DFS: visit a vertex, then recursively visit each unvisited neighbour in turn (the order of the adjacency list matters). Both run in $O(V + E)$ and visit exactly the vertices reachable from the start.

    DFS edge types: tree edges (to a newly discovered vertex), back edges (to an ancestor still being explored, which signals a cycle), forward and cross edges (directed graphs only). In an undirected DFS, every edge is a tree edge or a back edge.

    An ordering in which every edge $u \to v$ has $u$ before $v$. Kahn’s method: repeatedly output a vertex with in-degree 0 and delete its outgoing edges. When several vertices have in-degree 0, any of them may go next, so a DAG can have many valid orders. (Equivalently: list vertices in decreasing DFS finishing time.)

    Try it

    Choose a graph and a start vertex, then step BFS or DFS: the readout shows the queue or stack and the visiting order. On the 2024 Q51 DAG, run the topological sort and note the moments when more than one vertex is available: each choice gives a different valid order.

    GATE DA 2024 · Q51 · MSQ · 2 marks

    Consider the directed acyclic graph (DAG) below:

    The figure shows edges P → Q, R → Q, Q → S, Q → V, S → U and V → T.

    Which of the following is/are valid vertex orderings that can be obtained from a topological sort of the DAG?

    1. P Q R S T U V
    2. P R Q V S U T
    3. P Q R S V U T
    4. P R Q S V T U
    1. List the constraints: P and R before Q; Q before S and V; S before U; V before T.

      Every edge u → v requires u to come first.

    2. (A) and (C) put Q before R, but R → Q requires R first. ✗ (A also has T before V.)

      One violated edge is enough to reject an order.

    3. (B) P R Q V S U T: P, R before Q ✓; V, S after Q ✓; U after S ✓; T after V ✓. (D) P R Q S V T U: likewise ✓. Answer: B, D.

      After Q, both S and V are available, which is why there are several valid orders. Official key: B; D.

    GATE DA 2024 · Q14 · MCQ · 1 mark

    Consider performing depth-first search (DFS) on an undirected and unweighted graph G starting at vertex $s$. For any vertex $u$ in G, $d[u]$ is the length of the shortest path from $s$ to $u$. Let $(u, v)$ be an edge in G such that $d[u] \lt d[v]$. If the edge $(u, v)$ is explored first in the direction from $u$ to $v$ during the above DFS, then $(u, v)$ becomes a ______ edge.

    1. tree
    2. cross
    3. back
    4. gray

    Undirected DFS only has tree and back edges. If the edge is explored from u to v first, has v been discovered yet?

    If the edge is first explored from u, v hasn’t been discovered (otherwise the edge would have been explored from v’s side). So u discovers v: a tree edge. Undirected DFS has no cross edges, and “gray” is a vertex colour, not an edge type. Official key: (A).

    GATE DA 2024 · Q44 · MCQ · 2 marks

    Consider a state space where the start state is number 1. The successor function for the state numbered n returns two states numbered n+1 and n+2. Assume that the states in the unexpanded state list are expanded in the ascending order of numbers and the previously expanded states are not added to the unexpanded state list. Which ONE of the following statements about breadth-first search (BFS) and depth-first search (DFS) is true, when reaching the goal state number 6?

    1. BFS expands more states than DFS.
    2. DFS expands more states than BFS.
    3. Both BFS and DFS expand equal number of states.
    4. Both BFS and DFS do not reach the goal state number 6.

    Simulate both. In DFS, the smaller number (n + 1) is expanded first.

    BFS expands 1, 2, 3, 4, 5 before reaching 6. DFS expands 1, 2, 3, 4, 5 (always taking n + 1 first) and then reaches 6. Both expand 5 states. Official key: (C).

    GATE DA 2025 · Q65 · NAT · 2 marks

    Consider a directed graph G = (V, E), where V = {0, 1, 2, …, 100} and E = {(i, j) : 0 < j − i ≤ 2, for all i, j ∈ V}. Suppose the adjacency list of each vertex is in decreasing order of vertex number, and depth-first search (DFS) is performed at vertex 0. The number of vertices that will be discovered after vertex 50 is ______ (Answer in integer)

    Each vertex i has edges to i + 2 and i + 1, tried in that order. DFS from 0 races ahead through the even numbers first. When does it backtrack and pick up the odd ones?

    DFS goes 0 → 2 → 4 → … → 100 (always taking i + 2 first). At 100 there’s nowhere to go, so it backtracks to 98 and tries 99; then back to 96, tries 97; and so on down to 0, which tries 1. So the discovery order is all 51 even numbers 0, 2, …, 100, then the odds 99, 97, …, 1. After 50 come the 25 evens 52, …, 100 and all 50 odds: 25 + 50 = 75. Official key: 75.

    GATE DA 2026 · Q40 · MCQ · 2 marks

    Consider a directed graph G = (V, E), where V is the finite set of vertices and E is the set of directed edges between the vertices. G may contain cycles but there is no self-loop. Further, G may not be strongly connected. Let $G^R$ be the graph obtained by reversing the directions of all the edges in G without changing the set of vertices. Assume that Breadth First Search (BFS) or Depth First Search (DFS) from any given vertex $v$ of a graph visits only the reachable vertices from $v$ in that graph. Which of the following statements must always be true, regardless of the structure of G?

    1. If $u$ is a reachable vertex in the BFS of $G^R$ from $v$, then $u$ is also a reachable vertex in the DFS of G from $v$.
    2. In $G^R$, the BFS traversal from $v$ will visit exactly the same set of vertices as the DFS from $v$ in G.
    3. The order of vertices visited in the BFS of $G^R$ from $v$ is the reverse of the order of vertices visited in the DFS of G from $v$.
    4. If $u$ is a reachable vertex in the DFS of G from $v$, then $v$ is also a reachable vertex in the BFS of $G^R$ from $u$.

    A path v → … → u in G becomes a path u → … → v in Gᴿ. Which option states exactly this?

    Reversing every edge reverses every path: u reachable from v in G ⇔ v reachable from u in Gᴿ. That’s (D). (A) and (B) confuse “reachable from v in Gᴿ” with “reachable from v in G”; a one-way edge v → u breaks them. (C) makes a claim about order that has no basis. Official key: (D).

    What does this program print? (The graph is undirected; each list is that vertex’s neighbours.)

    G = {'A': ['B', 'C', 'D'],
         'B': ['A', 'E'],
         'C': ['A', 'E', 'F'],
         'D': ['A', 'F'],
         'E': ['B', 'C', 'G'],
         'F': ['C', 'D', 'G'],
         'G': ['E', 'F']}
    seen = []
    stack = ['A']
    while stack:
        u = stack.pop()
        if u in seen:
            continue
        seen.append(u)
        for v in G[u]:
            if v not in seen:
                stack.append(v)
    print(''.join(seen))
    1. ABECFDG
    2. ABCDEFG
    3. ADFGECB
    4. ADCBFEG

    The stack hands back the neighbour pushed last. Write the stack contents after each pop, and remember that a vertex can sit on the stack more than once.

    Pop A, record it, push B, C, D. Stack [B, C, D].

    Pop D, record it, push F (A is seen). Stack [B, C, F].

    Pop F, record it, push C and G. Stack [B, C, C, G].

    Pop G, record it, push E. Stack [B, C, C, E].

    Pop E, record it, push B and C. Stack [B, C, C, B, C]. Pop C, record it; all its neighbours are seen. Pop B, record it. The remaining entries are already seen and are skipped.

    Output ADFGECB: (C). It is a depth-first order, but it takes neighbours from the end of each list. (A) is recursive DFS taking neighbours in list order, (B) is BFS, and (D) takes all of A’s neighbours before going deeper.

    An undirected graph has vertices 1 to 9 and edges 1–2, 1–3, 2–4, 2–5, 3–5, 3–6, 4–7, 5–7, 5–8, 6–8, 7–9, 8–9. BFS starts at vertex 1, and every adjacency list is in increasing order. What is the sum of the BFS distances from 1 to all nine vertices? And which vertex is the parent of 8 in the BFS tree?

    Run the queue by hand. A vertex’s parent is the vertex being dequeued at the moment it is first discovered, and the queue order decides who gets there first.

    Dequeue 1: discover 2, 3 (distance 1).

    Dequeue 2: discover 4, 5 (distance 2). Dequeue 3: 5 is already discovered; discover 6 (distance 2).

    Dequeue 4: discover 7 (distance 3, parent 4). Dequeue 5: 7 is already discovered; discover 8 (distance 3, parent 5). Dequeue 6: 8 is already discovered, even though 6–8 is an edge.

    Dequeue 7: discover 9 (distance 4). Then 8 and 9 discover nothing new.

    Distances: 0 + 1 + 1 + 2 + 2 + 2 + 3 + 3 + 4 = 18. The parent of 8 is 5, because 5 is dequeued before 6.

    A directed acyclic graph has vertices a, b, c, d, e, f and edges a→c, b→c, b→d, c→e, d→e, d→f. Which of the following is/are correct?

    1. The graph has exactly 14 topological orders
    2. a comes first in every topological order
    3. a, c, b, d, e, f is a topological order
    4. DFS that starts new searches in alphabetical order and takes neighbours in alphabetical order, listing vertices by decreasing finish time, gives b, d, f, a, c, e

    To count, leave f aside first: order a, b, c, d (with e after all of them), then count the places f can go after d.

    Without f: c needs a and b before it, d needs b, and e must come after c and d, so e is last of the five. The orders of a, b, c, d are abcd, abdc, bacd, badc, bdac: 5 of them.

    f only needs to come after d. Its free places after d: in abcd e, 2 places; in abdc e, 3; in bacd e, 2; in badc e, 3; in bdac e, 4. Total 2 + 3 + 2 + 3 + 4 = 14. (A) true.

    (B) false: b, a, … orders (and b, d, …) start with b; both a and b are sources. (C) false: c comes before b, but b→c is an edge.

    (D) DFS from a: a → c → e. e finishes, then c, then a. From b: c is already visited, so go to d; e is visited, so go to f. f finishes, then d, then b. Finish order e, c, a, f, d, b; reversed, b, d, f, a, c, e. It is a valid topological order. (D) true.

    Correct: A, D.

    • Follow the adjacency-list order exactly when simulating DFS; it decides the discovery order.
    • Check a topological order edge by edge.
    • Remember: BFS gives shortest paths only when edges are unweighted.
    • Expecting cross edges in an undirected DFS.
    • Assuming a DAG has a unique topological order.
    • Confusing “reachable from v” with “can reach v”.
    1. BFS (queue) visits by distance and gives unweighted shortest paths; DFS (stack or recursion) dives deep first. Both are O(V + E).
    2. Undirected DFS has only tree and back edges; a back edge means a cycle.
    3. A topological order puts every edge u → v with u first; it exists only for DAGs and is usually not unique.

    Which traversal finds the fewest-edges path from s to every vertex?

    DFS
    DFS can wander far before reaching nearby vertices.
    BFS
    It visits vertices in increasing distance.
    Either, always
    Only BFS guarantees it.

    A directed graph has a topological order if and only if

    it is connected
    Disconnected DAGs have topological orders too.
    it has no directed cycle
    A cycle would force a vertex to come before itself.
    every vertex has in-degree 1
    Unrelated.

    An adjacency matrix for a graph with V vertices uses

    O(V + E) space
    That’s an adjacency list.
    O(V²) space
    A V × V table regardless of how many edges exist.
    O(E) space
    The matrix has a cell for every pair of vertices.

    Shortest paths: BFS for hops, Dijkstra for weights

    For unweighted graphs BFS already gives shortest paths; with non-negative edge weights, Dijkstra’s algorithm repeatedly settles the closest unsettled vertex and relaxes its edges.

    The syllabus names “shortest path”. GATE has asked you to reason about what shortest-path facts imply about a graph’s edges (2025 Q58), and Dijkstra is a standard simulation question in GATE CS.

    It’s like planning the cheapest trip between the league’s five home cities: from your city, keep extending the cheapest route you’ve found so far until you’ve reached everywhere.

    Where it shows up in GATE DA

    Shortest-path reasoning; Dijkstra simulation is likely in future papers (it’s standard in GATE CS).

    2025 Q58 · which edges can’t exist2024 Q14 · d[u] in DFS questionsAI module · uniform-cost and A* search
    Heat: most years, 1–2 marks
    1. Set $d[s] = 0$ and $d[v] = \infty$ for every other vertex. Everything starts unsettled.
    2. Repeatedly pick the unsettled vertex $u$ with the smallest $d[u]$ and settle it (its distance is now final).
    3. Relax each edge $u \to v$ with weight $w$: if $d[u] + w \lt d[v]$, set $d[v] = d[u] + w$ and remember $u$ as $v$’s predecessor.

    With a priority queue it runs in $O((V + E)\log V)$. A negative edge weight can break it: a vertex settled early might later be reachable more cheaply. (Bellman–Ford handles negative weights in $O(VE)$.)

    • Any part of a shortest path is itself a shortest path between its endpoints.
    • Triangle inequality: $d(s, v) \le d(s, u) + w(u, v)$ for every edge $(u, v)$.
    • In an unweighted graph, an edge between $x$ and $y$ means $|d(s, x) - d(s, y)| \le 1$ for every source $s$. That’s the key to 2025 Q58.
    Try it

    The five home cities of the Data Premier League, with travel costs on the roads. Pick a starting city and step Dijkstra’s algorithm: the next city settled is always the closest unsettled one, and each step may lower the tentative distances of its neighbours. Notice that Gurugram’s cheapest route to Bengaluru isn’t the direct road.

    GATE DA 2025 · Q58 · MSQ · 2 marks

    Let G be a simple, unweighted, and undirected graph. A subset of the vertices and edges of G are shown below.

    The figure shows vertices a, b, c, d (top row) and e, f, g, h (bottom row), with edges a–b, b–c, c–d, e–f, f–g, g–h, a–f, f–c and c–h.

    It is given that a − b − c − d is a shortest path between a and d; e − f − g − h is a shortest path between e and h; a − f − c − h is a shortest path between a and h. Which of the following is/are NOT the edges of G?

    1. (b, d)
    2. (b, g)
    3. (b, h)
    4. (e, g)
    1. The given shortest paths fix three distances: $d(a, d) = 3$, $d(e, h) = 3$, $d(a, h) = 3$.

      A shortest path with 3 edges means no path with fewer exists.

    2. (b, d) would give the path a − b − d of length 2, contradicting $d(a, d) = 3$. Similarly (b, h) gives a − b − h of length 2, contradicting $d(a, h) = 3$; and (e, g) gives e − g − h of length 2, contradicting $d(e, h) = 3$. So none of (A), (C), (D) can be an edge.

      An extra edge can only shorten paths, never lengthen them.

    3. (b, g) creates no shortcut for the three given pairs (for example a − b − g − h still has length 3). It might or might not be an edge, so it isn’t “NOT an edge”. Answer: A, C, D.

      Official key: A; C; D.

    Using the widget’s road map (Gurugram–Nagpur 10, Gurugram–Bengaluru 23, Nagpur–Hyderabad 5, Nagpur–Bhubaneswar 7, Nagpur–Bengaluru 11, Hyderabad–Bengaluru 6, Hyderabad–Bhubaneswar 9), what is the shortest distance from Gurugram to Bengaluru?

    Compare the direct road with routes through Nagpur, and through Nagpur then Hyderabad.

    Direct: 23. Via Nagpur: 10 + 11 = 21. Via Nagpur and Hyderabad: 10 + 5 + 6 = 21. Shortest: 21 (two routes tie).

    In what order does Dijkstra’s algorithm, started at Gurugram, settle the cities?

    Settled in increasing order of final distance: Nagpur 10, Hyderabad 15, Bhubaneswar 17, Bengaluru 21.

    Gurugram (0), Nagpur (10), Hyderabad (15), Bhubaneswar (17), Bengaluru (21). Dijkstra always settles vertices in non-decreasing order of distance.

    In the 2025 Q58 graph (just the edges shown), what is the BFS distance from e to d?

    e − f − c − d.

    e is adjacent only to f; f is adjacent to c; c to d. So 3.

    What can happen if Dijkstra’s algorithm runs on a graph with a negative edge weight?

    Dijkstra assumes a settled distance can never improve later.

    A vertex settled early might later become reachable more cheaply through a negative edge, so Dijkstra may report wrong distances. Use Bellman–Ford instead.

    An undirected weighted graph has edges S–A 4, S–B 1, B–A 2, A–C 5, B–C 8, B–D 6, A–D 7, C–D 1, C–T 3, D–E 2, E–T 2. Run Dijkstra’s algorithm from S. What is the shortest distance from S to T, and how many different shortest paths from S to T are there?

    Settle vertices in order of distance. Whenever a relaxation gives a length equal to the current one, you have found a second shortest route into that vertex: keep a count of routes alongside each distance.

    Settle S (0): A = 4, B = 1.

    Settle B (1): A improves to 1 + 2 = 3; C = 9; D = 7.

    Settle A (3): C improves to 3 + 5 = 8 (route S–B–A–C); A–D gives 10, no better than 7.

    Settle D (7): C via D is 7 + 1 = 8, a tie, so C now has 2 shortest routes (S–B–A–C and S–B–D–C). E = 9.

    Settle C (8): T = 8 + 3 = 11, reached by C’s 2 routes. Settle E (9): T via E is 9 + 2 = 11, a tie, adding the route S–B–D–E–T.

    d(S, T) = 11, with 3 shortest paths: S–B–A–C–T, S–B–D–C–T and S–B–D–E–T. (Following the cheapest edge greedily, S–B then B–D, and stopping at the first route found misses the ties.)

    A directed graph has edges P→Q 2, P→R 6, Q→R 3, Q→S 8, Q→T 9, R→S 2, R→T 7, S→T 1, S→U 6, T→U 4. Dijkstra’s algorithm runs from P. Which of the following is/are correct?

    1. The vertices are settled in the order P, Q, R, S, T, U
    2. The shortest distance to U is 13, along P→Q→R→S→U
    3. T’s tentative distance takes the values ∞, 11, 8 in that order
    4. R’s tentative distance is set only once, to 6, because P is settled first

    Keep a row of tentative distances and update it each time a vertex is settled. A value changes only when the new route is strictly shorter.

    Settle P (0): Q = 2, R = 6.

    Settle Q (2): R improves to 5, S = 10, T = 11.

    Settle R (5): S improves to 7; R→T gives 12, not better than 11.

    Settle S (7): T improves to 8, U = 13. Settle T (8): U improves to 12. Settle U (12).

    (A) true. (B) false: U ends at 12, along P→Q→R→S→T→U; 13 was only a tentative value. (C) true: T was set to 11 by Q, left alone by R, and lowered to 8 by S. (D) false: R went from 6 to 5 when Q was settled.

    Correct: A, C.

    A directed graph has edges S→A 2, S→B 5, A→C 4, B→A −4, C→T 1, B→T 7. Dijkstra’s algorithm runs from S in its usual form: once a vertex is settled, its distance is never changed again. What distance does it report for T? What is the true shortest distance from S to T?

    Run the algorithm exactly as stated, including the moment when B’s edge points back into a vertex that is already settled. Then look for the cheapest path by hand, allowing the negative edge.

    Settle S (0): A = 2, B = 5.

    Settle A (2): C = 6.

    Settle B (5): B→A would give 5 − 4 = 1, but A is already settled, so it is ignored. B→T gives T = 12.

    Settle C (6): T improves to 7. Settle T (7). Dijkstra reports 7.

    True shortest path: S→B→A→C→T = 5 − 4 + 4 + 1 = 6. Dijkstra settled A at 2 before it had seen the cheaper route through B. Its correctness argument needs every edge weight to be non-negative; with a negative edge, use Bellman–Ford.

    • Use BFS for unweighted graphs and Dijkstra for non-negative weights.
    • Keep a table of tentative distances and update it after each settle.
    • To rule out an edge, show it would create a path shorter than a stated shortest path.
    • Running Dijkstra with negative weights.
    • Changing a distance after its vertex is settled.
    • Assuming the direct edge is always the shortest route.
    1. BFS gives fewest-edge paths; Dijkstra gives minimum-weight paths when all weights are non-negative.
    2. Dijkstra: settle the closest unsettled vertex, relax its edges, repeat; O((V + E) log V) with a heap.
    3. Shortest-path facts constrain the graph: an extra edge can only shorten paths.

    Dijkstra settles vertices in order of

    their labels
    Labels are irrelevant.
    non-decreasing distance from the source
    That’s the greedy step.
    their degree
    Degree doesn’t matter.

    In an unweighted graph, d(s, x) = 2 and d(s, y) = 5. Can there be an edge x–y?

    Yes
    That edge would give a path to y of length 3.
    No
    Adjacent vertices’ distances differ by at most 1.

    Which algorithm is simplest for shortest paths when all edges have weight 1?

    BFS
    Weight 1 everywhere means fewest edges = least weight.
    DFS
    DFS doesn’t find shortest paths.
    Bellman–Ford
    It works but is slower and unnecessary.

    Calling a function with a default lst=[] twice without arguments (each call appends one item) leaves the default list with

    1 item
    The default is shared across calls.
    2 items
    Mutable defaults accumulate.

    Bubble sort on [3, 1, 2] makes how many swaps?

    1
    Count inversions: (3, 1), (3, 2).
    2
    Two inversions.
    3
    (1, 2) is already in order.

    Pre-order A B D E C, in-order D B E A C. The root’s right child is

    B
    B is on the left of A in the in-order.
    C
    Only C lies right of A in the in-order list.
    E
    E is in A’s left subtree.

    A DFS of a directed graph finds a back edge. The graph

    has a cycle
    A back edge points to an ancestor on the current path, closing a cycle.
    is a DAG
    DAGs have no back edges.
    is disconnected
    Back edges say nothing about connectivity.

    An open-addressing table at load factor 0.75 needs at most how many probes on average to insert?

    1.33
    That’s 1/0.75. Use 1/(1 − α).
    4
    1/(1 − 0.75).
    0.75
    That’s α itself.
    Every module complete

    Every question, answered right.

    You worked through every quiz and every practice problem in GATE Data Science & AI. That took real effort, and the understanding is yours to keep. Add your name to make a certificate.