BlackRock interview questions & answers

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

CodingEasyBlackRockSoftware Engineer

1. Two Sum (LeetCode)

Model answer

The task

Given a list of integers and a target, return the indices of two distinct elements whose values add up to the target. The usual version guarantees a valid pair.

Key idea

As we scan the list, store each value’s index in a hash table. For the current value, check whether its needed complement has already appeared; this finds a pair in one pass.

Approach

  1. Create a dictionary mapping previously seen values to their indices.
  2. For each element, compute the complement needed to reach the target.
  3. If that complement is in the dictionary, return its stored index and the current index.
  4. Otherwise, store the current value and index, then continue.
from typing import List

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # Map each value already visited to its index.
        seen = {}

        for index, value in enumerate(nums):
            complement = target - value

            # A match must come from an earlier, distinct element.
            if complement in seen:
                return [seen[complement], index]

            seen[value] = index

        # The standard problem guarantees a solution.
        raise ValueError("No two elements sum to the target")

Complexity:

  • Time: O(n), where n is the number of elements; each lookup and insertion is O(1) on average.
  • Space: O(n), for the dictionary of values seen so far.

Common follow-ups

  • What if there may be multiple valid pairs? Return the first pair found, or keep searching and collect pairs according to the required output rules.
  • What if the input is sorted? Use two pointers from opposite ends for O(1) extra space; preserve original indices if those are required.
  • What if values repeat? The dictionary stores indices, and checking before insertion ensures the current element is not paired with itself.
CodingEasyBlackRockSoftware Engineer

2. Happy Number (LeetCode)

Model answer

The task

Determine whether repeatedly replacing a positive integer with the sum of the squares of its digits eventually reaches 1. If the sequence loops without reaching 1, the number is not happy.

Key idea

The digit transformation is deterministic, so the sequence either reaches 1 or eventually repeats a value. Floyd’s cycle-finding algorithm detects a repeat using two pointers and constant extra space.

Approach

  1. Define a helper that computes the sum of the squared digits of a number.
  2. Start a slow pointer at the input and a fast pointer one transformation ahead.
  3. Advance the slow pointer once and the fast pointer twice per iteration.
  4. Stop if the fast pointer reaches 1 or the pointers meet.
  5. Return whether the fast pointer reached 1.
class Solution:
    def isHappy(self, n: int) -> bool:
        def next_value(value: int) -> int:
            total = 0
            while value > 0:
                digit = value % 10
                total += digit * digit
                value //= 10
            return total

        slow = n
        fast = next_value(n)

        while fast != 1 and slow != fast:
            slow = next_value(slow)
            fast = next_value(next_value(fast))

        return fast == 1

Complexity:

  • Time: O(log n), since digit transformations rapidly reduce the value and each transformation processes its digits.
  • Space: O(1), because only two pointers and a few temporary values are used.

Common follow-ups

  • How can a set solve this? Store values as they appear; a repeated value proves a cycle, using O(k) extra space for k visited values.
  • What if the transformation changes? The cycle-detection method still works for any deterministic transformation.
  • How would you test edge cases? Check 1, a known happy value, and values whose sequences enter a non-1 cycle.
CodingEasyBlackRockSoftware Engineer

3. Valid Parentheses (LeetCode)

Model answer

The task

Determine whether a string of opening and closing round, square, and curly brackets is correctly nested and matched. Return a boolean.

Key idea

A closing bracket must match the most recent unmatched opening bracket. A stack captures that order: push openings, and check each closing bracket against the stack’s top.

Approach

  1. Return False if the string has odd length.
  2. Map each closing bracket to its matching opening bracket.
  3. Scan the string from left to right.
  4. Push opening brackets onto the stack.
  5. For a closing bracket, return False if the stack is empty or its top does not match; otherwise pop.
  6. Return True only if the stack is empty after the scan.
class Solution:
    def isValid(self, s: str) -> bool:
        pairs = {")": "(", "]": "[", "}": "{"}
        openings = set(pairs.values())
        stack = []

        for char in s:
            if char in openings:
                stack.append(char)
            else:
                # A closing bracket must match the latest unmatched opening.
                if not stack or stack[-1] != pairs.get(char):
                    return False
                stack.pop()

        # Unmatched opening brackets make the sequence invalid.
        return not stack

Complexity:

  • Time: O(n), where n is the string length; each character is processed once.
  • Space: O(n) in the worst case, when all characters are opening brackets.

Common follow-ups

  • How would you support additional bracket types? Add their matching pairs to the map.
  • Can you stop early? Yes; return False as soon as a closing bracket mismatches or has no opening bracket.
  • What if the input includes non-bracket characters? Define how to handle them, then either ignore them or reject them during the scan.
