KatInterview

Implement Iterative and Recursive Factorial with Integer Squares

Math & Bit ManipulationModel answer
EasyModel answerMath & Bit Manipulationmathrecursioniteration

Last updated

Write iterative and recursive factorial functions alongside a sequence of integer squares, focusing on input validation, edge cases, and stack vs. loop complexity.

In a live technical screening, you are asked to implement two basic mathematical utility functions in Python and discuss their computational behavior and edge-case handling.

  1. factorial(n): Given an integer $n \ge 0$, compute its factorial $n!$.

    • Implement the primary version iteratively.
    • Provide a secondary recursive implementation for comparison.
    • Explain the trade-offs between the two approaches, including time complexity, auxiliary space usage, and language-specific limitations.
  2. squares(n): Given an integer $n \ge 0$, generate a list containing the squares of the first $n$ non-negative integers starting from $0$: $[0^2, 1^2, 2^2, \dots, (n-1)^2]$.

    • For example, squares(5) should yield [0, 1, 4, 9, 16].
    • Explain how your design handles $n = 0$ and $n = 1$.

For both utilities, incorporate robust input validation that properly handles negative integers and non-integer types (such as floats, strings, or booleans).

Hints

Hint 1

Recall that mathematically, 0! is defined as 1 (the empty product), and 0 elements of a square sequence should yield an empty list.

Hint 2

In Python, bool is a subclass of int (isinstance(True, int) evaluated to True), so explicit type checking must account for booleans.

Hint 3

Consider stack frame allocation and Python's recursion depth ceiling when comparing iterative vs. recursive execution.