Bird
Raised Fist0
DSA Cprogramming~20 mins

Kth Smallest Element in BST in DSA C - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Kth Smallest Element Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Kth Smallest Element Function
What is the output of the following C code that finds the 3rd smallest element in the given BST?
DSA C
typedef struct Node {
    int val;
    struct Node* left;
    struct Node* right;
} Node;

int count = 0;
int result = -1;

void kthSmallestUtil(Node* root, int k) {
    if (!root) return;
    kthSmallestUtil(root->left, k);
    count++;
    if (count == k) {
        result = root->val;
        return;
    }
    kthSmallestUtil(root->right, k);
}

int kthSmallest(Node* root, int k) {
    count = 0;
    result = -1;
    kthSmallestUtil(root, k);
    return result;
}

// BST structure:
//       5
//      / \
//     3   7
//    / \   \
//   2   4   8

// Call: kthSmallest(root, 3);
A5
B4
C3
D7
Attempts:
2 left
💡 Hint
Remember that inorder traversal of BST gives sorted order.
🧠 Conceptual
intermediate
1:30remaining
Understanding Kth Smallest Element in BST
Which property of a Binary Search Tree (BST) allows us to find the kth smallest element efficiently using inorder traversal?
ABST nodes are stored in a heap structure
BBST is always a balanced tree
CBST nodes have pointers to their parents
DInorder traversal of BST visits nodes in ascending order
Attempts:
2 left
💡 Hint
Think about the order in which nodes are visited in inorder traversal.
🔧 Debug
advanced
2:00remaining
Identify the Bug in Kth Smallest Element Code
What error will occur when running this code to find the kth smallest element in a BST?
DSA C
int kthSmallestUtil(Node* root, int k, int* count) {
    if (!root) return -1;
    int left = kthSmallestUtil(root->left, k, count);
    if (left != -1) return left;
    (*count)++;
    if (*count == k) return root->val;
    return kthSmallestUtil(root->right, k, count);
}

int kthSmallest(Node* root, int k) {
    int count = 0;
    return kthSmallestUtil(root, k, &count);
}

// Suppose k is larger than number of nodes in BST.
AReturns -1 indicating kth element not found
BCauses segmentation fault due to null pointer dereference
CReturns 0 as default value
DEnters infinite recursion
Attempts:
2 left
💡 Hint
What happens if k is bigger than total nodes?
❓ Predict Output
advanced
2:00remaining
Output of Iterative Kth Smallest Element Code
What is the output of this iterative C code to find the 2nd smallest element in the BST below?
DSA C
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int val;
    struct Node* left;
    struct Node* right;
} Node;

typedef struct Stack {
    Node* data[100];
    int top;
} Stack;

void push(Stack* s, Node* node) {
    s->data[++(s->top)] = node;
}

Node* pop(Stack* s) {
    return s->data[(s->top)--];
}

int kthSmallest(Node* root, int k) {
    Stack s = {.top = -1};
    Node* curr = root;
    int count = 0;
    while (curr || s.top != -1) {
        while (curr) {
            push(&s, curr);
            curr = curr->left;
        }
        curr = pop(&s);
        count++;
        if (count == k) return curr->val;
        curr = curr->right;
    }
    return -1;
}

// BST:
//      6
//     / \
//    3   8
//   / \   \
//  2   4   9

// Call: kthSmallest(root, 2);
A3
B4
C2
D6
Attempts:
2 left
💡 Hint
Iterative inorder traversal visits nodes in ascending order.
🚀 Application
expert
2:30remaining
Kth Smallest Element with Augmented BST
In an augmented BST where each node stores the count of nodes in its left subtree, how can you find the kth smallest element efficiently?
AUse postorder traversal to find kth smallest element
BAlways traverse entire tree inorder and count nodes until kth is found
CTraverse left subtree if k is less or equal to left count; else go right with k reduced by left count + 1
DPerform level order traversal and pick kth element visited
Attempts:
2 left
💡 Hint
Use the stored counts to skip subtrees.

Practice

(1/5)
1. What does the term kth smallest element in a BST mean?
easy
A. The element that appears in the kth position when BST elements are sorted in ascending order
B. The element with the kth largest value in the BST
C. The element at the kth level of the BST
D. The element with the kth highest frequency in the BST

