Implement Factorial and Squares
Morgan StanleyData Scientist · HR ScreenLast 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.
factorial(n): Given a non-negative integern, returnn!. Implement it iteratively, and be prepared to explain how a recursive version would differ. State the time and space complexity of each approach.squares(n): Given a non-negative integern, return a list containing the squares of the firstnintegers, 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 = 5should return[0, 1, 4, 9, 16].
For both functions, discuss input validation and edge cases such as n = 0 and invalid negative input.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.