GLA University Β· 2025-26 END TERM
DSA LAB END TERM Β· EVEN SEM 2025-26

Master Every Topic,
Ace the Lab Exam.

Complete prep guide covering all 5 syllabus topics: Arrays, Strings, Linked List, Stack & Queue, and Trees β€” with Java code, dry-run traces, and quizzes.

120 Min Exam 50 MCQ + 3 Coding 2 Easy + 1 Medium Language: Java BYOD Mode

βœ…Your Readiness Tracker

0/0 topics ready

TOPIC 01
EASY–MED

πŸ“¦ Arrays

Traversal, Insertion, Deletion, Linear & Binary Search, Bubble & Selection Sort, Sliding Window.

TOPIC 02
EASY

πŸ”€ Strings

String & character functions, traversal, palindrome, anagram, reverse, vowels.

TOPIC 03
MEDIUM

πŸ”— Linked List

Singly, Doubly, Circular LL β€” insert at beginning/end, delete first/last, count nodes.

TOPIC 04
MEDIUM

πŸ“š Stack & Queue

Push/Pop/Peek, Infix→Postfix, Postfix eval, Enqueue/Dequeue, Circular Queue, Deque.

TOPIC 05
MEDIUM

🌳 Trees

Binary Tree, BST, Preorder/Inorder/Postorder, Height, Count Nodes, Same Tree.

PRACTICE
MCQ + CODE

🧠 Quiz

Topic-wise MCQs covering all 5 units. Instant feedback and explanations.

πŸ“ŒExam Pattern Reminder

50 MCQs

Covers all 5 topics. Each question tests concept, code output, or complexity. Time budget: ~60 min.

2 Easy Coding Qs

Array/String/LL basics. Direct implementation. Time budget: ~20 min each.

1 Medium Coding Q

Stack application, Tree traversal, or Sliding Window. Time budget: ~20 min.

Language: Java

BYOD β€” bring your own device. Use Scanner for input. Always write Time & Space complexity.

πŸ“¦Array Basics & Traversal

An array stores elements of the same type in contiguous memory. Index starts at 0.

Java β€” Declare, Input, Reverse
import java.util.Scanner;

public class ArrayBasics {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] arr = new int[n];

        // Input
        for (int i = 0; i < n; i++) arr[i] = sc.nextInt();

        // Reverse an Array
        int left = 0, right = n - 1;
        while (left < right) {
            int temp = arr[left];
            arr[left++] = arr[right];
            arr[right--] = temp;
        }

        // Print
        for (int x : arr) System.out.print(x + " ");
    }
}
Check if Palindrome: Compare arr[i] with arr[n-1-i] for i from 0 to n/2. If all match β†’ palindrome.

πŸ”Linear & Binary Search

Java β€” Linear Search
int linearSearch(int[] arr, int target) {
    for (int i = 0; i < arr.length; i++)
        if (arr[i] == target) return i;
    return -1; // not found
} // Time: O(n) | Space: O(1)
Java β€” Binary Search (sorted array)
int binarySearch(int[] arr, int target) {
    int left = 0, right = arr.length - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2; // safe mid
        if (arr[mid] == target) return mid;
        else if (arr[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    return -1;
} // Time: O(log n) | Space: O(1)
Binary Search Trace: arr=[1,3,5,7,9,11], target=7
step 1left=0, right=5, mid=2 β†’ arr[2]=5 < 7 β†’ left=3
step 2left=3, right=5, mid=4 β†’ arr[4]=9 > 7 β†’ right=3
step 3left=3, right=3, mid=3 β†’ arr[3]=7 βœ“ return 3
⚠️ Binary Search only works on sorted arrays! Always confirm sorted before applying.

πŸ”ƒBubble Sort & Selection Sort

Java β€” Bubble Sort
void bubbleSort(int[] arr) {
    int n = arr.length;
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp; // swap
            }
        }
    }
} // Time: O(nΒ²) | Space: O(1)
Java β€” Selection Sort
void selectionSort(int[] arr) {
    int n = arr.length;
    for (int i = 0; i < n - 1; i++) {
        int minIdx = i;
        for (int j = i + 1; j < n; j++)
            if (arr[j] < arr[minIdx]) minIdx = j;
        // swap arr[i] with arr[minIdx]
        int temp = arr[minIdx];
        arr[minIdx] = arr[i];
        arr[i] = temp;
    }
} // Time: O(nΒ²) | Space: O(1)
Key Difference:
Bubble Sort: compares adjacent elements, bubbles max to end each pass.
Selection Sort: finds minimum in unsorted part, places it at beginning.

