Skip to content
Interview prep / Programming/Algorithms

25 quant programming and algorithms interview questions with answers

25 original quant programming interview questions with explained answers on algorithms, Python, data structures, numerical accuracy and reproducibility.

How to approach these questions

A quant implementation needs a clear contract: correct outputs, controlled numerical error and suitable performance on the intended workload. These examples combine algorithmic reasoning with Python behaviour, streaming calculations and numerical methods. State the input and data-structure assumptions whenever you give a complexity bound; expected, amortised and worst-case costs are different claims.

Define correctness first

Clarify duplicate handling, index conventions, empty inputs and required precision. A fast implementation of an ambiguous contract is difficult to evaluate.

Count operations and memory

Explain which elements are visited and what state is retained. Include preprocessing and auxiliary space instead of quoting a complexity label alone.

Treat numerics as part of correctness

Floating-point representation, convergence conditions and random-number generation affect the result. Use stable formulations and record enough context to reproduce a simulation.

Sample questions, answers and explanations

Try each question before reading its answer. These original teaching examples remain free to read on this page.

Search, hashing and sorting

Attach each complexity claim to its access pattern and assumptions.

1. Binary search complexity

A sorted random-access array contains n elements. What is binary search's worst-case comparison complexity?

Answer: O(log n).

Explanation: Each comparison discards about half the remaining interval. The random-access assumption matters when translating the method to another data structure.

2. Unsorted search

Without preprocessing or additional structure, what is the worst-case time to find an item in an unsorted array of n elements?

Answer: O(n).

Explanation: An adversary can place the item last or omit it. Sorting or indexing introduces a different preprocessing and query trade-off.

3. Hash lookup complexity

Is a hash-table lookup guaranteed to take O(1) time?

Answer: No; average performance is often O(1), while worst-case behaviour depends on implementation and collisions.

Explanation: State the hashing and load assumptions. Expected performance is a different claim from a per-operation worst-case guarantee.

4. Comparison sorting lower bound

Why does general comparison sorting require Ω(n log n) comparisons in the worst case?

Answer: A comparison decision tree must distinguish n! input orders.

Explanation: A binary tree with n! leaves needs depth at least log₂(n!). Non-comparison methods rely on extra assumptions about keys.

5. Stable sorting

What does stability mean for a sorting algorithm?

Answer: Records with equal sort keys retain their relative input order.

Explanation: Stability matters when prior ordering carries information or when performing several sorting passes. It is separate from speed and memory use.

Data structures for common tasks

Choose state that avoids repeated work while preserving the required output order.

6. Two-sum in one pass

How can you find two values summing to a target in an unsorted array using expected linear time?

Answer: Scan while storing previously seen values in a hash set; check the complement before inserting.

Explanation: Checking first prevents using the same position twice. Expected O(n) time costs O(n) auxiliary space under ordinary hashing assumptions.

7. Deduplicate records

How can you remove duplicate identifiers while preserving their first occurrence?

Answer: Scan in order, keep a set of seen identifiers and emit only the first unseen record.

Explanation: A set alone may lose required ordering across languages or implementations. Make the output-order contract explicit.

8. Merge two sorted lists

Two sorted arrays have lengths m and n. Give the time complexity of merging them into a sorted output.

Answer: O(m + n).

Explanation: Compare the current heads and advance one pointer. Each element is read and emitted at most once.

9. Keep the largest k values

For a stream of n values with k much smaller than n, how can you retain the largest k?

Answer: Maintain a min-heap of size at most k.

Explanation: Replace the heap minimum when a larger value arrives. Processing takes O(n log k) time and O(k) space.

10. Validate brackets

Which data structure validates balanced parentheses in a single pass?

Answer: A stack, or a depth counter for one bracket type.

Explanation: Opening brackets push and closing brackets must match the top. Reject premature closings and require an empty stack at the end.

Dynamic programming and streaming

A recurrence or rolling summary can replace repeated computation and reduce memory.

11. A simple dynamic programme

A staircase can be climbed in steps of size 1 or 2. If f(0) = f(1) = 1, give the recurrence for f(n).

