Jane Street interview questions & answers

20 real Jane Street interview questions with full model answers — Product & growth, Coding, Technical. Drawn from the same verified bank ChannelPulse drills from (25 Jane Street questions in total).

CodingEasyJane StreetSoftware 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.
CodingEasyJane StreetSoftware Engineer

2. Teemo Attacking (LeetCode)

Model answer

The task

Given sorted attack times and a poison duration, find the total time the target is poisoned. Overlapping poison intervals count only once.

Key idea

Each attack contributes poison time until the next attack or until its own duration ends, whichever comes first. The final attack contributes its full duration.

Approach

  1. If there are no attacks, return 0.
  2. For each attack except the last, add the smaller of the duration and the gap to the next attack.
  3. Add the full duration for the final attack.
  4. Return the accumulated time.
from typing import List

class Solution:
    def findPoisonedDuration(
        self, timeSeries: List[int], duration: int
    ) -> int:
        if not timeSeries:
            return 0

        total = 0

        # Each attack's contribution ends at the next attack,
        # unless its poison duration ends sooner.
        for i in range(len(timeSeries) - 1):
            gap = timeSeries[i + 1] - timeSeries[i]
            total += min(duration, gap)

        # The final attack has no later attack to shorten its interval.
        total += duration
        return total

Complexity:

  • Time: O(n), where n is the number of attack times.
  • Space: O(1), using only a constant amount of extra storage.

Common follow-ups

  • What if the attack times are unsorted? Sort them first, taking O(n log n) time.
  • What if each attack has a different duration? Add each interval’s contribution, clipping it at the next attack, or merge the intervals directly.
  • How would you process attacks as a stream? Track the previous attack and the current poisoned-until time, finalizing elapsed contributions as new attacks arrive.
  • What if timestamps are very large? The interval-based calculation already avoids iterating over individual seconds.
CodingEasyJane StreetSoftware 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.
CodingEasyJane StreetSoftware Engineer

4. Add Strings (LeetCode)

Model answer

The task

Given two strings representing nonnegative integers, return their sum as a string. The solution should perform the addition directly on the digits rather than converting either entire string to an integer.

Key idea

Add digits from right to left, keeping a carry just as in manual addition. Since the strings can have different lengths, treat missing digits as zero.

Approach

  1. Start at the final digit of each string with a carry of zero.
  2. While either string has digits left or a carry remains, read the next digits (using zero if a string is exhausted).
  3. Add the digits and carry; append the result’s ones digit and update the carry.
  4. Reverse the collected digits to form the answer.
class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        i = len(num1) - 1
        j = len(num2) - 1
        carry = 0
        result = []

        while i >= 0 or j >= 0 or carry:
            digit1 = ord(num1[i]) - ord("0") if i >= 0 else 0
            digit2 = ord(num2[j]) - ord("0") if j >= 0 else 0

            total = digit1 + digit2 + carry
            result.append(str(total % 10))
            carry = total // 10

            i -= 1
            j -= 1

        return "".join(reversed(result))

Complexity:

  • Time: O(max(n, m)), where n and m are the input lengths.
  • Space: O(max(n, m)) for the output digits.

Common follow-ups

  • How would you subtract two nonnegative number strings? Compare magnitudes first, then subtract digits with borrowing.
  • How would you handle negative values? Parse and track each sign, then add or subtract magnitudes as appropriate.
  • How would you add many number strings? Accumulate them with this routine, or use a digit-wise accumulator for a single pass over all inputs.
CodingEasyJane StreetSoftware Engineer

5. Longest Common Prefix (LeetCode)

Model answer

The task

Given a list of strings, return the longest string that is a prefix of every entry. If there is no shared prefix, return an empty string.

Key idea

Compare characters at the same position across all strings, starting from the first string. Stop at the first mismatch or when any string runs out.

Approach

  1. If the list is empty, return an empty string.
  2. Scan each character of the first string from left to right.
  3. For each position, compare that character with the character at the same position in every other string.
  4. If a string is too short or a character differs, return the matching prefix before that position.
  5. If all positions match, return the first string.