πŸ‘ˆπŸ‘‰Two Pointer Technique

Use two pointers from opposite ends or moving together to solve array problems in O(n).

Java β€” Two Sum II (sorted array)
int[] twoSum(int[] arr, int target) {
    int left = 0, right = arr.length - 1;
    while (left < right) {
        int sum = arr[left] + arr[right];
        if (sum == target) return new int[]{left, right};
        else if (sum < target) left++;
        else right--;
    }
    return new int[]{-1, -1};
} // Time: O(n) | Space: O(1)
Java β€” Move Zeroes
void moveZeroes(int[] arr) {
    int j = 0; // pointer for next non-zero position
    for (int i = 0; i < arr.length; i++)
        if (arr[i] != 0) arr[j++] = arr[i];
    while (j < arr.length) arr[j++] = 0;
} // Time: O(n) | Space: O(1)
Java β€” Remove Duplicates from Sorted Array
int removeDuplicates(int[] arr) {
    if (arr.length == 0) return 0;
    int j = 1;
    for (int i = 1; i < arr.length; i++)
        if (arr[i] != arr[i - 1]) arr[j++] = arr[i];
    return j; // new length
} // Time: O(n) | Space: O(1)

πŸͺŸSliding Window of Size K ⭐

Fix window size K. Slide it across the array. Track sum/max. Avoids O(nΒ·k) brute force.

Java β€” Sum / Average / Max of Subarray Size K
void slidingWindow(int[] arr, int k) {
    int n = arr.length;
    if (n < k) { System.out.println("Invalid"); return; }

    int windowSum = 0;
    // Build first window
    for (int i = 0; i < k; i++) windowSum += arr[i];

    int maxSum = windowSum;

    // Slide window
    for (int i = k; i < n; i++) {
        windowSum += arr[i] - arr[i - k]; // add new, remove old
        maxSum = Math.max(maxSum, windowSum);
        System.out.println("Window ["+(i-k+1)+","+i+"] Sum="+windowSum);
    }
    System.out.println("Max Sum = " + maxSum);
} // Time: O(n) | Space: O(1)
Trace: arr=[2,1,5,1,3,2], k=3
initwindowSum = 2+1+5 = 8
i=3+arr[3]=1, -arr[0]=2 β†’ sum=7 [1,5,1]
i=4+arr[4]=3, -arr[1]=1 β†’ sum=9 [5,1,3] βœ“MAX
i=5+arr[5]=2, -arr[2]=5 β†’ sum=6 [1,3,2]
Max Sum = 9 βœ“

πŸ“All Practice Problems (Quick Reference)

10 Questions from Syllabus:

1. Reverse an Array β€” two pointer swap
2. Check if Array is Palindrome β€” compare left & right
3. Two Sum II (Sorted Array) β€” two pointers
4. Remove Duplicates from Sorted Array β€” two pointers
5. Move Zeroes β€” partition technique
6. Sum of Subarray of Size K β€” sliding window
7. Average of Subarray of Size K β€” sum / k each slide
8. Maximum Element in Subarray of Size K β€” track max
9. Count Subarrays of Size K β€” n - k + 1
10. Find All Anagrams in a String β€” frequency map + sliding window
Java β€” Count Subarrays of Size K
// Number of subarrays of exactly size k = n - k + 1
int countSubarrays(int n, int k) {
    return n >= k ? n - k + 1 : 0;
}

πŸ”€String Basics in Java

Strings are immutable in Java. Use StringBuilder for efficient modification.

Java β€” Common String Methods
String s = "Hello World";
s.length();          // 11
s.charAt(0);         // 'H'
s.toUpperCase();     // "HELLO WORLD"
s.toLowerCase();     // "hello world"
s.substring(6);      // "World"
s.substring(0,5);   // "Hello"
s.trim();             // removes leading/trailing spaces
s.replace('l','x'); // "Hexxo Worxd"
s.contains("World");// true
s.split(" ");        // ["Hello","World"]
s.toCharArray();     // char array

// Character utility methods
Character.isLetter('a');    // true
Character.isDigit('3');     // true
Character.isUpperCase('A'); // true
Character.toLowerCase('A');// 'a'

πŸ”Reverse a String & Check Palindrome

