×

Instructions

Please read the instructions carefully before starting the exam.

Once you start the exam, the timer will begin, and you cannot pause it.

Ensure that you complete and submit your code within the given time if the timer is enabled.


Smart Contact Organiser – Closest Match in Binary Search Tree (Difficulty - Medium)


Smart Contact Organizer – Closest Match in BST

Problem Statement:

In a smart contact organiser app, names are stored in a Binary Search Tree (BST) to allow efficient alphabetical lookup.

Your task is to implement a function that finds the closest matching contact name in the BST to a given target name based on alphabetical order. If multiple names are equally close, return the one that appears first in in-order traversal.

Input:

  • tree: A list of strings representing level-order traversal of a BST. Use "null" for missing nodes.
  • target: A string representing the name you're trying to match.

Output:

Return the contact name in the BST that is alphabetically closest to the target.

Constraints:

  • Each name is a string of 1–20 alphabetic characters (uppercase/lowercase mixed)
  • The BST contains between 1 and 10⁴ nodes
  • There is at least one valid node in the input list

Example 1:

Input: [Emma, David, Sophia], Ella
Output: Emma

Explanation:
Tree structure:
       Emma
      /    \
   David  Sophia

Closest alphabetically to "Ella" is "Emma".
    

Example 2:

Input: [Kevin, Jake, Mike, null, null, Louis], Lucas
Output: Louis

Explanation:
        Kevin
       /     \
     Jake    Mike
             /
         Louis

"Lucas" is alphabetically closest to "Louis".
    

Example 3:

Input: [Zoe, Ann], Aaron
Output: Ann

Explanation:
Ann is the only node alphabetically near Aaron.
    

Example 4:

Input: [Mia, Emma, Olivia, null, null, Lily], Leo
Output: Lily

Explanation:
        Mia
       /   \
    Emma   Olivia
           /
         Lily

"Leo" is closest alphabetically to "Lily".
    


Time Left:



Processing...

Error:


                

Output:

Test Case Result Input Correct Output Your Output




Submission Result