from typing import List

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""

        first = strs[0]

        for i, char in enumerate(first):
            for word in strs[1:]:
                if i == len(word) or word[i] != char:
                    return first[:i]

        return first

Complexity:

  • Time: O(S), where S is the total number of characters inspected.
  • Space: O(1) auxiliary space, excluding the returned prefix.

Common follow-ups

  • How would you handle many prefix queries over the same set of strings? Build a trie once, then traverse it to find shared prefixes.
  • Could sorting help? Yes. Sort the strings and compare only the first and last; their common prefix is shared by all strings.
  • What if strings arrive as a stream? Keep a running prefix and shorten it as each new string arrives.
CodingEasyJane StreetSoftware Engineer

6. Count Common Words With One Occurrence (LeetCode)

Model answer

The task

Given two lists of words, count how many distinct words occur exactly once in each list.

Key idea

Count each list independently, then count words whose frequency is one in both. Hash maps make the frequency checks efficient.

Approach

  1. Build a frequency map for the first list.
  2. Build a frequency map for the second list.
  3. Count words in the first map that occur once and also occur once in the second map.
  4. Return that count.
from collections import Counter
from typing import List

class Solution:
    def countWords(self, words1: List[str], words2: List[str]) -> int:
        counts1 = Counter(words1)
        counts2 = Counter(words2)

        return sum(
            count == 1 and counts2[word] == 1
            for word, count in counts1.items()
        )

Complexity:

  • Time: O(n + m), to count the words and check the maps.
  • Space: O(u + v), for the distinct words in the two lists.

Common follow-ups

  • What if a word must occur exactly k times in each list? Check both frequency maps against k.
  • Can you reduce memory use? If one list is already frequency-counted, process the other while retaining only relevant counts.
  • Are words case-sensitive? Normalize each word before counting if case should be ignored.
CodingEasyJane StreetSoftware Engineer

7. Add Two Integers (LeetCode)

Model answer

The task

Return the sum of two integers.

Key idea

Integer addition directly gives the result. No iteration or extra data structures are needed.

Approach

  1. Accept the two integer arguments.
  2. Add them using +.
  3. Return the result.
class Solution:
    def sum(self, num1: int, num2: int) -> int:
        # Return the sum of the two integers.
        return num1 + num2

Complexity:

  • Time: O(1), since addition takes constant time for fixed-width integers.
  • Space: O(1), as no additional storage is used.

Common follow-ups

  • What if one or both integers are negative? The same addition works.
  • How would you add without using +? Use bitwise operations to compute carry and partial sums.
  • What if the integers are extremely large? Use arbitrary-precision integers, or a representation suited to the required size.
CodingMediumJane StreetSoftware Engineer

8. Walking Robot Simulation (LeetCode)

Model answer

The task

Simulate a robot starting at the origin, facing north. It turns left or right on designated commands and otherwise moves forward, stopping before any obstacle; return the greatest squared distance from the origin reached.

Key idea

Represent the four directions as vectors and track the current direction with an index. Store obstacles in a set for fast lookup, and update the maximum distance after each step.

Approach

  1. Convert the obstacles into a set of coordinate pairs.
  2. Initialize the robot at the origin, facing north, with the maximum distance set to zero.
  3. For each command, update the direction index for a turn.
  4. For a movement command, attempt each forward step and stop if the next position is blocked.
  5. After each successful step, update the maximum squared distance.
class Solution:
    def robotSim(self, commands: list[int], obstacles: list[list[int]]) -> int:
        blocked = {(x, y) for x, y in obstacles}

        # Directions in clockwise order: north, east, south, west.
        directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
        direction = 0
        x = y = 0
        max_distance_squared = 0

        for command in commands:
            if command == -2:  # Turn left.
                direction = (direction - 1) % 4
            elif command == -1:  # Turn right.
                direction = (direction + 1) % 4
            else:
                dx, dy = directions[direction]

                for _ in range(command):
                    next_x, next_y = x + dx, y + dy
                    if (next_x, next_y) in blocked:
                        break

                    x, y = next_x, next_y
                    max_distance_squared = max(
                        max_distance_squared, x * x + y * y
                    )

        return max_distance_squared