Java β€” Reverse a String
String reverse(String s) {
    return new StringBuilder(s).reverse().toString();
}

// Manual approach:
String reverseManual(String s) {
    char[] ch = s.toCharArray();
    int l = 0, r = ch.length - 1;
    while (l < r) {
        char temp = ch[l]; ch[l++] = ch[r]; ch[r--] = temp;
    }
    return new String(ch);
}
Java β€” Check Palindrome String
boolean isPalindrome(String s) {
    int l = 0, r = s.length() - 1;
    while (l < r) {
        if (s.charAt(l++) != s.charAt(r--)) return false;
    }
    return true;
}

πŸ”‘Count Vowels, Reverse Vowels, Count Occurrence

Java β€” Count Vowels & Consonants
void countVC(String s) {
    s = s.toLowerCase();
    int vowels = 0, consonants = 0;
    for (char c : s.toCharArray()) {
        if ("aeiou".indexOf(c) >= 0) vowels++;
        else if (Character.isLetter(c)) consonants++;
    }
    System.out.println("Vowels: "+vowels+", Consonants: "+consonants);
}
Java β€” Reverse Vowels of String
String reverseVowels(String s) {
    char[] ch = s.toCharArray();
    int l = 0, r = ch.length - 1;
    String vowels = "aeiouAEIOU";
    while (l < r) {
        while (l < r && vowels.indexOf(ch[l]) < 0) l++;
        while (l < r && vowels.indexOf(ch[r]) < 0) r--;
        char tmp = ch[l]; ch[l++] = ch[r]; ch[r--] = tmp;
    }
    return new String(ch);
}
Java β€” Count Occurrence & Remove Spaces
int countOccurrence(String s, char target) {
    int count = 0;
    for (char c : s.toCharArray()) if (c == target) count++;
    return count;
}

String removeSpaces(String s) {
    return s.replace(" ", "");
    // or: s.replaceAll("\\s+", "")
}

πŸ“Reverse Each Word of String

Java β€” Reverse Each Word
String reverseEachWord(String s) {
    String[] words = s.trim().split("\\s+");
    StringBuilder sb = new StringBuilder();
    for (String w : words) {
        sb.append(new StringBuilder(w).reverse()).append(' ');
    }
    return sb.toString().trim();
}
// "hello world" β†’ "olleh dlrow"
Example: Input: "I love Java" β†’ Output: "I evol avaJ"

πŸ”€Anagram Check (Find All Anagrams)

Two strings are anagrams if they have the same character frequencies.

Java β€” Check if Two Strings are Anagram
boolean isAnagram(String s, String t) {
    if (s.length() != t.length()) return false;
    int[] freq = new int[26];
    for (int i = 0; i < s.length(); i++) {
        freq[s.charAt(i) - 'a']++;
        freq[t.charAt(i) - 'a']--;
    }
    for (int f : freq) if (f != 0) return false;
    return true;
} // Time: O(n) | Space: O(1)

πŸ”—Linked List Node Structure

Java β€” Node & LinkedList Class
class Node {
    int data;
    Node next;
    Node(int data) {
        this.data = data;
        this.next = null;
    }
}

class LinkedList {
    Node head = null;

    // Traverse and print
    void display() {
        Node curr = head;
        while (curr != null) {
            System.out.print(curr.data + " β†’ ");
            curr = curr.next;
        }
        System.out.println("null");
    }
}
3 Golden Rules:
1. Always check null before accessing .next or .data
2. Save the next pointer before modifying links
3. Draw the list on paper before writing code

βž•Insert at Beginning & End

Java β€” Insert at Beginning
void insertAtBeginning(int data) {
    Node newNode = new Node(data);
    newNode.next = head; // point to old head
    head = newNode;      // update head
} // Time: O(1)
Java β€” Insert at End
void insertAtEnd(int data) {
    Node newNode = new Node(data);
    if (head == null) { head = newNode; return; }
    Node curr = head;
    while (curr.next != null) curr = curr.next;
    curr.next = newNode; // link last node to new
} // Time: O(n)
Insert 5 at Beginning: head→1→2→3→null
step 1newNode(5).next = head (1)
step 2head = newNode(5)
Result: headβ†’5β†’1β†’2β†’3β†’null βœ“

βž–Delete First & Last Node

