Two Sigma logo

Two Sigma Software Engineer Interview Questions

13 practice questions for Two Sigma Software Engineer interviews

Two Sigma software engineer interviews cover algorithms, data structures, system design, and coding problems drawn from real interview rounds.

Software Engineer Backend Engineer Frontend Engineer Full Stack Engineer Mobile Engineer Data Engineer Data Scientist ML Engineer DevOps Engineer DevOps Engineer Product Manager SRE Security Engineer Engineering Manager Data Analyst UX/UI Designer QA Engineer
coding Medium Verified Question #1

1. Binary Step Reduction


Category: Algorithm coding problem
You are given a positive integer n. Your goal is to reduce it to zero using the fewest operations possible. In a single operation, you may add or...
Input: Integer(s)
Output: Integer
Want to practise this one?
Create a free account to open the full question and practise Two Sigma questions with AI.
Sign up free
coding Hard Verified Question #2

2. Concert Ticket Auction


Category: Algorithm coding problem

Question A venue is holding an auction to allocate a limited number of concert tickets to fans. Before the sale closes, fans can submit bids. Each...

Input: List
Output: Computed result
coding Hard Verified Question #3

3. Pipeline Throughput Optimizer


Category: Array coding problem

Question A message-processing pipeline consists of n services that must all be traversed in sequence. The pipeline's effective throughput is...

Input: Array
Output: Integer
coding Hard Verified Question #4

4. Non-Adjacent Team Selection


Category: Tree coding problem

Question You are given n people labeled from 0 to n - 1. Some pairs of people know each other directly. These relationships are given as a...

Input: List
Output: Computed result
coding Medium Verified Question #5

5. Pythagorean Node Finder


Category: Tree coding problem

Question You are given an undirected tree with n nodes labeled from 0 to n - 1. The tree is described by two integer arrays treeFrom and...

Input: Array
Output: Computed result
coding Medium Verified Question #6

6. Balanced Drainage Split


Category: Tree coding problem

Question You are given a water drainage network shaped as a rooted tree with n nodes labeled from 0 to n - 1. Water flows from each node...

Input: Array
Output: Integer
coding Hard tree #1

1. [AI Enabled Coding] Research Trade Database with Atomic Risk Checks


Scenario
Two Sigma researchers rely on reproducible, data-driven investment simulations; late trade corrections must not silently corrupt a simulation's exposure calculations. In this exercise, build a mock in-memory database for simulated trades that accepts corrections atomically and enforces configurable exposure rules. This is an adaptation of a reported mock-database interview question, not a description of Two Sigma's production systems; you may use an AI assistant while implementing and testing it.
Part 1 — Atomic updates and symbol exposure
  • Process records in input order. Each record is a map with string keys and string values. UPSERT records contain op, id, symbol, desk, time, and amount; DELETE records contain only op and id.

  • amount is a positive USD notional with exactly two decimal places. Use exact integer cents internally. time is a nonnegative integer event timestamp in seconds, represented as a string.

  • An UPSERT inserts a new ID or replaces every field of an existing ID. Evaluate rules against the tentative state after removing the old version and adding the new version. If any rule fails, reject the entire update and preserve the previous state.

  • TRADE_CAP: the proposed trade's amount must be at most 100.00.

  • SYMBOL_CAP: the total amount of all active trades with the proposed trade's symbol, across all desks and timestamps, must be at most 250.00.

  • Report every failing rule, in the order TRADE_CAP, then SYMBOL_CAP. Equality with a cap is allowed.

  • DELETE removes an active ID and returns ACCEPTED; deleting an absent ID returns NOOP. Neither case has violations.

  • Use a rule registry or similarly extensible design. The return type is up to you; the examples show a canonical JSON representation, and an equivalent typed representation is acceptable.


Function signature: process_trades(records: list[dict[str, str]], enable_desk_windows: bool = False) — return type chosen by the candidate.
Example 1:
Input:
{
  "enable_desk_windows": false,
  "records": [
    {"op":"UPSERT","id":"a","symbol":"X","desk":"alpha","time":"0","amount":"80.00"},
    {"op":"UPSERT","id":"b","symbol":"X","desk":"alpha","time":"10","amount":"90.00"},
    {"op":"UPSERT","id":"c","symbol":"Y","desk":"beta","time":"20","amount":"120.00"},
    {"op":"UPSERT","id":"d","symbol":"X","desk":"alpha","time":"30","amount":"90.00"},
    {"op":"DELETE","id":"a"}
  ]
}

Output:
[
  {"id":"a","status":"ACCEPTED","violations":[]},
  {"id":"b","status":"ACCEPTED","violations":[]},
  {"id":"c","status":"REJECTED","violations":["TRADE_CAP"]},
  {"id":"d","status":"REJECTED","violations":["SYMBOL_CAP"]},
  {"id":"a","status":"ACCEPTED","violations":[]}
]

