Count nonnegative buy/sell sequences
Company: Optiver
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates combinatorial reasoning and algorithmic analysis by asking for the count of constrained buy/sell sequences, testing competence in counting under constraints and reasoning about sequence invariants.
Constraints
- 0 <= n <= 1000
- You must return the exact count, not modulo any value
- The empty sequence for n = 0 counts as one valid sequence
Examples
Input: (0,)
Expected Output: 1
Explanation: With 0 trades, the only valid sequence is the empty sequence.
Input: (1,)
Expected Output: 1
Explanation: The only valid sequence is buy, then sell.
Input: (2,)
Expected Output: 2
Explanation: The valid sequences are buy-buy-sell-sell and buy-sell-buy-sell.
Input: (3,)
Expected Output: 5
Explanation: There are 5 valid sequences, which is the 3rd Catalan number.
Input: (4,)
Expected Output: 14
Explanation: There are 14 valid sequences for 4 buys and 4 sells.
Input: (8,)
Expected Output: 1430
Explanation: This is the 8th Catalan number.
Solution
def solution(n):
if n < 0:
raise ValueError("n must be nonnegative")
catalan = 1
for k in range(n):
catalan = catalan * 2 * (2 * k + 1) // (k + 2)
return catalanTime complexity: O(n). Space complexity: O(1).
Hints
- Try viewing a buy as '(' and a sell as ')'. What well-known counting problem does that become?
- Instead of generating sequences, use the recurrence for Catalan numbers to compute the answer in O(n) time.