Java β€” Delete First Node
void deleteFirst() {
    if (head == null) { System.out.println("Empty list"); return; }
    head = head.next; // move head forward
} // Time: O(1)
Java β€” Delete Last Node
void deleteLast() {
    if (head == null) return;
    if (head.next == null) { head = null; return; } // only 1 node
    Node curr = head;
    while (curr.next.next != null) curr = curr.next;
    curr.next = null; // disconnect last node
} // Time: O(n)

πŸ”’Count Number of Nodes

Java β€” Count Nodes
int countNodes() {
    int count = 0;
    Node curr = head;
    while (curr != null) {
        count++;
        curr = curr.next;
    }
    return count;
} // Time: O(n) | Space: O(1)
βœ… Complete SLL implementation β€” combine Node class + all 5 methods above for exam.

↔️Doubly Linked List

Each node has both next and prev pointers.

Java β€” Doubly Linked List Node & Insert
class DNode {
    int data;
    DNode next, prev;
    DNode(int data) { this.data = data; }
}

// Insert at beginning of DLL
DNode insertFront(DNode head, int data) {
    DNode node = new DNode(data);
    node.next = head;
    if (head != null) head.prev = node;
    return node; // new head
}

// Delete a node in DLL
void deleteNode(DNode node) {
    if (node.prev != null) node.prev.next = node.next;
    if (node.next != null) node.next.prev = node.prev;
}

πŸ”„Circular Linked List

Last node points back to head. No null at end.

Java β€” Circular LL Insert & Traverse
// Insert at end of Circular LL
Node insertCircular(Node head, int data) {
    Node node = new Node(data);
    if (head == null) { node.next = node; return node; }
    Node curr = head;
    while (curr.next != head) curr = curr.next;
    curr.next = node;
    node.next = head; // circular link
    return head;
}

// Traverse Circular LL
void displayCircular(Node head) {
    if (head == null) return;
    Node curr = head;
    do {
        System.out.print(curr.data + " β†’ ");
        curr = curr.next;
    } while (curr != head);
    System.out.println("(back to head)");
}
⚠️ Always use do-while loop for circular LL traversal to ensure head is visited!

πŸ“šStack β€” Array Based Implementation

LIFO: Last In, First Out. Top tracks the latest element.

Java β€” Stack using Array
class Stack {
    int[] arr;
    int top = -1;
    int capacity;

    Stack(int size) { arr = new int[size]; capacity = size; }

    void push(int val) {
        if (top == capacity - 1) { System.out.println("Stack Overflow"); return; }
        arr[++top] = val;
    }

    int pop() {
        if (top == -1) { System.out.println("Stack Underflow"); return -1; }
        return arr[top--];
    }

    int peek() {
        if (top == -1) return -1;
        return arr[top];
    }

    boolean isEmpty() { return top == -1; }
    boolean isFull()  { return top == capacity - 1; }
}

βœ…Valid Parentheses ⭐ (Most Important Stack Q)

Java β€” Valid Parentheses
boolean isValid(String s) {
    Stack<Character> stack = new Stack<>();
    for (char c : s.toCharArray()) {
        if (c == '(' || c == '[' || c == '{')
            stack.push(c);
        else {
            if (stack.isEmpty()) return false;
            char top = stack.pop();
            if (c == ')' && top != '(') return false;
            if (c == ']' && top != '[') return false;
            if (c == '}' && top != '{') return false;
        }
    }
    return stack.isEmpty(); // must be empty at end
}
Trace: "({[]})"
'('push β†’ stack: ['(']
'{'push β†’ stack: ['(', '{']
'['push β†’ stack: ['(', '{', '[']
']'pop '[' β†’ match βœ“ stack: ['(', '{']
'}'pop '{' β†’ match βœ“ stack: ['(']
')'pop '(' β†’ match βœ“ stack: []
Stack empty β†’ return true βœ“

πŸ“ˆNext Greater Element

For each element, find the first element to its right that is greater. Use monotonic stack.

Java β€” Next Greater Element
int[] nextGreater(int[] arr) {
    int n = arr.length;
    int[] result = new int[n];
    Arrays.fill(result, -1); // default: no greater element
    Deque<Integer> stack = new ArrayDeque<>();

    for (int i = 0; i < n; i++) {
        // Pop elements smaller than current
        while (!stack.isEmpty() && arr[stack.peek()] < arr[i])
            result[stack.pop()] = arr[i];
        stack.push(i);
    }
    return result;
} // Time: O(n) | Space: O(n)
Example: [4, 5, 2, 10, 8]
NGE: [5, 10, 10, -1, -1]

