Implement exponentiation and link tree neighbors
MetaMachine Learning Engineer · Technical ScreenLast updated
This question evaluates numerical algorithm implementation and in-place tree traversal skills, specifically fast exponentiation with careful edge-case and precision handling and iterative linking of next pointers in a perfect binary tree.
Solve two independent tasks.
Task A — Fast exponentiation: Implement fastExponent(x, n) that returns x raised to the integer power n, where x is a double and n is a 32-bit signed integer. Requirements: O(log |n|) time via exponentiation by squaring; O(
- extra space with an iterative approach; correctly handle negative exponents, n == Integer.MIN_VALUE, and edge cases such as x == 0 or x == ±1. Return a double; a relative error up to 1e-10 is acceptable.
Task B — Link neighbors in a perfect binary tree: Given the root of a perfect binary tree whose nodes have fields (val, left, right, next), set each node’s next pointer to its immediate right neighbor on the same level; if none, set it to null. Constraints: O(n) time, O(
- extra space, and do not use recursion. Afterward, each level should be traversable using next pointers starting from its leftmost node.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.