Bird
Raised Fist0
DSA Goprogramming~20 mins

Kth Smallest Element in BST in DSA Go - 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 Go code that finds the 3rd smallest element in a BST?
DSA Go
package main
import "fmt"
type TreeNode struct {
    Val int
    Left *TreeNode
    Right *TreeNode
}

func kthSmallest(root *TreeNode, k int) int {
    stack := []*TreeNode{}
    current := root
    count := 0
    for current != nil || len(stack) > 0 {
        for current != nil {
            stack = append(stack, current)
            current = current.Left
        }
        current = stack[len(stack)-1]
        stack = stack[:len(stack)-1]
        count++
        if count == k {
            return current.Val
        }
        current = current.Right
    }
    return -1
}

func main() {
    root := &TreeNode{Val: 5}
    root.Left = &TreeNode{Val: 3}
    root.Right = &TreeNode{Val: 6}
    root.Left.Left = &TreeNode{Val: 2}
    root.Left.Right = &TreeNode{Val: 4}
    root.Left.Left.Left = &TreeNode{Val: 1}
    fmt.Println(kthSmallest(root, 3))
}
A4
B2
C3
D5
Attempts:
2 left
💡 Hint
Remember that an in-order traversal of a BST visits nodes in ascending order.
🧠 Conceptual
intermediate
1:30remaining
Understanding Kth Smallest Element in BST
Which property of a Binary Search Tree (BST) allows the kth smallest element to be found efficiently using in-order traversal?
AIn-order traversal of BST visits nodes in ascending order
BBST nodes are stored in a sorted linked list
CBST nodes have pointers to their parents
DBST is always a balanced tree
Attempts:
2 left
💡 Hint
Think about the order in which nodes are visited during in-order traversal.
🔧 Debug
advanced
2:00remaining
Identify the Error in Kth Smallest Element Code
What error will the following Go code produce when trying to find the 2nd smallest element in a BST?
DSA Go
package main
import "fmt"
type TreeNode struct {
    Val int
    Left *TreeNode
    Right *TreeNode
}

func kthSmallest(root *TreeNode, k int) int {
    var count int
    var result int
    var inorder func(node *TreeNode)
    inorder = func(node *TreeNode) {
        if node == nil {
            return
        }
        inorder(node.Left)
        count++
        if count == k {
            result = node.Val
            return
        }
        inorder(node.Right)
    }
    inorder(root)
    return result
}

func main() {
    root := &TreeNode{Val: 3}
    root.Left = &TreeNode{Val: 1}
    root.Right = &TreeNode{Val: 4}
    root.Left.Right = &TreeNode{Val: 2}
    fmt.Println(kthSmallest(root, 2))
}
AThe code returns 2 correctly
BThe code returns 1 instead of 2
CThe code causes a stack overflow
DThe code returns 0 instead of 2
Attempts:
2 left
💡 Hint
Check if the recursion stops after finding the kth element.
❓ Predict Output
advanced
2:00remaining
Output of Modified Kth Smallest Element Code
What is the output of this Go code that finds the 4th smallest element in a BST with duplicate values?
DSA Go
package main
import "fmt"
type TreeNode struct {
    Val int
    Left *TreeNode
    Right *TreeNode
}

func kthSmallest(root *TreeNode, k int) int {
    stack := []*TreeNode{}
    current := root
    count := 0
    for current != nil || len(stack) > 0 {
        for current != nil {
            stack = append(stack, current)
            current = current.Left
        }
        current = stack[len(stack)-1]
        stack = stack[:len(stack)-1]
        count++
        if count == k {
            return current.Val
        }
        current = current.Right
    }
    return -1
}

func main() {
    root := &TreeNode{Val: 5}
    root.Left = &TreeNode{Val: 3}
    root.Right = &TreeNode{Val: 6}
    root.Left.Left = &TreeNode{Val: 3}
    root.Left.Right = &TreeNode{Val: 4}
    fmt.Println(kthSmallest(root, 4))
}
A3
B4
C5
D-1
Attempts:
2 left
💡 Hint
Duplicates appear in in-order traversal as repeated values.
🚀 Application
expert
2:30remaining
Optimizing Kth Smallest Element Search with Augmented BST
You want to find the kth smallest element in a BST efficiently multiple times. Which data structure modification helps achieve O(log n) time per query?
AStore subtree sizes at each node to guide search
BConvert BST to a sorted array and binary search
CUse a hash map to store node values and their ranks
DPerform full in-order traversal each time to find kth element
Attempts:
2 left
💡 Hint
Think about augmenting nodes with extra info to skip parts of the tree.

Practice