CodingEasyBlackRockSoftware Engineer

4. Best Time to Buy and Sell Stock (LeetCode)

Model answer

The task

Given daily stock prices, find the greatest profit possible from one buy followed by one later sale. If no sale would make money, return zero.

Key idea

As we scan the prices, keep the lowest price seen so far. Treat each current price as a possible sale and update the best profit using the difference from that minimum.

Approach

  1. Initialize the minimum price to a value larger than any price and the best profit to zero.
  2. Visit each price in order.
  3. Update the minimum price with the current price.
  4. Check the profit from selling today and update the best profit.
  5. Return the best profit.
class Solution:
    def maxProfit(self, prices: list[int]) -> int:
        min_price = float("inf")
        best_profit = 0

        for price in prices:
            # The current price can be a new best day to buy.
            min_price = min(min_price, price)

            # Or it can be the day to sell after the cheapest earlier buy.
            best_profit = max(best_profit, price - min_price)

        return best_profit

Complexity:

  • Time: O(n), where n is the number of prices; each is processed once.
  • Space: O(1), since only a few variables are stored.

Common follow-ups

  • What if multiple buy-and-sell transactions are allowed? Sum the gains from every adjacent price increase.
  • What if a transaction fee is charged? Track the best holding and non-holding profits, incorporating the fee when selling.
  • What if at most k transactions are allowed? Use dynamic programming over the number of completed transactions and whether a share is currently held.
CodingEasyBlackRockSoftware Engineer

5. Climbing Stairs (LeetCode)

Model answer

The task

Count how many distinct ways there are to reach the top of a staircase with n steps when each move advances either one or two steps.

Key idea

To reach step i, the last move must come from step i - 1 or i - 2. Thus the number of ways to reach i is the sum of the ways to reach those two earlier steps. Only the previous two counts are needed, so there is no need to store a full table.

Approach

  1. Set the number of ways to reach step 0 to 1, representing the single empty sequence of moves.
  2. Set the number of ways to reach step 1 to 1.
  3. For each step from 2 through n, add the counts for the preceding two steps.
  4. Return the count for step n.
class Solution:
    def climbStairs(self, n: int) -> int:
        # Ways to reach steps 0 and 1.
        two_back = 1
        one_back = 1

        # Build the count using the two preceding results.
        for _ in range(2, n + 1):
            current = two_back + one_back
            two_back = one_back
            one_back = current

        return one_back

Complexity:

  • Time: O(n), since each step is processed once.
  • Space: O(1), since only two prior counts are retained.

Common follow-ups

  • What if each move can advance 1, 2, or 3 steps? Sum the counts for the previous three steps.
  • What if the result must be returned modulo a number? Apply the modulus after each addition.
  • What if some steps are forbidden? Set their ways count to zero and use dynamic programming for the allowed steps.
CodingMediumBlackRockSoftware Engineer

6. Integer to Roman (LeetCode)

Model answer

The task

Convert a positive integer into its standard Roman numeral representation, using subtractive forms such as IV and CM where appropriate.

Key idea

Process Roman numeral values from largest to smallest, including the six subtractive combinations as single entries. At each value, emit it as many times as possible, then continue with the remainder.

Approach

  1. List the values and their Roman numeral symbols in descending order.
  2. For each value, use integer division to determine how many times it fits in the remaining number.
  3. Append that many copies of its symbol.
  4. Subtract the represented amount and continue.
  5. Join the symbols to form the result.
class Solution:
    def intToRoman(self, num: int) -> str:
        # Include subtractive pairs alongside the ordinary symbols.
        values = [
            (1000, "M"),
            (900, "CM"),
            (500, "D"),
            (400, "CD"),
            (100, "C"),
            (90, "XC"),
            (50, "L"),
            (40, "XL"),
            (10, "X"),
            (9, "IX"),
            (5, "V"),
            (4, "IV"),
            (1, "I"),
        ]

        result = []

        for value, symbol in values:
            count, num = divmod(num, value)
            result.append(symbol * count)

        return "".join(result)

Complexity:

  • Time: O(1) for the standard bounded integer range; each of the fixed 13 values is checked.
  • Space: O(1) auxiliary space; the result uses O(1) space for the bounded output.

Common follow-ups

  • How would you convert a Roman numeral back to an integer? Scan symbols and subtract a value when it is less than the next symbol.
  • What if the input can exceed the standard Roman numeral range? Define an extension convention, such as overlines for thousands, before adapting the mapping.
  • How would you validate a Roman numeral string? Parse it, convert it to an integer, then convert that integer back and compare with the original.
CodingMediumBlackRockSoftware Engineer

7. Transform Binary String Using Subsequence Sort (LeetCode)