πŸ“Infix to Postfix Conversion

Convert a+b*c β†’ abc*+. Use operator precedence and stack.

Java β€” Infix to Postfix
int prec(char op) {
    if (op == '+' || op == '-') return 1;
    if (op == '*' || op == '/') return 2;
    return 0;
}

String infixToPostfix(String exp) {
    StringBuilder result = new StringBuilder();
    Stack<Character> stack = new Stack<>();
    for (char c : exp.toCharArray()) {
        if (Character.isLetterOrDigit(c)) {
            result.append(c);
        } else if (c == '(') {
            stack.push(c);
        } else if (c == ')') {
            while (!stack.isEmpty() && stack.peek() != '(')
                result.append(stack.pop());
            stack.pop(); // remove '('
        } else { // operator
            while (!stack.isEmpty() && prec(stack.peek()) >= prec(c))
                result.append(stack.pop());
            stack.push(c);
        }
    }
    while (!stack.isEmpty()) result.append(stack.pop());
    return result.toString();
}
// "a+b*c" β†’ "abc*+"

🚢Queue β€” Array Based (FIFO)

Java β€” Queue using Array
class Queue {
    int[] arr;
    int front = 0, rear = -1, size = 0, capacity;

    Queue(int cap) { arr = new int[cap]; capacity = cap; }

    void enqueue(int val) {
        if (size == capacity) { System.out.println("Queue Full"); return; }
        rear = (rear + 1) % capacity;
        arr[rear] = val;
        size++;
    }

    int dequeue() {
        if (size == 0) { System.out.println("Queue Empty"); return -1; }
        int val = arr[front];
        front = (front + 1) % capacity;
        size--;
        return val;
    }

    boolean isEmpty() { return size == 0; }
}

πŸ”„Circular Queue & Deque

Circular Queue reuses empty spaces. The Queue above already uses circular indexing with (rear+1) % capacity.

Java β€” Deque (Double-Ended Queue)
// Java's built-in Deque β€” use in exams!
Deque<Integer> dq = new ArrayDeque<>();

dq.addFirst(1);   // add to front
dq.addLast(2);    // add to rear
dq.removeFirst(); // remove from front
dq.removeLast();  // remove from rear
dq.peekFirst();   // view front without removing
dq.peekLast();    // view rear without removing
Key Concept:
Circular Queue advantage: rear wraps around, reuses freed front slots β†’ no wasted space.
Deque: can add/remove from both ends, O(1) per operation.

🌳Binary Tree β€” Node Structure

Java β€” Tree Node
class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int val) {
        this.val = val;
        left = right = null;
    }
}

// Build a sample tree:
//        1
//       / \
//      2   3
//     / \
//    4   5
TreeNode root = new TreeNode(1);
root.left  = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left  = new TreeNode(4);
root.left.right = new TreeNode(5);
Key Terminology:
Root: topmost node  |  Leaf: node with no children  |  Height: longest path rootβ†’leaf
BST property: left < node < right (for all nodes)

↩️Inorder Traversal (Left β†’ Root β†’ Right)

For a BST, inorder traversal gives elements in sorted order.

Java β€” Inorder (Recursive)
void inorder(TreeNode root) {
    if (root == null) return; // base case
    inorder(root.left);         // visit left
    System.out.print(root.val + " "); // visit root
    inorder(root.right);        // visit right
}
Tree: 1(root), 2(left), 3(right), 4(ll), 5(lr)
callinorder(1) β†’ go left
callinorder(2) β†’ go left
callinorder(4) β†’ null, print 4, null
backprint 2, go right β†’ inorder(5) β†’ print 5
backprint 1, go right β†’ inorder(3) β†’ print 3
Output: 4 2 5 1 3 βœ“

➑️Preorder Traversal (Root β†’ Left β†’ Right)

Root is processed first. Used to copy/clone a tree.

Java β€” Preorder (Recursive)
void preorder(TreeNode root) {
    if (root == null) return;
    System.out.print(root.val + " "); // visit root FIRST
    preorder(root.left);
    preorder(root.right);
}
// Same tree β†’ Output: 1 2 4 5 3
Memory Hook: Pre = Root comes before children. "Root first, then explore."

⬅️Postorder Traversal (Left β†’ Right β†’ Root)

Root is processed last. Used to delete a tree or evaluate expression trees.