Explanation: The first two trades create symbol-X exposure of 80.00 + 90.00 = 170.00. Trade c exceeds the individual cap. Trade d would create 260.00 of symbol-X exposure and is rejected. Deleting a leaves only b active.
Part 2 — Out-of-order event-time exposure rules
Add the following requirement when enable_desk_windows is true, without replacing Part 1:
  • DESK_WINDOW_CAP: for each desk and every integer endpoint r, the total amount of active trades whose timestamps satisfy r - 59 <= time <= r must be at most 180.00. Thus timestamps 0 and 59 can share a window, but timestamps 0 and 60 cannot.

  • Timestamps can arrive out of order, and a correction can change its timestamp, desk, symbol, and amount. A correction must preserve all existing caps and the new cap atomically. Evaluate the resulting active database, not merely the trades most recently received.

  • Report all failures in the order TRADE_CAP, SYMBOL_CAP, DESK_WINDOW_CAP. Each failure now includes rule, scope, observed, and limit. Scope is the proposed trade ID, symbol, or desk, respectively. For the desk rule, observed is that desk's maximum window total in the tentative state. Format monetary diagnostics with exactly two decimal places.

  • Also return the final active records, excluding op, sorted lexicographically by ID. The canonical representation is an object containing results and active_records.

  • Discuss how the return type changes before implementing this extension. The approach must support future additions of the same kind, such as another aggregate rule with its own scope, window length, and cap. Avoid rescanning all active trades for every operation; target O(n log n) total time for the fixed rules in this prompt. You may preprocess the complete input to build indexes, but must still decide operations in input order.


Example 2:
Input:
{
  "enable_desk_windows": true,
  "records": [
    {"op":"UPSERT","id":"a","symbol":"X","desk":"alpha","time":"0","amount":"90.00"},
    {"op":"UPSERT","id":"b","symbol":"Y","desk":"alpha","time":"30","amount":"80.00"},
    {"op":"UPSERT","id":"c","symbol":"Z","desk":"alpha","time":"59","amount":"20.00"},
    {"op":"UPSERT","id":"d","symbol":"Z","desk":"alpha","time":"60","amount":"20.00"},
    {"op":"UPSERT","id":"b","symbol":"Y","desk":"alpha","time":"30","amount":"60.00"}
  ]
}

Output:
{
  "results": [
    {"id":"a","status":"ACCEPTED","violations":[]},
    {"id":"b","status":"ACCEPTED","violations":[]},
    {"id":"c","status":"REJECTED","violations":[{"rule":"DESK_WINDOW_CAP","scope":"alpha","observed":"190.00","limit":"180.00"}]},
    {"id":"d","status":"ACCEPTED","violations":[]},
    {"id":"b","status":"ACCEPTED","violations":[]}
  ],
  "active_records": [
    {"id":"a","symbol":"X","desk":"alpha","time":"0","amount":"90.00"},
    {"id":"b","symbol":"Y","desk":"alpha","time":"30","amount":"60.00"},
    {"id":"d","symbol":"Z","desk":"alpha","time":"60","amount":"20.00"}
  ]
}

Explanation: Before c, alpha's peak is 90.00 + 80.00 = 170.00. At endpoint 59, c would raise it to 190.00, so c is rejected. Trade d is accepted: at endpoint 60, the window excludes a and contains 80.00 + 20.00 = 100.00; the earlier peak remains 170.00. Replacing b with 60.00 reduces the peak to 90.00 + 60.00 = 150.00. No individual or symbol cap fails.
Example 3:
Input:
{
  "enable_desk_windows": true,
  "records": [
    {"op":"UPSERT","id":"a","symbol":"X","desk":"alpha","time":"0","amount":"100.00"},
    {"op":"UPSERT","id":"b","symbol":"X","desk":"beta","time":"0","amount":"100.00"},
    {"op":"UPSERT","id":"c","symbol":"Y","desk":"alpha","time":"10","amount":"80.00"},
    {"op":"UPSERT","id":"b","symbol":"X","desk":"alpha","time":"20","amount":"160.00"},
    {"op":"DELETE","id":"c"}
  ]
}

Output:
{
  "results": [
    {"id":"a","status":"ACCEPTED","violations":[]},
    {"id":"b","status":"ACCEPTED","violations":[]},
    {"id":"c","status":"ACCEPTED","violations":[]},
    {"id":"b","status":"REJECTED","violations":[
      {"rule":"TRADE_CAP","scope":"b","observed":"160.00","limit":"100.00"},
      {"rule":"SYMBOL_CAP","scope":"X","observed":"260.00","limit":"250.00"},
      {"rule":"DESK_WINDOW_CAP","scope":"alpha","observed":"340.00","limit":"180.00"}
    ]},
    {"id":"c","status":"ACCEPTED","violations":[]}
  ],
  "active_records": [
    {"id":"a","symbol":"X","desk":"alpha","time":"0","amount":"100.00"},
    {"id":"b","symbol":"X","desk":"beta","time":"0","amount":"100.00"}
  ]
}

