chapter
    Programming and Data Structures PYQs for GATE CS

    GATE CS Programming and Data Structures: 7 chapters, 66 previous year questions (100% of Programming and Data Structures), 563 practice questions and one solv

    A question from this chapter

    Question 1
    2026 Slot Set2 PYQ
    Level 3: Exam Standard
    Consider the following three ANSI-C programs, P1, P2, and P3.

    P1P2P3
    #include <stdio.h>
    int a=5;
    int main(){
      int a=7;
      return(0);
    }
    #include <stdio.h>
    int main(){
      int a=5;
      int a=7;
      return(0);
    }
    #include <stdio.h>
    int main(){
      int a=5;
      float a=7;
      return(0);
    }


    Which one of the following statements is true?
    Question 2
    2026 Slot Set2 PYQ
    Level 3: Exam Standard

    In C runtime environment, which one of the following is stored in heap?

    Question 3
    2021 Slot Set2 PYQ
    Level 3: Exam Standard
    Consider the following ANSI C program.

    #include <stdio.h>

    int foo(int x, int y, int q)
    {
        if ((x <= 0) && (y <= 0))
            return q;
        if (x <= 0)
            return foo(x, y-q, q);
        if (y <= 0)
            return foo(x-q, y, q);
        return foo(x, y-q, q) + foo(x-q, y, q);
    }

    int main()
    {
        int r = foo(15,15,10);
        printf("%d", r);
        return 0;
    }

    The output of the program upon execution is __________.
    Question 4
    2026 Slot Set2 PYQ
    Level 3: Exam Standard
    Consider a stack and a queue . Both of them are initially empty and have the capacity to store ten elements each. The elements 1, 2, 3, 4, and 5 arrive one by one, in that order. When an element arrives, it is assigned either to (pushed on ) or to (enqueued to ). Once all the five elements are stored, the output is generated in two steps. First, stack S is emptied by popping all elements. Then queue is emptied by dequeueing all elements. The output obtained by following this process is 4 3 1 2 5 .
    Given the output, the objective is to predict whether an element was assigned to or .

    Which of the following options is/are possible valid assignment(s) of the elements?

    Note: In the options, the notation denotes that element was assigned to and denotes that element was assigned to .
    Question 5
    2026 Slot Set2 PYQ
    Level 3: Exam Standard
    The set T represents various traversals over binary tree. The set S represents the order of visiting nodes during a traversal.

    TS
    I: InorderL: left subtree, node, right subtree
    II: PreorderM: node, left subtree, right subtree
    III: PostorderN: left subtree, right subtree, node


    Which one of the following is the correct match from T to S ?
    Question 6
    2025 Slot Set1 PYQ
    Level 3: Exam Standard
    The height of any rooted tree is defined as the maximum number of edges in the path from the root node to any leaf node.

    Suppose a Min-Heap stores 32 keys. The height of is _____________. (Answer in integer)
    Question 7
    2026 Slot Set2 PYQ
    Level 4: Challenger

    The keys are inserted into a hash table using the hash function . The collisions are resolved by chaining. After all the keys are inserted, the length of the longest chain is __________. <i>(answer in integer)</i>

    Free preview ends here

    Login to view the complete previous-year questions and solutions

    Creating an account is free. You get the rest of this chapter, step-by-step solutions, and a study plan built around the topics you are actually weak at.

    Why MastersUp

    Personalised first. High quality throughout.

    Most platforms hand everyone the same content. Here the content moves with your performance, topic by topic.

    Built around you, not around a syllabus PDF

    Every answer you give moves your topic-level intelligence rate. The next question, the next revision card and tomorrow's plan all change with it.

    Revision that hits your weak spots

    We only revise topics you have actually attempted and are still below the safe bar on — never the same chapter on repeat.

    Questions calibrated to the real exam

    Each question carries a measured toughness. You are served a rung above your current level, so practice keeps stretching you.

    Notes written for recall, not for volume

    Full lesson cards for first study, curated short-note cards for the last mile — with derivations, traps and exam patterns marked.

    One place for everything

    Notes, chapter practice, previous-year questions, test series and full-length papers — all feeding one picture of your preparation.

    Honest progress

    No vanity streaks. Progress here means chapters mastered and accuracy that held up on harder questions.

    Unlock the whole course

    Full notes and short notes, the complete question bank with worked solutions, mock tests, full-length papers, and an adaptive plan that rebuilds itself as you improve.

    Programming and Data Structures PYQs for GATE CS

    GATE CS Programming and Data Structures: 7 chapters, 66 previous year questions (100% of Programming and Data Structures), 563 practice questions and one solved question from each chapter.

    About Programming and Data Structures Previous Year Questions (PYQs)

    66 previous year questions from Programming and Data Structures in GATE CS, grouped by chapter with the exam year, answer key and step-by-step solution for each.

    Programming and Data Structures Weightage in GATE CS

    Programming and Data Structures accounts for 66 of 66 Programming and Data Structures previous year questions in our bank (100%), about 6.6 per paper across 10 papers.

    Programming and Data Structures Chapter Matrix

    ChapterTopicsPYQsShare of unit PYQsPractice questions
    C Programming, Control Flow and Array AlgorithmsLoop Tracing and Iterative Computation, Function Calls, Evaluation Order and Static State, Bitwise and Character Expressions, Array Processing and Iterative Algorithms, Variable Scope, Shadowing and Compilation1320%193
    Pointers, Arrays, Strings and Memory ManagementPointer Assignment, Dereferencing and Arithmetic, Strings and Character Pointers, Multidimensional Arrays and Memory Layout, Runtime Memory and Dynamic Allocation1015%153
    Recursion and Recursive Program AnalysisRecursive Array and String Traversal, Recursive Arithmetic Algorithms, Nested Recursion and Return-Value Analysis69%0
    Stacks, Queues and Linked ListsStack Operations and Augmented Stacks, Queue Operations, Reversal and Stack-Queue Interaction, Linked List Manipulation, Recursion and Complexity1117%60
    Binary Trees, Binary Search Trees and TraversalsBinary Tree Structure, Height and Node Counts, Binary Search Tree Construction and Ordering Properties, Tree Traversals and Recursive Tree Processing, Complete Binary Search Trees in Array Representation1320%127
    Heaps, Priority Queues and Data Structure OperationsHeap Structure, Height and Leaf Positions, Heap Construction and Array Validation, Priority Queue Operations and Heap Extrema, Meld Operations and Data Structure Complexity812%30
    Hashing and Collision ResolutionOpen Addressing and Probe Sequences, Uniform Hashing and Expected Load, Dynamic Hashing and Collision Buckets, Separate Chaining and Chain Length58%0

    More from Programming and Data Structures

    One Solved Question from Each Programming and Data Structures Chapter

    Question 1 · C Programming, Control Flow and Array Algorithms · 2026_Set2 MCQ
    Consider the following three ANSI-C programs, P1, P2, and P3.

    P1P2P3
    #include <stdio.h>
    int a=5;
    int main(){
      int a=7;
      return(0);
    }
    #include <stdio.h>
    int main(){
      int a=5;
      int a=7;
      return(0);
    }
    #include <stdio.h>
    int main(){
      int a=5;
      float a=7;
      return(0);
    }


    Which one of the following statements is true?
    1. A.

      Only P1 will compile without any error

    2. B.

      Only P2 will compile without any error

    3. C.

      Only P3 will compile without any error

    4. D.

      All three programs P1, P2, and P3 will compile without any error

    Correct Answer:

    A

    Step-by-Step Solution

    Insight: C allows variable shadowing across different scopes but forbids redeclaration within the same scope, regardless of type.

    Exam route: Check the scope of each variable declaration. Global vs local is shadowing. Two locals in the same block is redeclaration.

    Learning route:

    1. P1: int a=5; is at file scope. int a=7; is inside main (block scope). The local a shadows the global a. This is perfectly valid C and compiles without error.
    2. P2: int a=5; and int a=7; are both declared inside the exact same block scope (main). This is a redeclaration error. The compiler will reject it.
    3. P3: int a=5; and float a=7; are both in the same block scope. Even though the types differ, C does not allow overloading or redeclaration with different types in the same scope. This is a compilation error.
    4. Therefore, only P1 compiles successfully.

    Trap: Believing that shadowing causes a compilation error or that different types in the same scope are allowed. Shadowing is strictly cross-scope; redeclaration is strictly intra-scope.

    Verification: Compile P1 mentally: global a exists, local a hides it. No conflict. P2: compiler sees two as in main's symbol table -> error. P3: same symbol table, conflicting types -> error.

    Question 2 · Pointers, Arrays, Strings and Memory Management · 2026_Set2 MCQ

    In C runtime environment, which one of the following is stored in heap?

    1. A.

      A static variable declared inside a function

    2. B.

      An array of integers declared inside a function

    3. C.

      A dynamically allocated array of integers created using malloc() function call

    4. D.

      Return address of a function

    Correct Answer:

    C

    Step-by-Step Solution

    Insight: This is a memory layout classification question, recognizable by asking where specific C constructs reside in the runtime environment.

    Exam route: Eliminate options based on standard C memory segments. Static variables go to Data/BSS. Local arrays and return addresses go to Stack. Only malloc targets the Heap.

    Learning route:

    1. Static variable inside a function: Stored in the Data segment (or BSS if uninitialized), not the Heap.
    2. Array of integers declared inside a function: This is a local variable, allocated on the Stack.
    3. Dynamically allocated array using malloc(): Explicitly requests memory from the Heap at runtime.
    4. Return address of a function: Pushed onto the Stack as part of the function call frame.

    Therefore, only the dynamically allocated array resides in the Heap.

    Question 3 · Recursion and Recursive Program Analysis · 2021_Set2 NAT
    Consider the following ANSI C program.

    #include <stdio.h>

    int foo(int x, int y, int q)
    {
        if ((x <= 0) && (y <= 0))
            return q;
        if (x <= 0)
            return foo(x, y-q, q);
        if (y <= 0)
            return foo(x-q, y, q);
        return foo(x, y-q, q) + foo(x-q, y, q);
    }

    int main()
    {
        int r = foo(15,15,10);
        printf("%d", r);
        return 0;
    }

    The output of the program upon execution is __________.
    Correct Answer:

    60.00

    Step-by-Step Solution

    Insight: The function acts as a path counter on a 2D grid, stepping by in either the or direction, with base cases returning when both coordinates drop to .

    Exam route: Trace the recursive tree for foo(15, 15, 10). Notice the symmetric reduction and how boundary conditions collapse the tree into simple additions of the constant .

    Learning route:

    1. This is a multi-variable path counting question, recognisable by two coordinate arguments reducing independently in separate recursive branches.
    2. The function foo(x, y, q) has constant q = 10. Let's trace f(x, y) = foo(x, y, 10).
    3. Base cases:
    • If and , return .
    • If , return .
    • If , return .
    1. Recursive step: If and , return .
    2. Calculate :
    1. Calculate :
    • : Since , it returns .
    • .
    • So, .
    1. Calculate :
    • By symmetry, .
    1. Final result: .
    Question 4 · Stacks, Queues and Linked Lists · 2026_Set2 MSQ
    Consider a stack and a queue . Both of them are initially empty and have the capacity to store ten elements each. The elements 1, 2, 3, 4, and 5 arrive one by one, in that order. When an element arrives, it is assigned either to (pushed on ) or to (enqueued to ). Once all the five elements are stored, the output is generated in two steps. First, stack S is emptied by popping all elements. Then queue is emptied by dequeueing all elements. The output obtained by following this process is 4 3 1 2 5 .
    Given the output, the objective is to predict whether an element was assigned to or .

    Which of the following options is/are possible valid assignment(s) of the elements?

    Note: In the options, the notation denotes that element was assigned to and denotes that element was assigned to .
    1. A.

    2. B.

    3. C.

    4. D.

    Correct Answer:

    ["A","B"]

    Step-by-Step Solution

    Insight: This is a stack-queue stream splitting question, recognizable because it asks to deduce the routing of elements into a stack and a queue given the final concatenated output.

    Exam route: Partition the output into a stack segment (reversed arrival) and a queue segment (original arrival), then interleave them to match 1, 2, 3, 4, 5.

    Learning route:

    Step 1: The final output is 4, 3, 1, 2, 5. This is formed by emptying the stack (LIFO) followed by emptying the queue (FIFO).

    Step 2: We must partition the output into a stack segment and a queue segment.

    Partition A: Stack outputs 4, 3, 1. Queue outputs 2, 5.

    For the stack to output 4, 3, 1, the elements must have been pushed in the order 1, 3, 4.

    For the queue to output 2, 5, the elements must have been enqueued in the order 2, 5.

    Interleaving 1, 3, 4 and 2, 5 to match the arrival order 1, 2, 3, 4, 5 gives: 1->S, 2->Q, 3->S, 4->S, 5->Q. This matches option A.

    Partition B: Stack outputs 4, 3. Queue outputs 1, 2, 5.

    For the stack to output 4, 3, the elements must have been pushed in the order 3, 4.

    For the queue to output 1, 2, 5, the elements must have been enqueued in the order 1, 2, 5.

    Interleaving 3, 4 and 1, 2, 5 to match 1, 2, 3, 4, 5 gives: 1->Q, 2->Q, 3->S, 4->S, 5->Q. This matches option B.

    Step 3: Verify other partitions. If stack outputs 4, queue outputs 3, 1, 2, 5. The queue arrival order would be 3, 1, 2, 5, which violates the increasing arrival order. Thus, only A and B are valid.

    Question 5 · Binary Trees, Binary Search Trees and Traversals · 2026_Set2 MCQ
    The set T represents various traversals over binary tree. The set S represents the order of visiting nodes during a traversal.

    TS
    I: InorderL: left subtree, node, right subtree
    II: PreorderM: node, left subtree, right subtree
    III: PostorderN: left subtree, right subtree, node


    Which one of the following is the correct match from T to S ?
    1. A.

      I – L, II – M, III – N

    2. B.

      I – M, II – L, III – N

    3. C.

      I – N, II – M, III – L

    4. D.

      I – L, II – N, III – M

    Correct Answer:

    A

    Step-by-Step Solution

    Insight: The names of the traversals (pre, in, post) directly indicate the position of the current node relative to its subtrees.

    Exam route: Preorder = Node first (pre). Inorder = Node in the middle (in). Postorder = Node last (post). Match these to the given descriptions: I (Inorder) is L (left, node, right). II (Preorder) is M (node, left, right). III (Postorder) is N (left, right, node). This matches option A.

    Learning route:

    1. Depth-first traversals are defined by when the current node is processed relative to its left and right subtrees.
    2. Preorder: The prefix "pre" means the node is visited before its subtrees. Order: Node, Left, Right (M).
    3. Inorder: The prefix "in" means the node is visited in between its left and right subtrees. Order: Left, Node, Right (L).
    4. Postorder: The prefix "post" means the node is visited after both subtrees. Order: Left, Right, Node (N).
    5. Matching these definitions to the given set S yields I-L, II-M, III-N.

    Verification: Consider a tree with root A, left B, right C. Preorder visits A, then B, then C (Node, Left, Right). Inorder visits B, then A, then C (Left, Node, Right). Postorder visits B, then C, then A (Left, Right, Node). This perfectly matches M, L, N respectively.

    Question 6 · Heaps, Priority Queues and Data Structure Operations · 2025_Set1 NAT
    The height of any rooted tree is defined as the maximum number of edges in the path from the root node to any leaf node.

    Suppose a Min-Heap stores 32 keys. The height of is _____________. (Answer in integer)
    Correct Answer:

    5.00

    Step-by-Step Solution

    Insight: This is a direct application of the heap height formula. The height of a complete binary tree with nodes is simply .

    Exam route: The problem states the min-heap stores 32 keys. Using the height formula , we substitute . Since , . The floor of 5 is 5. The height is 5.

    Learning route:

    1. Understand the definition: The height of a rooted tree is the maximum number of edges on any path from the root to a leaf.
    2. Recall the structure of a heap: A heap is a complete binary tree. This means all levels except possibly the last are completely full, and the last level is filled from left to right.
    3. Apply the formula: For a complete binary tree with nodes, the height is given by .
    4. Calculate: Here, . We know that , so .
    5. Conclusion: The height of the min-heap is 5.
    Question 7 · Hashing and Collision Resolution · 2026_Set2 NAT

    The keys are inserted into a hash table using the hash function . The collisions are resolved by chaining. After all the keys are inserted, the length of the longest chain is __________. <i>(answer in integer)</i>

    Correct Answer:

    3.00

    Step-by-Step Solution

    Insight: Separate chaining appends colliding keys to a linked list at the hashed index; the longest chain is simply the maximum bucket size.

    Exam route: Compute for all 9 keys, tally the frequencies of each remainder, and pick the maximum frequency.

    Learning route:

    The hash function is .

    Compute the bucket for each key:

    Tallying the remainders:

    • Index 0: 0 keys
    • Index 1: 28, 19, 10 (3 keys)
    • Index 2: 0 keys
    • Index 3: 12 (1 key)
    • Index 4: 0 keys
    • Index 5: 5 (1 key)
    • Index 6: 15, 33 (2 keys)
    • Index 7: 0 keys
    • Index 8: 26, 17 (2 keys)

    The maximum number of keys in any bucket is 3 (at index 1).

    Thus, the length of the longest chain is 3.

    Tempting wrong path: A student might count the total number of collisions instead of the maximum chain length. There are 4 collisions (28 collides with 19, 10 collides with them, 33 collides with 15, 17 collides with 26), leading to an answer of 4. This breaks down because "longest chain" refers to the maximum bucket size, not the sum of collisions.

    Generalization: In separate chaining, the chain length at any index is exactly the frequency of that hash value.

    Verification: Re-checking , , . All correctly map to 1. No other bucket has 3 or more keys.