Complexity:

  • Time: O(C + S), where C is the number of commands and S is the total number of attempted forward steps.
  • Space: O(B), where B is the number of obstacles stored in the set.

Common follow-ups

  • What if the robot must return its final position and direction? Return x, y, and the direction index along with the maximum.
  • What if there are many more commands than obstacles? The obstacle set already gives expected O(1) lookup per attempted step.
  • Can you avoid simulating every step? With axis-aligned obstacles, ordered obstacle indexes by row and column can help find the nearest blocker for each movement segment.
CodingMediumJane StreetSoftware Engineer

9. The United States uses the imperial system of weights and measures, which means that there are many different, seemingly arbitrary units to measure…

The full question

The United States uses the imperial system of weights and measures, which means that there are many different, seemingly arbitrary units to measure distance. There are 12 inches in a foot, 3 feet in a yard, 22 yards in a chain, and so on.

Create a data structure that can efficiently convert a certain quantity of one unit to the correct amount of any other unit. You should also allow for additional units to be added to the system.

Model answer

class UnitConverter {
  constructor() {
    this.parent = new Map();
    this.size = new Map();
    // scale[u] is the number of parent[u] units equal to one u.
    this.scale = new Map();
  }

  addUnit(unit) {
    if (!this.parent.has(unit)) {
      this.parent.set(unit, unit);
      this.size.set(unit, 1);
      this.scale.set(unit, 1);
    }
  }

  // factor means: 1 unitA = factor units of unitB.
  addConversion(unitA, unitB, factor) {
    if (!Number.isFinite(factor) || factor <= 0) {
      throw new Error("Conversion factor must be positive and finite");
    }

    this.addUnit(unitA);
    this.addUnit(unitB);

    const [rootA, weightA] = this.find(unitA);
    const [rootB, weightB] = this.find(unitB);

    if (rootA === rootB) {
      const impliedFactor = weightA / weightB;
      const tolerance = 1e-10 * Math.max(1, Math.abs(factor));
      if (Math.abs(impliedFactor - factor) > tolerance) {
        throw new Error("Inconsistent conversion");
      }
      return;
    }

    if (this.size.get(rootA) < this.size.get(rootB)) {
      // Attach rootA under rootB.
      this.parent.set(rootA, rootB);
      this.scale.set(rootA, (factor * weightB) / weightA);
      this.size.set(rootB, this.size.get(rootB) + this.size.get(rootA));
    } else {
      // Attach rootB under rootA.
      this.parent.set(rootB, rootA);
      this.scale.set(rootB, weightA / (factor * weightB));
      this.size.set(rootA, this.size.get(rootA) + this.size.get(rootB));
    }
  }

  find(unit) {
    if (!this.parent.has(unit)) throw new Error(`Unknown unit: ${unit}`);
    const parent = this.parent.get(unit);
    if (parent === unit) return [unit, 1];

    const [root, parentWeight] = this.find(parent);
    const totalWeight = this.scale.get(unit) * parentWeight;
    this.parent.set(unit, root);
    this.scale.set(unit, totalWeight);
    return [root, totalWeight];
  }

  convert(amount, from, to) {
    const [rootFrom, scaleFrom] = this.find(from);
    const [rootTo, scaleTo] = this.find(to);
    if (rootFrom !== rootTo) {
      throw new Error(`No conversion path from ${from} to ${to}`);
    }
    return amount * scaleFrom / scaleTo;
  }
}

const units = new UnitConverter();
units.addConversion("inch", "foot", 1 / 12);
units.addConversion("foot", "yard", 1 / 3);
units.addConversion("yard", "chain", 1 / 22);
console.log(units.convert(2, "chain", "inch")); // 1584

units.addConversion("mile", "chain", 80); // Add units as needed.
console.log(units.convert(1, "mile", "yard")); // 1760
  • Store each unit's scale relative to its disjoint-set parent; path compression makes repeated lookups efficient.
  • Adding a conversion joins two sets, or checks that a new relationship agrees with existing conversions.
  • Complexity: Adding a conversion and converting are amortized O(α(n)); storage is O(n).
