Katkat

Implement Factorial and Squares

Morgan StanleyData Scientist · HR Screen

Last updated

A Morgan Stanley data scientist HR-screen live-coding warm-up: implement Python `factorial(n)` (iteratively, then explain the recursive version) and `squares(n)` returning the squares of the first n integers. Evaluates clean Python, the iteration-vs-recursion trade-off, time and space complexity analysis, input validation, and edge cases like n = 0 and negative input.

Question

In a live coding interview, write two Python functions and be ready to discuss their behavior.

  1. factorial(n): Given a non-negative integer n, return n!. Implement it iteratively, and be prepared to explain how a recursive version would differ. State the time and space complexity of each approach.
  2. squares(n): Given a non-negative integer n, return a list containing the squares of the first n integers, in order. Clearly state your convention—either [0^2, 1^2, ..., (n-1)^2] or [1^2, 2^2, ..., n^2]. For example, with the 0-based convention, n = 5 should return [0, 1, 4, 9, 16].

For both functions, discuss input validation and edge cases such as n = 0 and invalid negative input.