Answer: f(n) = f(n − 1) + f(n − 2) for n ≥ 2.

Explanation: Classify paths by their final step. Retaining just the previous two counts gives O(n) time and O(1) auxiliary space.

12. Range sums

How can many static inclusive array range-sum queries be answered in O(1) time after preprocessing?

Answer: Build prefix sums P with P[0] = 0; return P[r + 1] − P[l].

Explanation: O(n) preprocessing avoids rescanning each interval. The extra leading zero makes index boundaries explicit.

13. Fixed-width moving mean

How can you update a moving mean of the last k values in O(1) time per observation?

Answer: Maintain the window sum, add the new value and subtract the outgoing value.

Explanation: A queue or ring buffer stores outgoing values. Handle the initial partial window separately and consider floating-point drift.

14. Python list aliasing

In Python, why can rows = [[0] * 3] * 2 be dangerous to mutate?

Answer: Both row entries refer to the same inner list.

Explanation: Changing one row changes the shared object visible through the other. A comprehension creates separate row lists.

15. Stream large data

Why use a Python generator when processing a very large file once?

Answer: It yields items lazily and can avoid storing the entire dataset.

Explanation: Memory savings depend on downstream consumers also streaming. Converting the generator immediately to a list removes that advantage.

Python behaviour and numerical stability

Reason about object identity, iteration contracts and approximation errors separately.

16. Dictionary mutation during iteration

Why is adding keys to a Python dictionary while iterating over it problematic?

Answer: Changing its size can raise a runtime error and invalidates the iteration contract.

Explanation: Iterate over a snapshot or collect updates for a later pass. Distinguish changing values from changing the set of keys.

17. Bisection iterations

A continuous function changes sign on an interval of width 1. How many bisection steps make the bracket width at most 1/1024?

Answer: 10.

Explanation: Each step halves the bracket, so its width becomes 2^(−k). Continuity and a sign change ensure a root remains bracketed.

18. Newton's method

State Newton's update for solving f(x) = 0.

Answer: x_next = x − f(x)/f′(x), when the derivative is nonzero.

Explanation: It follows the tangent line to its root. Convergence is local under suitable conditions; a small derivative can make the step unstable.

19. Floating-point cancellation

Why can subtracting nearly equal floating-point numbers lose relative accuracy?

Answer: Leading significant digits cancel, exposing rounding error in the small difference.

Explanation: Look for an algebraically equivalent stable form. More decimal output does not restore lost information.

20. Summing small terms

Why can adding many tiny values to a large floating-point accumulator lose contributions?

Answer: Some increments are below the accumulator's representable spacing.

Explanation: Pairwise or compensated summation can reduce error. The issue is arithmetic precision, not the mathematical commutativity of addition.

Testing and operational correctness

Use workload measurements, explicit edge cases and reproducibility to connect an algorithm to a dependable implementation.

21. Runtime versus asymptotics

Why might an O(n²) algorithm beat an O(n log n) algorithm on a very small input?

Answer: Constant factors, setup cost and memory access can dominate at small n.

Explanation: Asymptotic notation describes growth, not a stopwatch result for every input. Benchmark the realistic workload after checking correctness.

22. Test a binary search

What edge cases deserve attention in a binary-search implementation?

Answer: Empty and one-element arrays, absent targets, endpoints, duplicates and the chosen return contract.

Explanation: These expose interval and off-by-one mistakes. Define whether duplicates return any, first or last matching position.

23. Reproducible simulation

What should you record to reproduce a stochastic computation?

Answer: The seed, generator and version, inputs, algorithm and relevant environment.

Explanation: A seed alone does not fix changing code, data or generator behaviour. Parallel execution can also alter draw order.

24. Shared-state race

Two workers read a counter, increment locally and write it back. What can go wrong?

Answer: An update can be lost because both workers read the same old value.

Explanation: The read-modify-write sequence needs synchronisation or an atomic operation. Independent-looking instructions do not make the sequence atomic.

25. Define an implementation contract

Before optimising a pricing routine, what should you clarify?

Answer: Required accuracy, valid inputs, error behaviour, workload and latency or throughput objective.