CodingMediumJane StreetSoftware Engineer

10. 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.
CodingMediumJane StreetSoftware Engineer

11. Number of Orders in the Backlog (LeetCode)

Model answer

The task

Process incoming buy and sell orders, matching them whenever the best available prices are compatible. Return the total number of unfilled orders, modulo \(10^9+7\).

Key idea

Keep unmatched buy orders in a max-heap and unmatched sell orders in a min-heap. A new order only needs to match against the best-priced order on the opposite side; stop when prices no longer cross.

Approach

  1. Initialize a max-heap for buys and a min-heap for sells.
  2. For each order, repeatedly inspect the best opposing price.
  3. If prices are compatible, match as many units as possible and keep any remainder.
  4. Add any unmatched units to the heap for their order type.
  5. Sum the remaining quantities and take the result modulo \(10^9+7\).
from typing import List
import heapq

class Solution:
    def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:
        buy_heap = []   # Entries are (-price, quantity), so the highest price comes first.
        sell_heap = []  # Entries are (price, quantity), so the lowest price comes first.

        for price, quantity, order_type in orders:
            if order_type == 0:  # Buy order: match against the cheapest sells.
                while quantity > 0 and sell_heap and sell_heap[0][0] <= price:
                    sell_price, sell_quantity = heapq.heappop(sell_heap)
                    matched = min(quantity, sell_quantity)
                    quantity -= matched
                    sell_quantity -= matched

                    if sell_quantity > 0:
                        heapq.heappush(sell_heap, (sell_price, sell_quantity))

                if quantity > 0:
                    heapq.heappush(buy_heap, (-price, quantity))

            else:  # Sell order: match against the highest-priced buys.
                while quantity > 0 and buy_heap and -buy_heap[0][0] >= price:
                    neg_buy_price, buy_quantity = heapq.heappop(buy_heap)
                    matched = min(quantity, buy_quantity)
                    quantity -= matched
                    buy_quantity -= matched

                    if buy_quantity > 0:
                        heapq.heappush(buy_heap, (neg_buy_price, buy_quantity))

                if quantity > 0:
                    heapq.heappush(sell_heap, (price, quantity))

        modulus = 10**9 + 7
        return sum(quantity for _, quantity in buy_heap + sell_heap) % modulus

Complexity:

  • Time: O(n log n), where each order causes at most heap operations per match.
  • Space: O(n), for the unmatched orders stored in the heaps.

Common follow-ups

  • What if orders can be cancelled? Track order IDs and use lazy deletion when cancelled orders reach a heap’s top.
  • What if matching happens continuously in a distributed system? Partition by instrument and serialize updates per instrument to preserve price priority.
  • What if you need the total at every step? Compute and record the backlog sum after processing each order.
CodingMediumJane StreetSoftware Engineer

12. Add Two Numbers (LeetCode)

Model answer

The task

Each linked list stores a non-negative integer one digit per node, with the least significant digit first. Return a new linked list containing their sum in the same order.

Key idea

Add corresponding digits from left to right, carrying any value of 10 or more into the next position. Continue until both lists and the carry are exhausted, so a final carry gets its own node.

Approach

  1. Create a dummy node to simplify building the result.
  2. Track the current nodes and a carry initialized to zero.
  3. While either list has digits or a carry remains, add the available digits and carry.
  4. Use division and remainder by 10 to get the next carry and result digit.
  5. Append the digit, advance whichever input nodes exist, and return the node after the dummy.
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 addTwoNumbers(
        self, l1: Optional[ListNode], l2: Optional[ListNode]
    ) -> Optional[ListNode]:
        dummy = ListNode()
        tail = dummy
        carry = 0

        while l1 is not None or l2 is not None or carry:
            total = carry

            if l1 is not None:
                total += l1.val
                l1 = l1.next

            if l2 is not None:
                total += l2.val
                l2 = l2.next

            carry, digit = divmod(total, 10)
            tail.next = ListNode(digit)
            tail = tail.next

        return dummy.next

