Moloco interview questions & answers

12 real Moloco interview questions with full model answers — Coding. Drawn from the same verified bank ChannelPulse drills from (12 Moloco questions in total).

CodingMediumMolocoSoftware Engineer

1. Number of Islands (LeetCode)

Model answer

The task

Given a grid of land and water, count the groups of connected land cells. Cells connect horizontally or vertically, not diagonally.

Key idea

Each group is one island. Scan the grid, and whenever an unvisited land cell is found, count a new island and explore its entire connected region. Mark cells as visited when adding them to the search queue so no cell is processed more than once.

Approach

  1. Return 0 if the grid is empty.
  2. Scan every cell in the grid.
  3. When a land cell is found, increment the island count and start a breadth-first search from it.
  4. During the search, mark each discovered land cell as water and add its in-bounds land neighbors to the queue.
  5. Return the island count after the scan is complete.
from collections import deque
from typing import List

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid or not grid[0]:
            return 0

        rows, cols = len(grid), len(grid[0])
        islands = 0

        for row in range(rows):
            for col in range(cols):
                if grid[row][col] != "1":
                    continue

                islands += 1
                grid[row][col] = "0"
                queue = deque([(row, col)])

                while queue:
                    current_row, current_col = queue.popleft()

                    for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                        next_row = current_row + dr
                        next_col = current_col + dc

                        if (
                            0 <= next_row < rows
                            and 0 <= next_col < cols
                            and grid[next_row][next_col] == "1"
                        ):
                            # Mark when enqueuing to avoid duplicate work.
                            grid[next_row][next_col] = "0"
                            queue.append((next_row, next_col))

        return islands

Complexity: Time: O(rows * cols), since each cell is examined at most a constant number of times.

Complexity: Space: O(rows * cols) in the worst case for the BFS queue.

Common follow-ups

  • Preserve the input grid? Track visited cells in a separate set instead of changing land cells to water.
  • Use depth-first search instead? Recursively or iteratively explore the four neighbors; iterative DFS avoids recursion-depth concerns.
  • Count diagonally connected land as part of the same island? Include the four diagonal directions in the neighbor list.
CodingMediumMolocoSoftware Engineer

2. Rotting Oranges (LeetCode)

Model answer

The task

Given a grid of empty cells, fresh oranges, and rotten oranges, find the minimum number of minutes until no fresh oranges remain. Each minute, a rotten orange makes any fresh orange directly above, below, left, or right of it rotten; return -1 if some fresh oranges can never be reached.

Key idea

Use multi-source breadth-first search: all initially rotten oranges spread at the same time, so put them all in the queue at the start. Process the queue one minute at a time, counting newly rotten oranges to detect whether any fresh ones remain unreachable.

Approach

  1. Count the fresh oranges and enqueue every initially rotten orange.
  2. If there are no fresh oranges, return 0.
  3. For each BFS layer, rot adjacent fresh oranges, decrement the fresh count, and enqueue them.
  4. Count each processed layer as one minute.
  5. Return the minutes if all fresh oranges rotted; otherwise return -1.
from collections import deque
from typing import List

class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:
        rows, cols = len(grid), len(grid[0])
        queue = deque()
        fresh = 0

        # Gather all initial sources and count oranges that still need to rot.
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == 2:
                    queue.append((r, c))
                elif grid[r][c] == 1:
                    fresh += 1

        if fresh == 0:
            return 0

        minutes = 0
        directions = ((1, 0), (-1, 0), (0, 1), (0, -1))

        while queue and fresh > 0:
            # Process exactly the oranges rotten before this minute began.
            for _ in range(len(queue)):
                r, c = queue.popleft()

                for dr, dc in directions:
                    nr, nc = r + dr, c + dc
                    if (
                        0 <= nr < rows
                        and 0 <= nc < cols
                        and grid[nr][nc] == 1
                    ):
                        grid[nr][nc] = 2
                        fresh -= 1
                        queue.append((nr, nc))

            minutes += 1

        return minutes if fresh == 0 else -1

Complexity:

  • Time: O(rows × cols), since each cell is visited at most once.
  • Space: O(rows × cols) for the BFS queue in the worst case.

Common follow-ups

  • What if diagonal neighbors also spread rot? Add the four diagonal directions to the neighbor list.
  • Can the original grid be preserved? Copy it first, or track visited cells separately.
  • How would you return which oranges rot each minute? Store each BFS layer’s cells or record a rot-time value per cell.
CodingMediumMolocoSoftware Engineer

3. Course Schedule II (LeetCode)

Model answer

The task

Return an ordering of all courses that satisfies the prerequisite relationships. If no such ordering exists because the relationships contain a cycle, return an empty list.

Key idea

Model each course as a graph node, with an edge from a prerequisite to the course that depends on it. Kahn’s topological-sort algorithm repeatedly takes courses with no remaining prerequisites; if it cannot take every course, the graph contains a cycle.

Approach

  1. Build an adjacency list and count each course’s prerequisites as its indegree.
  2. Add all zero-indegree courses to a queue.
  3. Remove courses from the queue, adding each to the result and reducing the indegree of its dependent courses.
  4. Add a dependent course to the queue when its indegree reaches zero.
  5. Return the result if it includes every course; otherwise, return an empty list.
from collections import deque
from typing import List

class Solution:
    def findOrder(
        self, numCourses: int, prerequisites: List[List[int]]
    ) -> List[int]:
        # Edges point from prerequisite to dependent course.
        graph = [[] for _ in range(numCourses)]
        indegree = [0] * numCourses

        for course, prerequisite in prerequisites:
            graph[prerequisite].append(course)
            indegree[course] += 1

        ready = deque(
            course
            for course in range(numCourses)
            if indegree[course] == 0
        )
        order = []

        while ready:
            course = ready.popleft()
            order.append(course)

            for dependent in graph[course]:
                indegree[dependent] -= 1
                if indegree[dependent] == 0:
                    ready.append(dependent)

        # A cycle prevents all courses from being added.
        return order if len(order) == numCourses else []

**Complexity:**

- Time: O(V + E), where V is the number of courses and E is the number of prerequisite relationships.
- Space: O(V + E) for the graph, indegrees, queue, and result.

**Common follow-ups**

- How can DFS solve this? Use three node states—unvisited, visiting, and visited—to detect cycles while building a topological order.
- How can the algorithm return the number of courses that can be completed? Return the length of the processed order.
- How can you choose the smallest-numbered available course at each step? Use a min-heap instead of a queue, giving O((V + E) log V) time.
CodingMediumMolocoSoftware Engineer

4. LRU Cache (LeetCode)

Model answer

The task

Design a cache with a fixed capacity that supports retrieving and inserting key-value pairs. When an insertion exceeds capacity, evict the item that has gone unused for the longest time.

Key idea

Use a hash map for direct key lookup and a doubly linked list to track recency. Keep the most recently used item at the front; the least recently used item is at the back.

Approach

  1. Create a map from keys to their linked-list nodes.
  2. Use dummy head and tail nodes so items can be added or removed without special cases at the ends.
  3. On a successful get, move the node to the front and return its value; return -1 if the key is absent.
  4. On put, update and promote an existing node, or add a new node at the front.
  5. If the cache is over capacity, remove the node just before the tail and delete its key from the map.
class _Node:
    def __init__(self, key: int = 0, value: int = 0):
        self.key = key
        self.value = value
        self.prev = None
        self.next = None

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.nodes = {}

        # Items are stored between these sentinels.
        self.head = _Node()
        self.tail = _Node()
        self.head.next = self.tail
        self.tail.prev = self.head

    def _remove(self, node: _Node) -> None:
        node.prev.next = node.next
        node.next.prev = node.prev

    def _add_to_front(self, node: _Node) -> None:
        node.prev = self.head
        node.next = self.head.next
        self.head.next.prev = node
        self.head.next = node

    def _make_most_recent(self, node: _Node) -> None:
        self._remove(node)
        self._add_to_front(node)

    def get(self, key: int) -> int:
        node = self.nodes.get(key)
        if node is None:
            return -1

        self._make_most_recent(node)
        return node.value

    def put(self, key: int, value: int) -> None:
        node = self.nodes.get(key)

        if node is not None:
            node.value = value
            self._make_most_recent(node)
            return

        node = _Node(key, value)
        self.nodes[key] = node
        self._add_to_front(node)

        if len(self.nodes) > self.capacity:
            least_recent = self.tail.prev
            self._remove(least_recent)
            del self.nodes[least_recent.key]

Complexity:

  • Time: O(1) for get and put; map and list operations take constant time.
  • Space: O(capacity); the map and list store at most the cache’s capacity of entries.

Common follow-ups

  • How would you make the cache thread-safe? Protect operations with a lock.
  • What if entries expire after a time-to-live? Track expiration times and remove expired entries during access or with a cleanup mechanism.
  • How would you support eviction by frequency instead of recency? Track access counts and organize entries by frequency.
CodingMediumMolocoSoftware Engineer

5. Decode String (LeetCode)

Model answer

The task

Decode a string where a number before brackets indicates how many times to repeat the bracketed section. Sections may be nested.

Key idea

Parse the input into a compact tree of literal fragments and repeat nodes instead of expanding nested sections immediately. Then traverse that tree to produce the decoded string, avoiding repeated copying of large intermediate strings.

Approach

  1. Scan the input, accumulating each repetition count.
  2. On an opening bracket, save the current fragment list and count, then start a new list.
  3. On a closing bracket, wrap the current list in a repeat node and add it to its parent.
  4. Traverse the resulting structure with an explicit stack, yielding literal fragments as they are needed.
  5. Join the yielded fragments into the result.
class Solution:
    def decodeString(self, s: str) -> str:
        # Each repeat node is a (count, fragments) tuple.
        current = []
        stack = []
        count = 0

        for char in s:
            if "0" <= char <= "9":
                count = count * 10 + int(char)
            elif char == "[":
                stack.append((current, count))
                current = []
                count = 0
            elif char == "]":
                parent, repeat = stack.pop()
                # Omit zero repetitions so traversal skips empty sections.
                if repeat:
                    parent.append((repeat, current))
                current = parent
            else:
                current.append(char)

        def fragments():
            # Frames contain a fragment list, its next index, and
            # how many times to traverse that list.
            frames = [[current, 0, 1]]

            while frames:
                parts, index, remaining = frames[-1]

                if index == len(parts):
                    remaining -= 1
                    if remaining == 0:
                        frames.pop()
                    else:
                        frames[-1][1] = 0
                        frames[-1][2] = remaining
                    continue

                node = parts[index]
                frames[-1][1] += 1

                if isinstance(node, str):
                    yield node
                else:
                    repeat, nested = node
                    frames.append([nested, 0, repeat])

        return "".join(fragments())

Complexity:

  • Time: O(n + m), where n is the encoded length and m is the decoded length.
  • Space: O(n + m) for the parsed structure and returned string.

Common follow-ups

  • How would you handle malformed input? Validate bracket balance and ensure each opening bracket has a preceding count.
  • How could this support streaming output? Yield decoded fragments to a consumer instead of joining them into one string.
  • What if the grammar adds escaping or other operators? Extend the parser with explicit rules and represent each operation as a distinct node.
CodingMediumMolocoSoftware Engineer

6. Check if a Parentheses String Can Be Valid (LeetCode)

Model answer

The task

Given a parentheses string and a same-length lock string, decide whether changing any unlocked character to either parenthesis can make the string balanced.

Key idea

A valid sequence needs enough opening parentheses before every closing parenthesis, and enough closing parentheses after every opening parenthesis. Two greedy scans check these conditions: left to right, let unlocked positions act as opens; right to left, let them act as closes.

Approach

  1. Return False if the length is odd.
  2. Scan left to right, counting locked opens and unlocked positions as available opens.
  3. If that count ever drops below zero, a prefix has too many locked closes.
  4. Scan right to left, counting locked closes and unlocked positions as available closes.
  5. If that count ever drops below zero, a suffix has too many locked opens. Otherwise, return True.
class Solution:
    def canBeValid(self, s: str, locked: str) -> bool:
        n = len(s)
        if n % 2 == 1:
            return False

        balance = 0

        # Check that every prefix can have enough opening parentheses.
        for i in range(n):
            if s[i] == "(" or locked[i] == "0":
                balance += 1
            else:
                balance -= 1

            if balance < 0:
                return False

        balance = 0

        # Check that every suffix can have enough closing parentheses.
        for i in range(n - 1, -1, -1):
            if s[i] == ")" or locked[i] == "0":
                balance += 1
            else:
                balance -= 1

            if balance < 0:
                return False

        return True

Complexity:

  • Time: O(n), for two scans of the string.
  • Space: O(1), using only a counter.

Common follow-ups

  • Can this be solved in one pass? Track the minimum and maximum possible open counts, updating a range at each character.
  • What if there are multiple bracket types? Track types with a stack; a single balance count is not enough to enforce matching types.
  • Why check both directions? The forward scan catches excess locked closes; the reverse scan catches excess locked opens.
CodingMediumMolocoSoftware Engineer

7. Longest String Chain (LeetCode)

Model answer

The task

Given a list of distinct words, find the length of the longest sequence where each word is formed by inserting one letter anywhere into the previous word.

Key idea

For each word, try removing each character in turn. Any resulting word in the list can precede it in a chain. Dynamic programming stores the longest chain ending at each word.

Approach

  1. Sort the words by increasing length so shorter possible predecessors are processed first.
  2. For each word, initialize its best chain length to 1.
  3. Remove each character to generate possible predecessors.
  4. If a predecessor has already been processed, extend its chain by one.
  5. Track and return the maximum chain length.
from typing import List

class Solution:
    def longestStrChain(self, words: List[str]) -> int:
        # Process possible predecessors before their longer successors.
        words.sort(key=len)

        # dp[word] is the longest chain ending at word.
        dp = {}
        longest = 0

        for word in words:
            best = 1

            # Try removing each character to find a predecessor.
            for i in range(len(word)):
                predecessor = word[:i] + word[i + 1:]
                if predecessor in dp:
                    best = max(best, dp[predecessor] + 1)

            dp[word] = best
            longest = max(longest, best)

        return longest

Complexity:

  • Time: O(n log n + nL²), where sorting costs O(n log n) and generating and hashing each deletion costs O(L²) per word in the worst case.
  • Space: O(nL), for storing the words as keys in the dynamic-programming map.

Common follow-ups

  • What if words can repeat? Deduplicate them first; duplicates do not create a valid extra link.
  • How would you return an actual longest chain? Store the best predecessor alongside each word, then backtrack from the word with the largest DP value.
  • Can the approach handle an empty list? Yes; initialize the answer to zero and return it when no words are processed.
CodingHardMolocoSoftware Engineer

8. Minimum Window Substring (LeetCode)

Model answer

The task

Given strings s and t, return the shortest contiguous substring of s that contains every character in t, including repeated characters. Return an empty string if no such substring exists.

Key idea

Use a sliding window and character counts. Expand the right edge until the window contains all required character frequencies, then move the left edge rightward as far as possible while keeping the window valid.

Approach

  1. Count the required characters in t.
  2. Move the right edge across s, updating counts for relevant characters.
  3. Track how many distinct required characters have reached their needed frequencies.
  4. Whenever all are satisfied, record the window if it is shorter than the best found.
  5. Shrink from the left until the window is no longer valid, then continue expanding.
from collections import Counter, defaultdict

class Solution:
    def minWindow(self, s: str, t: str) -> str:
        if not s or not t:
            return ""

        need = Counter(t)
        window = defaultdict(int)
        required = len(need)
        formed = 0

        best_start = 0
        best_length = float("inf")
        left = 0

        for right, char in enumerate(s):
            if char in need:
                window[char] += 1
                if window[char] == need[char]:
                    formed += 1

            # Shrink while all required character counts are satisfied.
            while formed == required:
                length = right - left + 1
                if length < best_length:
                    best_start = left
                    best_length = length

                left_char = s[left]
                if left_char in need:
                    if window[left_char] == need[left_char]:
                        formed -= 1
                    window[left_char] -= 1
                left += 1

        if best_length == float("inf"):
            return ""
        return s[best_start:best_start + best_length]

Complexity:

  • Time: O(|s| + |t|), since each pointer advances at most the length of s.
  • Space: O(d), where d is the number of distinct characters in t.

Common follow-ups

  • What if t is empty? Return an empty string immediately, as handled above.
  • Can you return all shortest windows? Keep each window matching the minimum length instead of only one.
  • How does this scale to a stream? Maintain counts and window positions, while accounting for the storage needed to retain candidate characters.
CodingHardMolocoSoftware Engineer

9. Number of Islands II (LeetCode)

Model answer

The task

Track the number of connected land regions as cells are added to an initially empty grid. Return the count after each addition, treating repeated additions as no-ops.

Key idea

Use disjoint-set union (Union-Find) to represent connected land components. When a cell becomes land, it starts as one component; each neighboring land cell in a different component merges with it and reduces the count.

Approach

  1. Assign each grid cell a flat index and initialize its parent as inactive.
  2. For each added cell, activate it unless it is already land.
  3. Check its four orthogonal neighbors; for each active neighbor, union their sets.
  4. Append the current component count after processing each addition.
class Solution:
    def numIslands2(self, m: int, n: int, positions: list[list[int]]) -> list[int]:
        parent = [-1] * (m * n)
        size = [1] * (m * n)
        components = 0
        result = []

        def find(x: int) -> int:
            # Path halving keeps tree height nearly constant.
            while parent[x] != x:
                parent[x] = parent[parent[x]]
                x = parent[x]
            return x

        def union(a: int, b: int) -> bool:
            root_a = find(a)
            root_b = find(b)
            if root_a == root_b:
                return False

            # Union by size.
            if size[root_a] < size[root_b]:
                root_a, root_b = root_b, root_a
            parent[root_b] = root_a
            size[root_a] += size[root_b]
            return True

        for row, col in positions:
            cell = row * n + col

            if parent[cell] == -1:
                parent[cell] = cell
                components += 1

                for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                    nr, nc = row + dr, col + dc
                    if 0 <= nr < m and 0 <= nc < n:
                        neighbor = nr * n + nc
                        if parent[neighbor] != -1 and union(cell, neighbor):
                            components -= 1

            result.append(components)

        return result

Complexity:

  • Time: O(k α(mn)), where k is the number of additions; each uses a constant number of near-constant-time DSU operations.
  • Space: O(mn) for the parent and size arrays.

Common follow-ups

  • What if the grid is too large to allocate densely? Store only land cells in hash maps for a sparse DSU.
  • What if diagonal cells also connect? Check the four diagonal neighbors as well.
  • How would you support removing land? Standard DSU does not handle deletions directly; use offline processing or a more advanced dynamic-connectivity structure.
CodingHardMolocoSoftware Engineer

10. Trapping Rain Water (LeetCode)

Model answer

The task

Given an array of nonnegative bar heights, compute how much water remains trapped between the bars after rainfall. Each bar has unit width.

Key idea

Water above a position is limited by the shorter of the tallest bars to its left and right. With two pointers, process the side whose current height is lower: its boundary already determines the maximum water that position can hold, so no arrays of prefix and suffix maxima are needed.

Approach

  1. Start pointers at both ends and track the greatest height seen from each side.
  2. While the pointers have not crossed, compare their current heights.
  3. If the left height is lower, update the left maximum and add any water above the left bar, then advance the left pointer.
  4. Otherwise, do the symmetric operation on the right.
  5. Return the accumulated water.
from typing import List

class Solution:
    def trap(self, height: List[int]) -> int:
        left, right = 0, len(height) - 1
        left_max = right_max = 0
        water = 0

        while left < right:
            if height[left] < height[right]:
                # The right side is tall enough that the left maximum
                # determines the water level at this position.
                left_max = max(left_max, height[left])
                water += left_max - height[left]
                left += 1
            else:
                # Symmetrically, the right maximum determines this level.
                right_max = max(right_max, height[right])
                water += right_max - height[right]
                right -= 1

        return water

Complexity:

  • Time: O(n), because each pointer moves across the array at most once.
  • Space: O(1), because the algorithm uses only a fixed number of variables.

Common follow-ups

  • How can this be solved with dynamic programming? Precompute the maximum height to each position from the left and right, then sum the trapped water at each position.
  • How can a monotonic stack solve it? Keep indices of decreasing bar heights; when a taller bar arrives, pop a basin bottom and calculate the bounded layer.
  • What if bars have different widths? Track each bar’s width and use area rather than unit-width contributions; the boundary logic must account for the resulting horizontal spans.
CodingHardMolocoSoftware Engineer

11. Merge k Sorted Lists (LeetCode)

Model answer

The task

Combine several individually sorted linked lists into one sorted linked list. The result should reuse the input nodes rather than create a new node for every value.

Key idea

Keep the first unmerged node from each nonempty list in a min-heap. Repeatedly take the smallest node, append it to the result, and add its successor to the heap.

Approach

  1. Add each nonempty list’s head to the heap.
  2. Include a unique counter in each heap entry so equal values never require comparing nodes.
  3. Pop the smallest node and append it to the result.
  4. If that node has a successor, push the successor into the heap.
  5. Return the node after a dummy head.
import heapq
from typing import Optional

class ListNode:
    def __init__(self, val: int = 0, next: Optional["ListNode"] = None):
        self.val = val
        self.next = next

class Solution:
    def mergeKLists(
        self, lists: list[Optional[ListNode]]
    ) -> Optional[ListNode]:
        heap = []
        serial = 0  # Break ties without comparing ListNode objects.

        for node in lists:
            if node is not None:
                heapq.heappush(heap, (node.val, serial, node))
                serial += 1

        dummy = ListNode()
        tail = dummy

        while heap:
            _, _, node = heapq.heappop(heap)
            tail.next = node
            tail = node

            if node.next is not None:
                heapq.heappush(heap, (node.next.val, serial, node.next))
                serial += 1

        tail.next = None
        return dummy.next

Complexity:

  • Time: O(N log k), where each of the N nodes is pushed and popped once.
  • Space: O(k) for the heap, which holds at most one node per input list.

Common follow-ups

  • How can divide and conquer solve this? Merge lists in pairs over successive rounds, also taking O(N log k) time.
  • What if the lists are supplied as a stream? Keep one current node per active list in the heap and add lists as they arrive.
  • Can the inputs be modified? Yes; this solution relinks and reuses their nodes.
CodingHardMolocoSoftware Engineer

12. Making A Large Island (LeetCode)

Model answer

The task

Given a binary square grid, you may change at most one water cell into land. Return the largest island size achievable, where an island consists of horizontally or vertically connected land cells.

Key idea

First label each existing island with a unique ID and record its area. Flipping a water cell joins the distinct islands directly beside it, so its resulting area is one plus the sum of their areas.

Approach

  1. Scan the grid and iteratively traverse each unvisited land component.
  2. Replace its cells with a unique ID and store the component’s area.
  3. Track the largest existing island, which also covers the option of making no change.
  4. For each water cell, collect the IDs of its neighboring islands and sum their areas plus one.
  5. Return the largest area found. If the grid has no water, the existing island already covers the entire grid.
from typing import List

class Solution:
    def largestIsland(self, grid: List[List[int]]) -> int:
        n = len(grid)
        areas = {}
        island_id = 2  # Keep component IDs distinct from 0 and 1.
        largest = 0
        directions = ((1, 0), (-1, 0), (0, 1), (0, -1))

        # Label each land component and record its area.
        for row in range(n):
            for col in range(n):
                if grid[row][col] != 1:
                    continue

                stack = [(row, col)]
                grid[row][col] = island_id
                area = 0

                while stack:
                    r, c = stack.pop()
                    area += 1

                    for dr, dc in directions:
                        nr, nc = r + dr, c + dc
                        if (
                            0 <= nr < n
                            and 0 <= nc < n
                            and grid[nr][nc] == 1
                        ):
                            grid[nr][nc] = island_id
                            stack.append((nr, nc))

                areas[island_id] = area
                largest = max(largest, area)
                island_id += 1

        # Try turning each water cell into land.
        for row in range(n):
            for col in range(n):
                if grid[row][col] != 0:
                    continue

                adjacent_ids = set()
                for dr, dc in directions:
                    nr, nc = row + dr, col + dc
                    if 0 <= nr < n and 0 <= nc < n:
                        if grid[nr][nc] >= 2:
                            adjacent_ids.add(grid[nr][nc])

                merged_area = 1 + sum(areas[i] for i in adjacent_ids)
                largest = max(largest, merged_area)

        return largest

Complexity:

  • Time: O(n²), since each cell is visited a constant number of times.
  • Space: O(n²) in the worst case for the traversal stack and component areas.

Common follow-ups

  • What if the grid is all land? The initial largest-area value is already n².
  • Why use a set of neighboring IDs? A component can touch the water cell from multiple sides and should only be counted once.
  • Can this avoid modifying the input? Keep component labels in a separate matrix instead.
  • What if cells connect diagonally too? Add the four diagonal directions to the neighbor checks and component traversal.

Practice these out loud, don't memorise them

Reading an answer is not the same as being able to give one under pressure. ChannelPulse plays the interviewer, asks the follow-ups, and scores each answer with feedback and a model answer so you can hear the gap between what you said and what lands.

Get ChannelPulse Browse all questions