Implement right side view and local minimum search
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's understanding of binary tree traversal and array local-minimum detection, measuring skills in data structures (binary trees and arrays), algorithm design, and algorithmic time-complexity analysis.
Constraints
- 0 <= len(tree) <= 200000
- 1 <= len(nums) <= 200000
- All elements in nums are pairwise distinct
- Tree values fit in 32-bit signed integer range
- Return value format: [right_view_list, local_min_index]
Solution
from typing import List, Optional, Any
from collections import deque
class TreeNode:
__slots__ = ("val", "left", "right")
def __init__(self, val: int, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(level: List[Optional[int]]) -> Optional[TreeNode]:
"""Builds a binary tree from level-order array with None as null."""
if not level:
return None
it = iter(level)
root_val = next(it)
if root_val is None:
return None
root = TreeNode(root_val)
q = deque([root])
while q:
node = q.popleft()
try:
lv = next(it)
except StopIteration:
break
if lv is not None:
node.left = TreeNode(lv)
q.append(node.left)
try:
rv = next(it)
except StopIteration:
break
if rv is not None:
node.right = TreeNode(rv)
q.append(node.right)
return root
def right_side_view(root: Optional[TreeNode]) -> List[int]:
if root is None:
return []
res: List[int] = []
q = deque([root])
while q:
size = len(q)
for i in range(size):
node = q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
if i == size - 1:
res.append(node.val)
return res
def find_local_min_index(nums: List[int]) -> int:
"""Binary search for any local minimum index with virtual +∞ boundaries."""
n = len(nums)
l, r = 0, n - 1
while l < r:
m = (l + r) // 2
if nums[m] > nums[m + 1]:
l = m + 1
else:
r = m
return l
def right_view_and_local_min(tree: List[Optional[int]], nums: List[int]) -> List[Any]:
root = build_tree(tree)
rv = right_side_view(root)
idx = find_local_min_index(nums)
return [rv, idx]