Answer the following independent algorithmic prompts. For each, explain your approach, justify data structures, analyze time/space complexity, and provide correct code:
-
Bulb toggling passes: You have n bulbs initially off. For pass i (1 ≤ i ≤ n), toggle every bulb whose index is a multiple of i. After n passes, return the count of bulbs that are on. Follow-up: given m ≤ n passes or a custom toggling set S of divisors, compute the result efficiently without simulating all passes.
-
Repeated word-distance queries: Preprocess an array of words to support many queries of the form shortestDistance(word1, word
-
that returns the minimum index gap between any occurrence of the two words. Design the initialization and query APIs, then optimize for both time and memory. Follow-ups: support dynamic inserts/appends; support queries over a sliding window.
-
Invert a binary tree: Given the root of a binary tree, return its mirror image. Discuss iterative vs. recursive solutions and how to handle nodes missing exactly one child. Follow-ups: verify structural equality between the original and double-inverted tree; invert only nodes at odd depths.
-
Count land clusters in a grid: Given an m×n grid of '1' (land) and '0' (water), return the number of connected land clusters using 4-directional adjacency. Follow-ups: handle dynamic updates turning cells on/off; extend to 8-directional adjacency; optimize with union–find.
-
Longest run in a circular binary array: Given a binary array treated as circular (index wraps around), compute the maximum number of consecutive 1s. Follow-ups: if you may flip up to k zeros to ones, find the new maximum and return one optimal window.
-
Peel leaves by rounds: Given a binary tree, iteratively collect and remove its leaves; output a list of lists where the i-th list contains the values removed at round i. Provide an O(n) solution and discuss how computing node heights leads to the result.