Explanation: Initially X totals 200.00, and alpha reaches exactly 100.00 + 80.00 = 180.00, which is allowed. The proposed replacement of b has amount 160.00, makes X total 100.00 + 160.00 = 260.00, and makes alpha's window total 100.00 + 80.00 + 160.00 = 340.00. All three rules fail. The old b remains on beta with amount 100.00; deleting c then leaves two unchanged trades.
Notes:
  • There are at most 200,000 operations; timestamps are canonical integer strings in [0, 10^9], and amounts are between 0.01 and 1000000.00. IDs, symbols, and desks are nonempty, case-sensitive strings of at most 40 characters.

  • Inputs are well formed. The database starts empty, execution is single-threaded, and positive notionals represent gross simulated exposure rather than signed positions.

  • Explain why your window index remains correct after rejected updates, timestamp corrections, and deletions, and write tests for these cases.
Want to practise this one?
Create a free account to open the full question and practise Two Sigma questions with AI.
Sign up free
coding Hard graph #2

2. [Graph] — Find shortest path in a weighted graph


Background: Two Sigma often deals with large datasets and requires efficient algorithms for data processing and analytics. Finding optimal paths in graphs can significantly enhance data-related tasks, such as trading algorithms and routing.
Problem statement: Given a weighted directed graph represented as an adjacency list, write a function shortest_path that finds the shortest path from a starting node to a destination node using Dijkstra's algorithm. You should return the path as a list of node identifiers and the total weight of that path.
Function/class signature:
  • def shortest_path(graph: Dict[int, List[Tuple[int, int]]], start: int, end: int) -> Tuple[List[int], int]:


Example 1:
  • Input: graph = {0: [(1, 4), (2, 1)], 1: [(3, 1)], 2: [(1, 2), (3, 5)], 3: []}, start = 0, end = 3

  • Output: ([0, 2, 1, 3], 5)

  • Explanation: The path 0 -> 2 -> 1 -> 3 has a total weight of 5.


Example 2:
  • Input: graph = {0: [(1, 10), (2, 5)], 1: [(3, 2)], 2: [(1, 3), (3, 1)], 3: []}, start = 0, end = 3

  • Output: ([0, 2, 3], 6)

  • Explanation: The path 0 -> 2 -> 3 has a total weight of 6.


Constraints:
  • The number of nodes in the graph will not exceed 10^5.

  • The edges' weights are positive integers.

  • You can assume the graph is connected and directed.


coding Medium hash map #3

3. Hash_map — Design a key-value store with efficient retrieval

Background: Two Sigma requires an fast and scalable storage solution for data used in its trading algorithms. This key-value store can be utilized to cache data points that need to be fetched quickly during computation processes.
Problem statement: Implement a class KeyValueStore that allows for storing, retrieving, and deleting key-value pairs. The operations should have O(1) time complexity. The class should also provide a method to check if a key exists in the store.
Function/class signature:
  • def set_key(key: str, value: Any) -> None: # Adds or updates a key-value pair

  • def get_value(key: str) -> Optional[Any]: # Returns the value associated with the key, or None if it doesn't exist

  • def delete_key(key: str) -> None: # Removes the key from the store

  • def key_exists(key: str) -> bool: # Returns True if the key exists, else False

Example 1: Input: set_key('alpha', 100), get_value('alpha') → Output: 100. Explanation: 'alpha' is set to 100, therefore retrieving it returns 100.
Example 2: Input: set_key('beta', 200), delete_key('beta'), get_value('beta') → Output: None. Explanation: 'beta' is deleted, so retrieving it returns None.
Constraints:
  • Total number of keys (1 ≤ key length ≤ 100)

  • Store can handle up to 10^6 entries

  • The value can be any data type

  • Operations should complete in O(1) time complexity.

coding Medium caching #4

4. LRU Cache Implementation — managing memory with a Least Recently Used cache