Complexity:

  • Time: O(max(m, n)), where m and n are the list lengths.
  • Space: O(max(m, n)) for the newly created result; O(1) auxiliary space.

Common follow-ups

  • What if digits are stored most significant first? Reverse the lists, or use stacks to add from the ends without modifying them.
  • Can the input lists be modified to save space? Reuse nodes from one list to store result digits, while handling any remaining carry.
  • How would you implement this recursively? Recurse node by node, passing the carry and treating a missing node as digit zero.
CodingMediumJane StreetSoftware Engineer

13. Generate a finite, but an arbitrarily large binary tree quickly in O(1).

The full question

Generate a finite, but an arbitrarily large binary tree quickly in O(1). That is, generate() should return a tree whose size is unbounded but finite.

Model answer

class LazyNode {
  constructor(remainingDepth) {
    this.remainingDepth = remainingDepth;
  }

  get left() {
    return this.remainingDepth === 0
      ? null
      : new LazyNode(this.remainingDepth - 1n);
  }

  get right() {
    return this.remainingDepth === 0
      ? null
      : new LazyNode(this.remainingDepth - 1n);
  }
}

// Returns a full binary tree of the requested depth without building its nodes.
// Depth 0 is a single leaf; depth d has 2^(d + 1) - 1 logical nodes.
function generate(depth) {
  if (typeof depth !== "bigint" || depth < 0n) {
    throw new TypeError("depth must be a non-negative BigInt");
  }
  return new LazyNode(depth);
}

const tree = generate(1000000n); // Constant-time construction.
console.log(tree.left.left.remainingDepth); // 999998n
  • There is an important constraint: a materialized tree cannot be created in O(1) time if its size is unbounded; writing its nodes takes time proportional to the size.
  • This uses lazy child getters. Construction is O(1) for any supplied finite depth, while accessing a child creates only that node. The depth input makes the requested size explicit.
  • If generate() must take no input and guarantee an unbounded yet finite size, the requirement is not well-defined: a no-input algorithm cannot guarantee an arbitrarily large finite result. A size/depth input or a specified source of randomness is needed.

Complexity: O(1) construction time and space; fully materializing the tree takes O(N) time and space for N nodes.

CodingMediumJane StreetSoftware Engineer

14. Suppose you are given a table of currency exchange rates, represented as a 2D array.

The full question

Suppose you are given a table of currency exchange rates, represented as a 2D array. Determine whether there is a possible arbitrage: that is, whether there is some sequence of trades you can make, starting with some amount A of any currency, so that you can end up with some amount greater than A of that currency. There are no transaction costs and you can trade fractional quantities.

Model answer

function hasArbitrage(rates) {
  const n = rates.length;
  const dist = Array(n).fill(0);
  const EPS = 1e-12;

  // A trade from i to j has weight -log(rate[i][j]).
  // A profitable cycle is therefore a negative-weight cycle.
  for (let pass = 0; pass < n; pass++) {
    let changed = false;

    for (let i = 0; i < n; i++) {
      for (let j = 0; j < n; j++) {
        const rate = rates[i][j];
        if (rate <= 0) continue; // No trade along a zero-rate edge.

        const weight = -Math.log(rate);
        if (dist[i] + weight < dist[j] - EPS) {
          dist[j] = dist[i] + weight;
          changed = true;

          // A relaxation on the nth pass implies a negative cycle.
          if (pass === n - 1) return true;
        }
      }
    }

    if (!changed) return false;
  }

  return false;
}

// Example: the cycle 0 -> 1 -> 2 -> 0 has product 1.1 * 1.1 * 0.9 > 1.
console.log(hasArbitrage([
  [1, 1.1, 1],
  [1, 1, 1.1],
  [0.9, 1, 1],
])); // true
  • Taking logs turns a cycle's exchange-rate product into a sum; negating the logs makes profitable cycles negative-weight cycles.
  • Bellman–Ford starts every distance at zero, so it detects a cycle anywhere in the graph without choosing a starting currency.
  • EPS helps avoid treating tiny floating-point rounding differences as arbitrage.

Complexity: O(n^3) time for the dense rate table and O(n) extra space.