Java β€” Postorder (Recursive)
void postorder(TreeNode root) {
    if (root == null) return;
    postorder(root.left);
    postorder(root.right);
    System.out.print(root.val + " "); // visit root LAST
}
// Same tree β†’ Output: 4 5 2 3 1
All Three Traversals Summary:
Tree: 1, left=2(children:4,5), right=3
Inorder: 4 2 5 1 3  |  Preorder: 1 2 4 5 3  |  Postorder: 4 5 2 3 1

πŸ“Height & Count Nodes

Java β€” Height of Binary Tree
int height(TreeNode root) {
    if (root == null) return 0; // base: null has height 0
    int leftH  = height(root.left);
    int rightH = height(root.right);
    return 1 + Math.max(leftH, rightH);
} // Time: O(n)
Java β€” Count Total Nodes
int countNodes(TreeNode root) {
    if (root == null) return 0;
    return 1 + countNodes(root.left) + countNodes(root.right);
} // Time: O(n) | Space: O(h) β€” h = height
Height Trace: same tree (root=1)
h(4)null,null β†’ 1+max(0,0) = 1
h(5)null,null β†’ 1
h(2)h(4)=1, h(5)=1 β†’ 1+max(1,1) = 2
h(3)null,null β†’ 1
h(1)h(2)=2, h(3)=1 β†’ 1+max(2,1) = 3
Height = 3 βœ“

πŸ”Same Tree & BST Basics

Java β€” Check if Two Trees are Same
boolean isSameTree(TreeNode p, TreeNode q) {
    if (p == null && q == null) return true;  // both null
    if (p == null || q == null) return false; // one null
    if (p.val != q.val) return false;           // values differ
    return isSameTree(p.left, q.left) &&
           isSameTree(p.right, q.right);
}
Java β€” BST Search & Insert
// BST Search
boolean searchBST(TreeNode root, int key) {
    if (root == null) return false;
    if (root.val == key) return true;
    if (key < root.val) return searchBST(root.left, key);
    return searchBST(root.right, key);
} // Time: O(h) β€” O(log n) for balanced BST

// BST Insert
TreeNode insertBST(TreeNode root, int val) {
    if (root == null) return new TreeNode(val);
    if (val < root.val) root.left = insertBST(root.left, val);
    else root.right = insertBST(root.right, val);
    return root;
}

🧠MCQ Quiz β€” All Topics

Click an option. Get instant feedback. Reset to try again.

Score: 0 / 0 correct

πŸ“¦ Arrays

Q1. What is the time complexity of Binary Search?
A O(n)
B O(log n)
C O(nΒ²)
D O(1)
βœ… Binary Search halves the search space each step β†’ O(log n). It requires a sorted array.

πŸ“¦ Arrays

Q2. Sliding window of size K over array of size N gives how many windows?
A N
B K
C N - K + 1
D N * K
βœ… Windows start at index 0, 1, 2, ..., N-K. That's N-K+1 windows total.

πŸ“¦ Arrays

Q3. In Bubble Sort, after each outer loop pass, where does the largest element end up?
A At the beginning
B At its correct sorted position at the end
C In the middle
D Randomly placed
βœ… Each pass "bubbles" the largest unsorted element to its final position at the end of the unsorted portion.

πŸ”€ Strings

Q4. What does s.charAt(0) return for s = "Java"?
A "J"
B 'J' (char)
C 74 (int)
D Compilation error
βœ… charAt() returns a char primitive, not a String. 'J' is the first character.

πŸ”€ Strings

Q5. Which method checks if two strings have the same character frequencies?
A s1.equals(s2)
B s1.compareTo(s2)
C Anagram check using frequency array
D s1.contains(s2)
βœ… equals() checks exact match. Anagram check: increment freq for s1 chars, decrement for s2 chars, all should be 0.

πŸ”— Linked List

Q6. Inserting at the beginning of a Singly Linked List takes:
A O(1)
B O(n)
C O(log n)
D O(nΒ²)
βœ… Just set newNode.next = head and head = newNode. No traversal needed. O(1).

πŸ”— Linked List

Q7. In a Circular Linked List, what does the last node's next point to?
A null
B The head node
C Itself
D The second node
βœ… In a circular LL, the last node's next wraps back to head, forming a circle.

πŸ”— Linked List

Q8. A Doubly Linked List node has how many pointer fields?
A 1 (next only)
B 2 (next and prev)
C 3
D 0
βœ… DLL nodes have both next (forward) and prev (backward) pointers, enabling bi-directional traversal.