Model answer

The task

The title suggests transforming a binary string by sorting selected subsequences. The metadata does not specify the target string or whether the goal is to check feasibility, find a minimum number of operations, or produce a sequence of operations.

Key idea

Those details change the algorithm, so a specific greedy strategy or result would be a guess. A useful general starting point is to model one operation precisely and track how it changes the positions of the 1 bits.

Approach

  1. Represent a selected subsequence by its indices in increasing order.
  2. Read the bits at those indices and sort them.
  3. Write the sorted bits back to the same indices; leave all other positions unchanged.
  4. To solve the full task, compare the resulting state against the stated target and optimize the required objective.
def sort_selected_subsequence(binary: str, indices: list[int]) -> str:
    """Apply one ascending sort to the bits at the given indices."""
    chars = list(binary)

    if any(i < 0 or i >= len(chars) for i in indices):
        raise IndexError("Subsequence index is out of range")
    if any(indices[i] >= indices[i + 1] for i in range(len(indices) - 1)):
        raise ValueError("Indices must be strictly increasing")

    selected = sorted(chars[i] for i in indices)

    for index, bit in zip(indices, selected):
        chars[index] = bit

    return "".join(chars)

Complexity:

  • Time: O(n + k log k), where n is the string length and k is the number of selected indices; sorting dominates for large subsequences.
  • Space: O(n + k), for the copied string and sorted selected bits.

Common follow-ups

  • Is the goal to reach a particular target, or merely to sort the whole string?
  • Is the task asking for feasibility, the minimum number of operations, or an operation sequence?
  • Can a subsequence contain any indices, and must it be nonempty?
  • Are repeated operations allowed, and do they have different costs?
CodingMediumBlackRockSoftware Engineer

8. 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.
CodingMediumBlackRockSoftware Engineer

9. Lowest Common Ancestor of a Binary Search Tree (LeetCode)

Model answer

The task

Given a binary search tree and two nodes in it, return their lowest common ancestor: the deepest node that is an ancestor of both.

Key idea

In a BST, values smaller than a node are in its left subtree, and larger values are in its right. If both target values lie on the same side, the ancestor must be there; otherwise, the current node is where their paths meet.

Approach

  1. Start at the root.
  2. If both target values are smaller, move left.
  3. If both are larger, move right.
  4. Otherwise, the current node is the lowest common ancestor; return it.
from typing import Optional

# The platform provides TreeNode.
class Solution:
    def lowestCommonAncestor(
        self,
        root: "TreeNode",
        p: "TreeNode",
        q: "TreeNode",
    ) -> Optional["TreeNode"]:
        current = root

        while current is not None:
            if p.val < current.val and q.val < current.val:
                current = current.left
            elif p.val > current.val and q.val > current.val:
                current = current.right
            else:
                # The paths split here, or one target is this node.
                return current

        return None

Complexity:

  • Time: O(h), where h is the tree height and each step moves down one level.
  • Space: O(1), using only an iterative traversal.

Common follow-ups

  • What if the nodes might not be in the tree? Verify both nodes exist before returning an ancestor.
  • How does the approach change for a general binary tree? Search both subtrees recursively; values no longer identify the direction.
  • What if many ancestor queries are needed? Preprocess ancestors with binary lifting to answer each query in O(log n).
  • What if the BST is skewed? The traversal can take O(n); balancing the tree keeps its height logarithmic.
CodingMediumBlackRockSoftware Engineer

10. Group Anagrams (LeetCode)

Model answer

The task

Partition the input strings into groups so that strings in the same group contain the same characters with the same frequencies. The order of the groups does not matter.

Key idea

Sort the characters of each string to create a canonical key. Anagrams produce the same key, so a hash table can collect them together.

Approach

  1. Create a mapping from canonical keys to lists of original strings.
  2. For each string, sort its characters and use the result as its key.
  3. Append the string to the list for that key.
  4. Return all grouped lists.
from collections import defaultdict
from typing import List

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        groups = defaultdict(list)

        for word in strs:
            # Anagrams have identical sorted-character representations.
            key = "".join(sorted(word))
            groups[key].append(word)

        return list(groups.values())

Complexity:

  • Time: O(n · k log k), where n is the number of strings and k is the maximum string length.
  • Space: O(n · k) to store the grouped strings and their keys.

Common follow-ups

  • Can this be faster for a fixed alphabet? Use a character-frequency tuple as the key, computing it in O(k) per string.
  • Does this work with uppercase letters or Unicode? Yes; sorting characters works for any Python strings.
  • Can groups be returned in a deterministic order? Sort the groups, or their keys, before returning them.
  • What if memory is limited? Consider processing input in batches or grouping externally by canonical key.

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