(1/5)
1. What does the term Kth Smallest Element in BST mean?
easy
A. The element with the highest frequency in the BST
B. The element at the root of the BST
C. The largest element in the BST
D. The element that is the Kth smallest when BST elements are sorted in ascending order

Solution

  1. Step 1: Understand BST property

    A Binary Search Tree (BST) stores elements so that left child nodes are smaller and right child nodes are larger than the parent node.
  2. Step 2: Define Kth smallest element

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

    The element that is the Kth smallest when BST elements are sorted in ascending order -> Option D
  4. Quick Check:

    Kth smallest = Kth element in sorted order [OK]
Hint: Think in sorted order of BST elements [OK]
Common Mistakes:
  • Confusing Kth smallest with root element
  • Thinking it means largest element
  • Mixing frequency with order
2. Which of the following Go function signatures correctly represents a function to find the Kth smallest element in a BST node structure named TreeNode?
easy
A. func kthSmallest(root *TreeNode) int
B. func kthSmallest(root *TreeNode, k int) int
C. func kthSmallest(root TreeNode, k int) *int
D. func kthSmallest(k int, root *TreeNode) int

Solution

  1. Step 1: Check parameter order and types

    The function should take the root pointer of type *TreeNode and an integer k to specify the Kth element.
  2. Step 2: Check return type

    The function returns an int representing the value of the Kth smallest element.
  3. Final Answer:

    func kthSmallest(root *TreeNode, k int) int -> Option B
  4. Quick Check:

    Correct parameters and return type [OK]
Hint: Root pointer first, then k, return int [OK]
Common Mistakes:
  • Swapping parameter order
  • Passing root by value instead of pointer
  • Missing k parameter
  • Wrong return type
3. Given the BST below and k = 3, what will the output of kthSmallest(root, 3) be?

      5
     / \
    3   7
   / \   \
  2   4   8
medium
A. 4
B. 5
C. 3
D. 7

Solution

  1. Step 1: Perform in-order traversal

    In-order traversal visits nodes in ascending order: 2, 3, 4, 5, 7, 8.
  2. Step 2: Identify the 3rd element

    The 3rd element in this order is 4.
  3. Final Answer:

    4 -> Option A
  4. Quick Check:

    In-order 3rd element = 4 [OK]
Hint: In-order traversal gives sorted order [OK]
Common Mistakes:
  • Counting root as first without traversal
  • Confusing pre-order or post-order with in-order
  • Off-by-one counting errors
4. Consider this Go function snippet to find the Kth smallest element in a BST:
func kthSmallest(root *TreeNode, k int) int {
    count := 0
    var result int
    var inorder func(node *TreeNode)
    inorder = func(node *TreeNode) {
        if node == nil {
            return
        }
        inorder(node.Left)
        count++
        if count == k {
            result = node.Val
            return
        }
        inorder(node.Right)
    }
    inorder(root)
    return result
}
What is the main bug in this code?
medium
A. The function does not stop traversal after finding the Kth element
B. The count variable is not incremented correctly
C. The result variable is not returned
D. The inorder function is not called

Solution

  1. Step 1: Analyze traversal stopping condition

    The code sets result when count == k but does not stop further recursion, so it continues traversing unnecessarily.
  2. Step 2: Identify missing early return

    After finding the Kth element, the function should stop traversing to avoid overwriting result or extra work.
  3. Final Answer:

    The function does not stop traversal after finding the Kth element -> Option A
  4. Quick Check:

    Traversal continues after Kth found [OK]
Hint: Stop traversal immediately after finding Kth element [OK]
Common Mistakes:
  • Not stopping recursion after finding result
  • Incorrect count increment placement
  • Returning wrong variable
5. You want to find the Kth smallest element in a BST but the tree is very large and you want to optimize the search. Which approach below best improves efficiency?
hard
A. Convert the BST to a sorted array and then pick the Kth element
B. Perform a full in-order traversal every time to find the Kth element
C. Store the count of nodes in each subtree and use it to skip branches
D. Use breadth-first search to find the Kth smallest element

Solution

  1. Step 1: Understand subtree counts

    By storing the number of nodes in each subtree, we can decide if the Kth smallest is in left subtree, current node, or right subtree without full traversal.
  2. Step 2: Use counts to skip branches

    If left subtree has more than or equal to k nodes, recurse left; else adjust k and recurse right, reducing unnecessary visits.
  3. Final Answer:

    Store the count of nodes in each subtree and use it to skip branches -> Option C
  4. Quick Check:

    Subtree counts optimize search [OK]
Hint: Use subtree node counts to jump branches [OK]
Common Mistakes:
  • Doing full traversal every time
  • Converting to array wastes space/time
  • Using BFS which is not sorted order
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