Top Interview Questions Flashcards

Master top interview questions with our interactive flashcard system

Basic Calculator II
Medium
Stack

Hints:

  • • Use a stack to store numbers
  • • Process multiplication and division immediately
  • • Handle addition and subtraction at the end
  • • Use a variable to track the current number
def calculate(s: str) -> int:
    stack = []
    num = 0
    sign = '+'
    for i in range(len(s)):
        if s[i].isdigit():
            num = num * 10 + int(s[i])
        if (not s[i].isdigit() and s[i] != '') or i == len(s) - 1:
            if sign == '+':
                stack.append(num)
            elif sign == '-':
                stack.append(-num)
            elif sign == '*':
                stack.append(stack.pop() * num)
            elif sign == '/':
                stack.append(int(stack.pop() / num))
            sign = s[i]
            num = 0
    return sum(stack)
Closest Binary Search Tree Value
Easy
Binary Search Tree

Hints:

  • • Use binary search tree properties
  • • Keep track of the closest value found
  • • Update closest value based on absolute difference
  • • Move left or right based on target comparison
def closestValue(root: Optional[TreeNode], target: float) -> int:
    closest = root.val
    while root:
        if abs(root.val - target) < abs(closest - target):
            closest = root.val
        root = root.left if target < root.val else root.right
    return closest
Vertical Order Traversal of a Binary Tree
Hard
Tree

Hints:

  • • Use a dictionary to store nodes by column
  • • Track row and column positions during traversal
  • • Sort nodes at the same position by value
  • • Use BFS or DFS to traverse the tree
def verticalTraversal(root: Optional[TreeNode]) -> List[List[int]]:
    if not root:
        return []
    
    column_map = defaultdict(list)
    queue = deque([(root, 0, 0)])
    
    while queue:
        node, row, col = queue.popleft()
        column_map[col].append((row, node.val))
        if node.left:
            queue.append((node.left, row + 1, col - 1))
        if node.right:
            queue.append((node.right, row + 1, col + 1))
    
    return [[val for _, val in sorted(column_map[col])] 
            for col in sorted(column_map.keys())]
Merge k Sorted Lists
Hard
Linked List

Hints:

  • • Use a min-heap to efficiently get the smallest element
  • • Push the head of each list into the heap
  • • Pop the smallest element and add it to the result
  • • Push the next element from the same list if it exists
def mergeKLists(lists: List[Optional[ListNode]]) -> Optional[ListNode]:
    import heapq
    heap = []
    for i, node in enumerate(lists):
        if node:
            heapq.heappush(heap, (node.val, i, node))
    
    dummy = ListNode()
    current = dummy
    
    while heap:
        val, i, node = heapq.heappop(heap)
        current.next = node
        current = current.next
        if node.next:
            heapq.heappush(heap, (node.next.val, i, node.next))
    
    return dummy.next
Convert Binary Search Tree to Sorted Doubly Linked List
Medium
Tree

Hints:

  • • Use in-order traversal
  • • Keep track of the previous node
  • • Connect nodes in the correct order
  • • Handle the circular connection at the end
def treeToDoublyList(root: 'Node') -> 'Node':
    if not root:
        return None
    
    first = None
    last = None
    
    def helper(node):
        nonlocal first, last
        if node:
            helper(node.left)
            if last:
                last.right = node
                node.left = last
            else:
                first = node
            last = node
            helper(node.right)
    
    helper(root)
    last.right = first
    first.left = last
    return first
Shortest Path in Binary Matrix
Medium
BFS

Hints:

  • • Use BFS to find the shortest path
  • • Track visited cells to avoid cycles
  • • Consider all 8 possible directions
  • • Return -1 if no path exists
def shortestPathBinaryMatrix(grid: List[List[int]]) -> int:
    if grid[0][0] == 1:
        return -1
    
    n = len(grid)
    queue = deque([(0, 0, 1)])
    grid[0][0] = 1
    
    directions = [(0, 1), (1, 0), (0, -1), (-1, 0),
                 (1, 1), (1, -1), (-1, 1), (-1, -1)]
    
    while queue:
        x, y, steps = queue.popleft()
        if x == n-1 and y == n-1:
            return steps
        
        for dx, dy in directions:
            nx, ny = x + dx, y + dy
            if 0 <= nx < n and 0 <= ny < n and grid[nx][ny] == 0:
                grid[nx][ny] = 1
                queue.append((nx, ny, steps + 1))
    
    return -1