Data Structures & AlgorithmsEasyInfosys SP/DSE · Product Company SDE
Problem: Given the root of a BST with n nodes and a target, return the value closest to the target. What is the best time complexity, where h is the tree height?
- A. O(n) – an inorder traversal is always required
- B. O(h) – walk down one path, going left or right by comparing with the target
- C. O(n log n) – sort the values first
- D. O(1) – the root is always closest
Correct answer: B. O(h) – walk down one path, going left or right by comparing with the target
At each node, the closest value can only be on the side towards the target, so one root-to-leaf walk with a running best suffices: O(h), which is O(log n) for a balanced tree and O(n) for a skewed one.
More Coding Interview Problems questions
- Problem: Return the maximum width of a tree: the largest number of positions between the leftmost and rightmost non-null nodes of a level…
- Problem: Flatten a tree into a 'linked list' in preorder using right pointers, then print the values along the right pointers. Trees are…
- Problem: A trie stores n words of average length L over a 26-letter alphabet. Autocomplete must list whether any word starts with a prefix…
- Problem: Insert words into a trie and count how many stored words start with a given prefix. python def make(words): root = {} for w in…
- Problem: Count islands (groups of '1' cells connected up, down, left or right) on a satellite grid. python def islands(g): R, C = len(g)…
- Problem: In a grid of fresh (1) and rotten (2) oranges, every minute rot spreads to 4-neighbours. Return the minutes until no fresh orange…