1. Background: In performance-critical applications like the ones Two Sigma develops, efficient memory management is essential to store and retrieve frequently accessed data without excessive latency. An efficient LRU (Least Recently Used) cache helps in keeping the most relevant data in memory for quick access.
2. Problem statement: Design and implement a LRUCache class that supports the following operations: get(key) and put(key, value). The get method should return the value of the key if it exists in the cache, otherwise return -1. The put method should insert or update the value of the key. If the number of keys exceeds the capacity, the least recently used key should be removed.
3. Function/class signature:
- class LRUCache:
- def __init__(self, capacity: int): # initializes the LRU cache with a positive capacity.
- def get(self, key: int) -> int: # returns the value of the key if it exists.
- def put(self, key: int, value: int) -> None: # updates or adds the key-value pair.
4. Example 1: Input: put(1, 1); put(2, 2); get(1) → Output: 1 Explanation: Key 1 is found, returning 1.
5. Example 2: Input: put(3, 3); get(2) → Output: -1 Explanation: Key 2 was evicted when putting key 3 since the capacity is 2.
6. Constraints:
- Capacity (1 <= capacity <= 3000)
- Each key and value (0 <= key, value <= 10^4)
- All operations are guaranteed to be called with valid keys.
coding Medium graph #5

5. Breadth-First Search (BFS) — Shortest Path in a Grid with Obstacles

Background: Two Sigma often deals with complex algorithms for optimizing quantitative analysis. Efficient pathfinding is crucial in scenarios such as navigating through large datasets represented as grids.
Problem statement: Given a grid represented by a 2D list of integers, where 0 represents an open cell and 1 represents an obstacle, write a function that returns the length of the shortest path from the top-left corner (0,0) to the bottom-right corner (n-1,m-1). You can only move right, left, up, or down. If there is no such path, return -1.
Function/class signature:
  • def shortest_path(grid: List[List[int]]) -> int:

Example 1:
Input: [[0,0,0],[0,1,0],[0,0,0]]
Output: 4
Explanation: The path is down -> down -> right -> right.
Example 2:
Input: [[0,1],[0,0]]
Output: 3
Explanation: The path is down -> right -> right.
Constraints:
  • 1 <= n, m <= 100

  • The grid will contain only 0s and 1s.

  • The starting and ending cells will always be 0.
coding Medium graph #6

6. Graph — Shortest Path in a Grid with Obstacles

Background: Two Sigma requires efficient pathfinding algorithms to navigate and analyze potential trading routes, using grid-like representations of financial landscapes. This problem models a grid system, where certain cells are obstructed, complicating the route selection.
Problem statement: Given an m x n grid represented by a 2D array, where each cell is either 0 (open space) or # (obstacle), determine the shortest path from the starting point (0, 0) to a destination point (x, y). You may move up, down, left, or right but may not traverse the cells containing obstacles (#). Return the length of the shortest path if it exists, otherwise return -1.
Function/class signature:
  • def shortest_path(grid: List[List[str]], destination: Tuple[int, int]) -> int:

Example 1:
  • Input: grid = [['0', '0', '#'], ['0', '0', '0'], ['#', '0', '0']], destination = (2, 2)

  • Output: 4

  • Explanation: The path is [(0,0), (0,1), (1,1), (2,1), (2,2)], which has 4 steps.

Example 2:
  • Input: grid = [['0', '#', '0'], ['0', '0', '0'], ['#', '#', '0']], destination = (2, 2)

  • Output: 5

  • Explanation: The path is [(0,0), (1,0), (1,1), (1,2), (2,2)], which has 5 steps.

Constraints:
  • 1 ≤ m, n ≤ 100

  • grid[i][j] is either '0' or '#'.

  • destination must be within the grid bounds.
coding Medium caching #7

7. [Caching] — Implement a thread-safe Least Recently Used (LRU) cache


Background: In a trading environment, Two Sigma needs to manage data efficiently to provide real-time insights and analytics. A Least Recently Used (LRU) cache is essential to store frequently accessed items, thus improving the speed and efficiency of data retrieval.
Problem statement: Implement a thread-safe LRUCache class that supports the following operations: get and put. The get(key) method retrieves the value if the key exists, otherwise returns -1. The put(key, value) method updates the value if the key is present, or inserts a new key-value pair. If the cache reaches its limit, it should remove the least recently used item before inserting a new item.
Function/class signature:
  • def __init__(self, capacity: int):

  • def get(self, key: int) -> int:

  • def put(self, key: int, value: int) -> None:


Example 1:
  • Input: cache = LRUCache(2); cache.put(1, 1); cache.put(2, 2); cache.get(1)

  • Output: 1

  • Explanation: The cache is {1=1, 2=2}. The value for key 1 is returned, and key 2 becomes the least recently used.


Example 2:
  • Input: cache.put(3, 3); cache.get(2)

  • Output: -1

  • Explanation: The cache reaches capacity and removes key 2; hence, trying to access it returns -1.


Constraints:
  • 1 <= capacity <= 3000

  • 0 <= key, value <= 100000

  • get and put operations are called at most 10^4 times.

Related Two Sigma Software Engineer interview prep

Start practicing Two Sigma questions

Sign up for free to access walkthroughs, AI-generated questions, and more.

Get Started Free