Solution

  1. Step 1: Understand BST property

    A Binary Search Tree (BST) stores elements so that left subtree has smaller values and right subtree has larger values.
  2. Step 2: Define kth smallest element

    The kth smallest element is the one that appears in the kth position when all elements are sorted in ascending order.
  3. Final Answer:

    The element that appears in the kth position when BST elements are sorted in ascending order -> Option A
  4. Quick Check:

    kth smallest = kth in sorted order [OK]
Hint: Think of inorder traversal to get sorted order [OK]
Common Mistakes:
  • Confusing kth smallest with kth largest
  • Thinking kth smallest means kth level node
  • Assuming frequency matters
2. Which of the following C function signatures is correct to find the kth smallest element in a BST node structure struct Node?
easy
A. void kthSmallest(int root, int k);
B. int kthSmallest(struct Node root, int k);
C. int kthSmallest(struct Node* root, int k);
D. int kthSmallest(struct Node* root);

Solution

  1. Step 1: Understand function parameters

    The function needs the root pointer to the BST and the integer k to find kth smallest.
  2. Step 2: Check parameter types

    Passing struct Node* for root and int for k is correct. Return type should be int for the element value.
  3. Final Answer:

    int kthSmallest(struct Node* root, int k); -> Option C
  4. Quick Check:

    Correct signature includes pointer and k parameter [OK]
Hint: Use pointer for tree root and int for k [OK]
Common Mistakes:
  • Passing root by value instead of pointer
  • Missing k parameter
  • Wrong return type or missing return
3. Given the BST below and k = 3, what is the output of the function kthSmallest(root, 3)?
      5
     / \
    3   7
   / \   \
  2   4   8
medium
A. 5
B. 4
C. 3
D. 7

Solution

  1. Step 1: Perform inorder traversal

    Inorder traversal of BST visits nodes in ascending order: 2, 3, 4, 5, 7, 8.
  2. Step 2: Identify 3rd element in traversal

    The 3rd element is 4.
  3. Final Answer:

    4 -> Option B
  4. Quick Check:

    Inorder 3rd element = 4 [OK]
Hint: Inorder traversal gives sorted order; pick kth element [OK]
Common Mistakes:
  • Counting nodes incorrectly in traversal
  • Confusing preorder or postorder with inorder
  • Choosing root or other node instead of kth
4. Consider this buggy C code snippet to find kth smallest element in BST:
int count = 0;
int kthSmallest(struct Node* root, int k) {
    if (!root) return -1;
    int left = kthSmallest(root->left, k);
    if (left != -1) return left;
    count++;
    if (count == k) return root->data;
    return kthSmallest(root->right, k);
}
What is the main issue with this code?
medium
A. Global variable 'count' causes incorrect results on multiple calls
B. Function does not handle empty tree
C. Returns -1 for valid kth element
D. Does not traverse right subtree

Solution

  1. Step 1: Analyze use of 'count'

    The variable 'count' is global and not reset between calls, causing wrong counts if function called multiple times.
  2. Step 2: Understand impact on results

    Because 'count' is not reset, subsequent calls may return wrong kth smallest element or fail.
  3. Final Answer:

    Global variable 'count' causes incorrect results on multiple calls -> Option A
  4. Quick Check:

    Global count not reset breaks repeated calls [OK]
Hint: Avoid global counters; pass as function argument [OK]
Common Mistakes:
  • Ignoring global variable side effects
  • Assuming function works for multiple calls
  • Not resetting count before each call
5. You have a BST with nodes containing duplicate values. How would you modify the standard kth smallest element algorithm to correctly find the kth smallest unique element?
hard
A. Use preorder traversal instead of inorder
B. Count all nodes including duplicates normally
C. Remove duplicates from BST before traversal
D. Use inorder traversal and skip duplicates by comparing with previous visited value

Solution

  1. Step 1: Understand duplicates in BST

    Duplicates appear as multiple nodes with same value; inorder traversal visits them in sorted order including duplicates.
  2. Step 2: Modify traversal to skip duplicates

    Track previous visited value during inorder traversal; only increment count when current value differs from previous.
  3. Step 3: Find kth unique element

    Increment count only for unique values; when count equals k, return current node's value.
  4. Final Answer:

    Use inorder traversal and skip duplicates by comparing with previous visited value -> Option D
  5. Quick Check:

    Skip duplicates by comparing previous value [OK]
Hint: Track previous value to count unique elements [OK]
Common Mistakes:
  • Counting duplicates as separate elements
  • Using preorder traversal which is not sorted
  • Trying to remove duplicates instead of skipping
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard