BitGo interview questions & answers

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

CodingMediumBitGoSoftware 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.
CodingMediumBitGoSoftware Engineer

2. Course Schedule (LeetCode)

Model answer

The task

Given a number of courses and prerequisite pairs, decide whether it’s possible to complete every course. A prerequisite pair means one course must be taken before another.

Key idea

Represent courses as a directed graph, with an edge from each prerequisite to the course that depends on it. A cycle means the courses in that cycle depend on one another, so not all courses can be completed.

Use Kahn’s topological-sort algorithm: repeatedly take courses with no remaining prerequisites and remove their outgoing edges.

Approach

  1. Create an adjacency list and count each course’s prerequisites (its indegree).
  2. Add every course with indegree zero to a queue.
  3. Remove courses from the queue, counting each as completed.
  4. Decrease the indegree of each dependent course; enqueue it when its indegree reaches zero.
  5. Return whether the number completed equals the total number of courses.
from collections import deque
from typing import List

class Solution:
    def canFinish(
        self, numCourses: int, prerequisites: List[List[int]]
    ) -> bool:
        # Edges point from prerequisite to the course that depends on it.
        graph = [[] for _ in range(numCourses)]
        indegree = [0] * numCourses

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

        # Begin with courses that have no prerequisites.
        ready = deque(
            course
            for course in range(numCourses)
            if indegree[course] == 0
        )

        completed = 0

        while ready:
            course = ready.popleft()
            completed += 1

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

        return completed == numCourses

Complexity:

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

Common follow-ups

  • How can you return a valid course order? Record courses as they are removed from the queue; return the order if it includes every course.
  • How can DFS detect a cycle? Track nodes as unvisited, visiting, or finished; reaching a visiting node reveals a cycle.
  • What if there are no courses? The algorithm returns True, since zero courses can all be completed.
CodingMediumBitGoSoftware Engineer

3. 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.
CodingMediumBitGoSoftware Engineer

4. Longest Palindromic Substring (LeetCode)

Model answer

The task

Given a string, return its longest contiguous substring that reads the same forward and backward. If several substrings have the same maximum length, returning any of them is acceptable.

Key idea

Every palindrome has a center: either a character (odd length) or the gap between two characters (even length). Expand outward from each possible center while the characters match, keeping track of the longest range found.

Approach

  1. Initialize the best range to an empty substring.
  2. For each character position, expand from that position to check odd-length palindromes.
  3. Also expand from the gap after that position to check even-length palindromes.
  4. When an expansion finds a longer palindrome, save its start and end indices.
  5. Return the substring covered by the saved range.
class Solution:
    def longestPalindrome(self, s: str) -> str:
        best_start = 0
        best_length = 0

        def expand(left: int, right: int) -> None:
            nonlocal best_start, best_length

            # Keep expanding while the current range is a palindrome.
            while left >= 0 and right < len(s) and s[left] == s[right]:
                length = right - left + 1
                if length > best_length:
                    best_start = left
                    best_length = length
                left -= 1
                right += 1

        for center in range(len(s)):
            expand(center, center)      # Odd-length palindromes
            expand(center, center + 1)  # Even-length palindromes

        return s[best_start:best_start + best_length]

Complexity:

  • Time: O(n²), since each of the O(n) centers can expand across O(n) characters.
  • Space: O(1), excluding the returned substring.

Common follow-ups

  • How can this be made linear time? Use Manacher’s algorithm to reuse information from previously explored centers.
  • How would you return all longest palindromic substrings? Track every range tied for the maximum length.
  • What if the input is empty? The method returns an empty string.
  • How would you count all palindromic substrings? Count each successful expansion instead of only saving the longest range.
CodingMediumBitGoSoftware Engineer

5. Longest Substring with At Most K Distinct Characters (LeetCode)

Model answer

The task

Given a string and an integer k, return the length of its longest contiguous substring containing no more than k distinct characters.

Key idea

Use a sliding window and track character frequencies inside it. Expand the window to the right, and move its left edge forward whenever the window contains too many distinct characters.

Approach

  1. Return 0 if k is zero or negative.
  2. Initialize a frequency map, a left boundary, and the best length found.
  3. Add each character as the right boundary advances.
  4. While the window has more than k distinct characters, remove characters from the left and delete any whose count reaches zero.
  5. Update the best length after the window is valid.
class Solution:
    def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
        if k <= 0 or not s:
            return 0

        counts = {}
        left = 0
        best = 0

        for right, char in enumerate(s):
            counts[char] = counts.get(char, 0) + 1

            # Shrink until the window has at most k distinct characters.
            while len(counts) > k:
                left_char = s[left]
                counts[left_char] -= 1
                if counts[left_char] == 0:
                    del counts[left_char]
                left += 1

            best = max(best, right - left + 1)

        return best

Complexity:

  • Time: O(n), since each character enters and leaves the window at most once.
  • Space: O(min(n, k)), for the character-frequency map after each window is made valid.

Common follow-ups

  • What if the substring must contain exactly k distinct characters? Track valid windows with exactly k distinct characters, or subtract the at-most-k-1 count from the at-most-k count.
  • What if the string is streamed and cannot be stored? Keep the window’s counts and boundaries as characters arrive; report the best length so far.
  • How would you return the substring itself? Store the start and end indices whenever a longer valid window is found.
CodingMediumBitGoSoftware Engineer

6. Gas Station (LeetCode)

Model answer

The task

Given circular arrays of fuel available and fuel required for each leg, find a starting station from which a vehicle can complete the full loop, or return -1 if no such start exists.

Key idea

If the total fuel is less than the total cost, no start can work. Otherwise, when the running fuel balance becomes negative, none of the stations in the current candidate segment can be a valid start, so begin a new candidate at the next station.

Approach

  1. Track the total fuel surplus across all stations.
  2. Track the surplus from the current candidate start.
  3. At each station, add its fuel minus its travel cost to both totals.
  4. If the candidate’s running surplus drops below zero, discard that segment and set the next station as the candidate.
  5. Return the candidate if the total surplus is nonnegative; otherwise, return -1.
class Solution:
    def canCompleteCircuit(self, gas: list[int], cost: list[int]) -> int:
        total_surplus = 0
        current_surplus = 0
        start = 0

        for i in range(len(gas)):
            surplus = gas[i] - cost[i]
            total_surplus += surplus
            current_surplus += surplus

            # No station in the current segment can be a valid start.
            if current_surplus < 0:
                start = i + 1
                current_surplus = 0

        return start if total_surplus >= 0 else -1

Complexity:

  • Time: O(n), where n is the number of stations; each station is processed once.
  • Space: O(1), using only a fixed number of variables.

Common follow-ups

  • Why can the candidate segment be discarded after the balance goes negative? Starting at any station within that segment leaves less fuel by the time it reaches the failure point, so it cannot succeed.
  • What if multiple valid starts exist? The algorithm returns one valid start; uniqueness is not guaranteed.
  • Can this be solved without storing prefix sums? Yes. The running surplus and total surplus are sufficient, as shown above.
CodingMediumBitGoSoftware Engineer

7. Lowest Common Ancestor of a Binary Tree (LeetCode)

Model answer

The task

Given the root of a binary tree and two nodes in it, return their lowest common ancestor: the deepest node that has both given nodes in its subtree, counting a node as its own descendant.

Key idea

A recursive search can return either a target node or the lowest common ancestor already found below it. When one target is found on each side of a node, that node is the answer.

Approach

  1. If the current node is None or is one of the targets, return it.
  2. Recursively search the left and right subtrees.
  3. If both searches return a node, the current node is the first shared ancestor.
  4. Otherwise, return whichever side found a target; if neither did, return None.
# The platform provides the TreeNode class.
class Solution:
    def lowestCommonAncestor(self, root, p, q):
        # A target (or an empty subtree) is returned directly.
        if root is None or root is p or root is q:
            return root

        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)

        # Targets found on opposite sides make this node their LCA.
        if left is not None and right is not None:
            return root

        # Otherwise, pass the result from the side that found a target.
        return left if left is not None else right

Complexity:

  • Time: O(n), where n is the number of nodes; each node is visited at most once.
  • Space: O(h), for the recursion stack, where h is the tree height.

Common follow-ups

  • What if either target might be absent? Track whether both targets were found, and return an answer only when both are present.
  • What if many LCA queries use the same tree? Preprocess ancestor information with binary lifting to answer each query in O(log n).
  • What if the tree has parent pointers? Move the nodes’ ancestors into a set, then walk upward from the other node to find the first match.
CodingMediumBitGoSoftware Engineer

8. Longest Consecutive Sequence (LeetCode)

Model answer

The task

Given an integer array, return the length of its longest run of consecutive values, regardless of their order in the array.

Key idea

Put the values in a set for fast membership checks. Only start counting from a value whose predecessor is absent, so each consecutive run is scanned once.

Approach

  1. Convert the array to a set, removing duplicates.
  2. For each distinct value, check whether its predecessor is in the set.
  3. If not, count upward while consecutive values remain present.
  4. Track and return the longest count.
from typing import List

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        values = set(nums)
        longest = 0

        for value in values:
            # Only begin counting at the start of a consecutive run.
            if value - 1 not in values:
                current = value
                length = 1

                while current + 1 in values:
                    current += 1
                    length += 1

                longest = max(longest, length)

        return longest

Complexity:

  • Time: O(n) on average; each distinct value is checked a constant number of times.
  • Space: O(n) for the set of distinct values.

Common follow-ups

  • How should an empty array be handled? The implementation returns 0.
  • What if the input contains duplicates? The set removes them without affecting the run length.
  • Can this be solved with sorting? Yes; sort the values and scan adjacent differences, taking O(n log n) time.
  • How could Union-Find be used? Treat each value as a node, union neighboring values that exist, then find the largest component.
CodingMediumBitGoSoftware Engineer

9. Longest Substring Without Repeating Characters (LeetCode)

Model answer

The task

Find the length of the longest contiguous section of a string in which every character appears at most once.

Key idea

Maintain a sliding window with no repeated characters. When a character repeats within the window, move the left edge just past its previous occurrence.

Approach

  1. Track each character’s most recent index in a dictionary.
  2. Keep left as the window’s starting index and best as its longest length so far.
  3. For each character, move left forward if its previous occurrence is inside the current window.
  4. Record the character’s current index and update best using the window length.
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        last_seen = {}
        left = 0
        best = 0

        for right, char in enumerate(s):
            # Skip past a repeated character if it is in the current window.
            if char in last_seen and last_seen[char] >= left:
                left = last_seen[char] + 1

            last_seen[char] = right
            best = max(best, right - left + 1)

        return best

Complexity:

  • Time: O(n), because each character is processed once.
  • Space: O(k), where k is the number of distinct characters encountered.

Common follow-ups

  • Return the substring itself: store the best window’s start and end indices when updating best.
  • Handle a stream of characters: keep the same window state and process each arriving character incrementally.
  • Use a fixed-size character set: replace the dictionary with an array of last-seen indices.
CodingHardBitGoSoftware 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.
CodingHardBitGoSoftware Engineer

11. Bus Routes (LeetCode)

Model answer

The task

Given bus routes as lists of stops, find the fewest buses needed to travel from a source stop to a destination stop. Return 0 if they are the same stop, or -1 if no route connects them.

Key idea

Use breadth-first search, where each level represents boarding one additional bus. Index routes by stop so that, from a stop, we can efficiently find the routes available there; process each route only once.

Approach

  1. Return 0 if the source and destination are identical.
  2. Build a map from each stop to the route indices that serve it.
  3. Start BFS from the source stop, tracking visited stops and routes.
  4. For each stop in a BFS level, explore each unvisited route serving it.
  5. Add newly reached stops to the next level; return the bus count if the destination is reached.
  6. If BFS finishes without reaching the destination, return -1.
from collections import defaultdict, deque
from typing import List

class Solution:
    def numBusesToDestination(
        self, routes: List[List[int]], source: int, target: int
    ) -> int:
        if source == target:
            return 0

        # Map each stop to the routes that serve it.
        routes_at_stop = defaultdict(list)
        for route_index, stops in enumerate(routes):
            for stop in stops:
                routes_at_stop[stop].append(route_index)

        queue = deque([source])
        visited_stops = {source}
        visited_routes = set()
        buses_taken = 0

        while queue:
            buses_taken += 1

            # All stops in this level are reachable with buses_taken buses.
            for _ in range(len(queue)):
                stop = queue.popleft()

                for route_index in routes_at_stop[stop]:
                    if route_index in visited_routes:
                        continue
                    visited_routes.add(route_index)

                    for next_stop in routes[route_index]:
                        if next_stop == target:
                            return buses_taken
                        if next_stop not in visited_stops:
                            visited_stops.add(next_stop)
                            queue.append(next_stop)

        return -1

Complexity:

  • Time: O(M), where M is the total number of stop entries across all routes; each route and its stops are processed at most once.
  • Space: O(M), for the stop-to-routes map and BFS tracking structures.

Common follow-ups

  • What if the source is not served by any route? The BFS finds no routes to explore and returns -1.
  • Can the search be performed over routes instead of stops? Yes; connect routes that share a stop and BFS between the source-serving and destination-serving routes.
  • How would you handle many queries on the same route network? Reuse the stop-to-routes index; consider preprocessing route connectivity if queries are frequent.