Explanation: Optimisation needs a measurable target and correctness boundary. A faster routine with uncontrolled numerical error does not satisfy a pricing contract.

67 programming/algorithms questions from the bank

Each question has its own page with a short answer and a credit to its source. Hints and full worked solutions are in the question bank with a free account.

  1. Best single buy-then-sell profit from a price listEasy
  2. Tracker for top tickers by cumulative volumeEasy
  3. Coding and speeding up a numerical integratorEasy
  4. Mapping a uniform draw to a discrete lawEasy
  5. Efficient program for Fibonacci numbersEasy
  6. Adding a number of days to a calendar dateEasy
  7. Raising a matrix to a high power quicklyEasy
  8. Building a histogram from raw dataEasy
  9. Numerically stable sinc functionEasy
  10. Why comparison sorts need n log n timeMedium
  11. Robust function for n factorialEasy
  12. Spotting a repeat among values 0 to N-1Medium
  13. Routine for linear interpolation on a gridEasy
  14. Adding up all node values in a binary treeEasy
  15. Simulating random points to approximate piEasy
  16. Talking about the compilers you have usedEasy
  17. Discussing design patterns from your C++ workEasy
  18. Inline functions versus preprocessor macrosEasy
  19. Signalling failure by throwing in a constructorMedium
  20. Why destructors should not throwMedium
  21. Cloning an object through a base pointerMedium
  22. Does a subclass need its own operator=Medium
  23. Declaring a pointer to a function in C++Easy
  24. Role of C++ in quantitative financeEasy
  25. Meaning of a virtual member functionEasy
  26. Hand-rolling a C string comparisonEasy
  27. When a destructor must be virtualEasy
  28. Order of construction with a base and a memberEasy
  29. Member functions the compiler writes for youEasy
  30. Two routes for implicit type conversionEasy
  31. Deep copies for classes owning heap memoryEasy
  32. Implementing and improving a sorting routineEasy
  33. Counting up forever in int and floatMedium
  34. Memory location of static variablesEasy
  35. Mechanics of virtual dispatch with vtablesMedium
  36. Why virtual calls are harder to optimiseMedium
  37. Mixing up delete and delete[]Easy
  38. Replacing the conditional operator by a functionMedium
  39. Uniforms consumed by the polar Gaussian methodMedium
  40. Reversing a string by copy and in placeEasy
  41. Passing arguments by value, reference or pointerEasy
  42. Square root by Newton's method as a CLI toolEasy
  43. Integer binary tree with depth and maxMedium
  44. The many jobs of const in C++Easy
  45. Every context where static appearsEasy
  46. Polymorphism, abstract classes, pointers, referencesEasy
  47. Catching any exception from a code blockEasy
  48. Declaring a function with C linkageEasy
  49. Finding two absent numbers between 1 and 100Easy
  50. Algorithms for solving f(x) = 0Easy

What our question-bank data shows

Our bank summary dated contains 69 Programming/Algorithms entries in the bank. Counts describe entries in our curated practice bank, including its source and classification choices. They do not measure employer interview frequency, candidate success rates or how often any one question is asked.

  • C++: 31 entries, or 44.9% of this topic's bank. Use this coverage to identify areas for practice alongside the technique-based examples above.
  • Algorithms: 18 entries, or 26.1% of this topic's bank. Use this coverage to identify areas for practice alongside the technique-based examples above.
  • Numerical Methods: 11 entries, or 15.9% of this topic's bank. Use this coverage to identify areas for practice alongside the technique-based examples above.

The public examples above were written for these guides. They illustrate the techniques and are not a reproduction or ranking of the bank's sourced questions. The dashboard's broader bank combines sourced questions, worked answers where available and references for book entries without a reproduced solution.

Subtopic coverage in the bank

SubtopicBank entries
C++31
Algorithms18
Numerical Methods11
Sorting & Searching6
Data Structures2
Dynamic Programming1

Bank difficulty labels: 49 easy · 20 medium.

Lessons behind the techniques

Use these lesson previews to find the definitions and derivations behind the worked examples.

Continue with 69 programming/algorithms questions in the practice bank.

Open the programming/algorithms bank

Other interview topic guides