CodingMediumJane StreetSoftware Engineer

15. Given integers M and N, write a program that counts how many positive integer pairs (a, b) satisfy the following conditions: a + b = M a XOR b = N

Model answer

function countPositivePairs(M, N) {
  M = BigInt(M);
  N = BigInt(N);
  if (M < 0n || N < 0n || M < N) return 0n;

  const difference = M - N;
  if (difference % 2n !== 0n) return 0n;

  const both = difference / 2n; // a & b, since a + b = (a XOR b) + 2(a & b)
  if ((both & N) !== 0n) return 0n; // AND and XOR cannot share set bits.

  if (N === 0n) return both > 0n ? 1n : 0n;

  let setBits = 0;
  for (let bits = N; bits > 0n; bits &= bits - 1n) setBits++;

  let count = 1n << BigInt(setBits); // Assign each XOR bit to either a or b.
  if (both === 0n) count -= 2n; // Exclude (0, N) and (N, 0).
  return count;
}

console.log(String(countPositivePairs(10, 4))); // 2
console.log(String(countPositivePairs(5, 5)));  // 0
  • From a + b = (a XOR b) + 2(a & b), the required AND value is (M - N) / 2. Reject if that is negative, non-integral, or has a bit in common with N.
  • Each set bit of N can be assigned to either operand, giving 2^popcount(N) ordered pairs. Enforce positivity by excluding the two zero-operand cases when a & b = 0; when N = 0, the only possible pair is (both, both).
  • Complexity: O(log N) time and O(1) extra space.
CodingMediumJane StreetSoftware Engineer

16. Given an arithmetic expression in Reverse Polish Notation, write a program to evaluate it.

The full question