CodingHardBitGoSoftware Engineer

12. Largest Rectangle in Histogram (LeetCode)

Model answer

The task

Given bar heights in a histogram, find the largest area of a rectangle that fits entirely beneath consecutive bars.

Key idea

For each bar, treat its height as the rectangle’s limiting height. A monotonic stack lets us find the widest span for each such height when we encounter a shorter bar.

Approach

  1. Scan the bars from left to right, keeping indices in a stack whose heights are non-decreasing.
  2. When the current bar is shorter than the stack’s top, pop that bar: the current index is its first shorter bar on the right.
  3. The new stack top, if present, marks the first shorter bar on the left. Compute the area across the span between those boundaries.
  4. Process a virtual height of zero after the last bar to resolve all remaining indices.
  5. Track and return the largest area found.
class Solution:
    def largestRectangleArea(self, heights: list[int]) -> int:
        best = 0
        stack = []
        n = len(heights)

        # The virtual zero-height bar closes every remaining span.
        for i in range(n + 1):
            current_height = heights[i] if i < n else 0

            while stack and heights[stack[-1]] > current_height:
                height = heights[stack.pop()]

                # The new top is the nearest shorter bar to the left.
                left_boundary = stack[-1] if stack else -1
                width = i - left_boundary - 1
                best = max(best, height * width)

            # Do not store the virtual bar's index.
            if i < n:
                stack.append(i)

        return best

Complexity:

  • Time: O(n), since each bar is pushed and popped at most once.
  • Space: O(n), for the stack in the worst case.

Common follow-ups

  • How would you handle bars with different widths? Use cumulative horizontal positions to calculate span widths.
  • How can this solve the maximal rectangle in a binary matrix? Build histogram heights row by row and apply this method to each row.
  • What if bar heights change and queries arrive between updates? A segment tree can store range summaries, though supporting arbitrary updates efficiently is more involved.
CodingHardBitGoSoftware Engineer

13. Check if an Original String Exists Given Two Encoded Strings (LeetCode)

Model answer

The task

Determine whether two encoded strings can represent the same original string. A digit run can be split into one-, two-, or three-digit counts, each standing for that many arbitrary characters.

Key idea

Track how many unmatched wildcard characters have been generated by the first string minus those generated by the second. Parse digit runs by trying each valid prefix; when the difference is nonzero, match it against literal characters from the other string.

Approach

  1. Define a memoized search state by both string positions and the unmatched-character difference.
  2. If the current character is a digit, try consuming each prefix of up to three digits as a count.
  3. Otherwise, use the difference to consume a literal from the string with fewer unmatched characters.
  4. When the difference is zero and both characters are literals, require them to match.
  5. Succeed only when both strings are consumed and the difference is zero.
from functools import lru_cache

class Solution:
    def possiblyEquals(self, s1: str, s2: str) -> bool:
        n, m = len(s1), len(s2)

        @lru_cache(None)
        def search(i: int, j: int, diff: int) -> bool:
            # diff is unmatched wildcard characters from s1 minus s2.
            if i == n and j == m:
                return diff == 0

            if i < n and s1[i].isdigit():
                value = 0
                for end in range(i, min(i + 3, n)):
                    if not s1[end].isdigit():
                        break
                    value = value * 10 + int(s1[end])
                    if search(end + 1, j, diff + value):
                        return True
                return False

            if j < m and s2[j].isdigit():
                value = 0
                for end in range(j, min(j + 3, m)):
                    if not s2[end].isdigit():
                        break
                    value = value * 10 + int(s2[end])
                    if search(i, end + 1, diff - value):
                        return True
                return False

            if diff > 0:
                return j < m and search(i, j + 1, diff - 1)

            if diff < 0:
                return i < n and search(i + 1, j, diff + 1)

            return (
                i < n
                and j < m
                and s1[i] == s2[j]
                and search(i + 1, j + 1, 0)
            )

        return search(0, 0, 0)

Complexity:

  • Time: O(n · m · D · 3), where D is the number of reachable difference values; each state tries at most three digit prefixes.
  • Space: O(n · m · D) for memoized states and recursion.

Common follow-ups

  • What if counts can have more than three digits? Try all valid digit prefixes up to the permitted maximum length.
  • How would you return a matching original string? Record successful transitions, then reconstruct a witness by assigning compatible wildcard characters.
  • What edge cases are important? Digit runs at either end, unequal remaining wildcard counts, and literal mismatches.

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