πŸ“š Stack & Queue

Q9. Stack follows which principle?
A FIFO β€” First In, First Out
B LIFO β€” Last In, First Out
C Random access
D Priority-based
βœ… Stack = LIFO. The last element pushed is the first to be popped. Like a stack of plates.

πŸ“š Stack & Queue

Q10. For Valid Parentheses: input = "([)]". Output?
A true
B false
C Depends on length
D Throws exception
βœ… "([)]" is invalid. Stack after '([': sees ')' β€” top is '[', mismatch! Returns false.

πŸ“š Stack & Queue

Q11. Infix "a+b*c" in Postfix is:
A ab+c*
B abc*+
C a+bc*
D *+abc
βœ… * has higher precedence than +. So b*c is evaluated first β†’ bc*. Then a+result β†’ abc*+.

🌳 Trees

Q12. For Inorder traversal, the order is:
A Root β†’ Left β†’ Right
B Left β†’ Right β†’ Root
C Left β†’ Root β†’ Right
D Right β†’ Root β†’ Left
βœ… Inorder = Left β†’ Root β†’ Right. For a BST, this gives elements in sorted ascending order.

🌳 Trees

Q13. Height of a tree with only 1 node (root) is:
A 0
B 1
C 2
D Undefined
βœ… By convention (as coded), a single node returns height 1. Null returns 0.

🌳 Trees

Q14. In a BST, where is the minimum value always found?
A Leftmost node
B Rightmost node
C Root
D Any leaf node
βœ… BST property: all left subtree values < root. So the minimum is always at the leftmost node.

🌳 Trees

Q15. Postorder traversal is used for:
A Copying a tree
B Level-order printing
C Deleting a tree / evaluating expression trees
D Sorting BST elements
βœ… Postorder processes children before root β€” perfect for deletion (free children before parent) and postfix expression evaluation.

πŸ“‹Quick Reference Cheatsheet

All 5 topics at a glance β€” print this before entering the exam hall.

⏱ Time Complexities

Linear SearchO(n) / O(1)
Binary SearchO(log n) / O(1)
Bubble / Selection SortO(nΒ²) / O(1)
Sliding Window (fixed K)O(n) / O(1)
LL Insert at HeadO(1)
LL Insert at TailO(n)
Stack Push/Pop/PeekO(1)
Queue Enqueue/DequeueO(1)
Tree TraversalsO(n) / O(h)
BST Search/InsertO(h) = O(log n)

🎯 Pattern Recognition

Fixed subarray/windowSliding Window
Sorted array searchBinary Search
Pair finding in sorted arrTwo Pointers
Brackets matchingStack
Next greater/smallerMonotonic Stack
Infix β†’ PostfixStack + Precedence
BFS (level order)Queue
Tree recursionBase: null β†’ return
BST sorted outputInorder traversal
Delete treePostorder traversal

πŸ”— Linked List Tricks

Insert at headO(1) β€” update head
Insert at tailO(n) β€” traverse to end
Delete headhead = head.next
Delete tailcurr.next.next == null
Count nodesLoop until null
Circular traversedo-while loop
DLL deleteUpdate prev & next

🌳 Tree Traversal Order

Inorder (L→N→R)BST → sorted
Preorder (N→L→R)Clone tree
Postorder (L→R→N)Delete tree
Base case alwaysif (root==null) return
Height formula1 + max(L, R)
Count formula1 + count(L) + count(R)
Same treeRecursive val check

πŸ“¦ Array Quick Ops

Reverse arrayTwo pointer swap
Palindrome checkarr[i] == arr[n-1-i]
Max in window KSliding + track max
Move zeroesPartition pointer j
Remove duplicatesTwo pointer j
Two Sum (sorted)left++, right--

🏁 Exam Day Tips

Always check nullBefore .next or .data
Write base cases firstTree recursion key
Dry run on paperBefore typing code
State complexity// Time: O(?) Space: O(?)
Use ScannerRead input properly
Edge: empty inputn=0, null, empty string

πŸ“ŒImportant Notes from Syllabus

Focus on traversal order

Memorize In/Pre/Post order. Know which gives sorted output (Inorder in BST).

Dry run before coding

Always trace through an example manually before writing any code.

Practice recursion base case

Every recursive tree function starts with: if (root == null) return 0/false/null.

Understand node visiting sequence

Draw the tree and number each step of the traversal on paper.