Given an arithmetic expression in Reverse Polish Notation, write a program to evaluate it. The expression is given as a list of numbers and operands. For example: [5, 3, '+'] should return 5 + 3 = 8. For example, [15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-'] should return 5, since it is equivalent to ((15 / (7 - (1 + 1))) * 3) - (2 + (1 + 1)) = 5. You can assume the given expression is always valid.

Model answer

function evaluateRPN(tokens) {
  const stack = [];
  const operations = {
    "+": (a, b) => a + b,
    "-": (a, b) => a - b,
    "*": (a, b) => a * b,
    "/": (a, b) => a / b,
  };

  for (const token of tokens) {
    if (typeof token === "number") {
      stack.push(token);
      continue;
    }

    // Pop right operand first: subtraction and division are not commutative.
    const right = stack.pop();
    const left = stack.pop();
    stack.push(operations[token](left, right));
  }

  return stack.pop();
}

console.log(evaluateRPN([5, 3, "+"])); // 8
console.log(evaluateRPN([
  15, 7, 1, 1, "+", "-", "/", 3, "*", 2, 1, 1, "+", "+", "-",
])); // 5
  • Push numbers onto a stack. For each operator, pop the right operand and then the left, apply the operation, and push the result.
  • The expression is valid, so the final stack contains exactly one value.

Complexity: O(n) time and O(n) worst-case space for n tokens.

CodingMediumJane StreetSoftware EngineerPhone interview

17. Given an expensive function f of type int -> int whose output depends only on its input, write a memoized function g of the same type that returns…

The full question

Given an expensive function f of type int -> int whose output depends only on its input, write a memoized function g of the same type that returns the same values as f and computes f only once for each input.

Model answer

// Return a function that caches f's result for each integer input.
function memoize(f) {
  const cache = new Map();

  return function g(x) {
    // Check membership separately so cached values such as 0 are valid.
    if (cache.has(x)) {
      return cache.get(x);
    }

    const result = f(x);
    cache.set(x, result);
    return result;
  };
}
  • The Map uses the input integer as the key; each distinct input is evaluated at most once.
  • This assumes f returns normally. If it throws, the input is not cached and a later call retries it.

Complexity: Expected O(1) cache lookup and insertion per call; O(k) space for k distinct inputs.

Product & growthMediumJane StreetProduct Manager

18. Work through a case study involving order books.

Model answer

Clarify & scope

I’d first clarify what “order books” means in this case: are we building a retail trading interface, tools for professional traders, or the exchange’s matching and market-data infrastructure? I’ll assume we’re improving a retail investor’s view of an exchange order book. The goal is to help users make informed decisions with low latency and clear execution expectations—not to encourage more trading.

User segments & pain points

I’d segment new investors, active self-directed traders, and professional users. I’d initially focus on active self-directed traders: they need to understand available liquidity, spread, and price movement, but may confuse displayed quantity with guaranteed execution. New investors may need a simpler explanation; professionals typically need deeper controls and faster data.

Goals & success metrics

The North Star should be successful, informed use of order-book data, not trading volume. Possible measures include order-book feature adoption, comprehension in usability tests, and the percentage of eligible limit orders placed with a price users intended. Guardrails: order-entry errors, cancellations, complaint rates, latency, stale-data incidents, and outcomes across novice users. I’d avoid interpreting trading frequency or short-term returns as evidence of user benefit.

Solutions

  • A depth view showing bid and ask levels, price, and aggregated quantity, with a visible timestamp and refresh status.
  • A plain-language explanation of spread, depth, and the fact that displayed orders can change before execution.
  • Optional controls for price range and depth, while preserving a clear, accessible default view.

Recommendation: Start with an opt-in, read-only depth view for a limited set of liquid instruments. Pair it with brief contextual explanations and keep order placement separate, so the display does not imply execution certainty.

flowchart LR
  A[Select instrument] --> B[View bids, asks, and spread]
  B --> C[See freshness and explanation]
  C --> D[Decide whether to place a limit order]
  D --> E[Review order details and confirm]
Diagram

Prioritization & trade-offs

I’d rank ideas by user value, confidence, effort, and risk. Read-only depth is a better MVP than advanced order-book analytics: it answers the core question while limiting complexity. Aggregated depth is easier to understand and cheaper to render than every individual order, though it offers less detail. I’d choose freshness and accessibility over visual density.

MVP, measurement & rollout

Prototype with target users and test whether they can correctly interpret spread, quantity, and freshness. Validate data quality and latency before releasing to a small cohort. Compare adoption and comprehension with the existing experience, review guardrails daily during rollout, and expand only if users understand the display and data remains reliable. If the event stream is stale or delayed, show a clear warning or hide depth rather than presenting misleading information.

TechnicalEasyJane StreetSoftware EngineerPhone interview

19. What is memoization?

Model answer

Memoization is a technique for caching the results of a function. When the function is called with an input it has seen before, the memoized version returns the stored result instead of recomputing it.

It is appropriate when the result depends only on the input and the function’s behavior is stable for the lifetime of the cache. The cache key must also represent inputs consistently. Memoization trades memory use and cache-management overhead for potentially less computation; it may need bounds or invalidation if inputs or cached results are numerous or can become stale.

TechnicalMediumJane StreetSoftware EngineerPhone interview

20. What trade-offs does FIFO have compared with other cache eviction schemes?

Model answer

FIFO evicts the entry that has been in the cache longest, regardless of how often or how recently it was used.

  • Advantages: It is simple to implement and has low per-hit overhead because reads do not change eviction order. That can make it attractive when simplicity or inexpensive bookkeeping matters.
  • Compared with LRU: LRU updates recency on access, so it tends to preserve recently reused entries. FIFO can evict a frequently used entry simply because it was inserted early.
  • Compared with LFU: FIFO avoids frequency counters and their aging or tie-breaking policies, but does not protect frequently accessed entries.
  • Workload sensitivity: FIFO can perform poorly when a small set of old entries is repeatedly accessed, and it can be vulnerable to cache pollution from one-time scans. Its behavior is predictable, but not necessarily aligned with reuse.
  • Caveat: For page replacement, FIFO can exhibit Belady’s anomaly: increasing the number of frames can increase page faults. That result does not apply to every cache workload, but illustrates that FIFO is not always stack-like or monotonic.

I would choose FIFO when low overhead and simplicity matter more than adapting eviction to access patterns; otherwise, I would compare it with LRU or a frequency-aware policy using representative traces.

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