Implement Iterative and Recursive Factorial with Integer Squares
Math & Bit ManipulationModel answerLast 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.
-
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.
-
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 example,
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.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Implementation
def validate_non_negative_int(n: int, arg_name: str = "n") -> None:
"""Validate that input is a non-boolean integer and non-negative."""
# bool is a subclass of int in Python; check for it explicitly
if isinstance(n, bool) or not isinstance(n, int):
raise TypeError(f"Argument '{arg_name}' must be an int, got {type(n).__name__}")
if n < 0:
raise ValueError(f"Argument '{arg_name}' must be non-negative, got {n}")
def factorial_iterative(n: int) -> int:
"""Computes n! iteratively."""
validate_non_negative_int(n)
result = 1
for i in range(2, n + 1):
result *= i
return result
def factorial_recursive(n: int) -> int:
"""Computes n! recursively."""
validate_non_negative_int(n)
if n <= 1:
return 1
return n * factorial_recursive(n - 1)
def squares(n: int) -> list[int]:
"""Returns a list of squares for the first n non-negative integers."""
validate_non_negative_int(n)
return [i * i for i in range(n)]
Complexity Analysis
| Function | Unit-Cost Time | Bit-Operation Time | Auxiliary Space |
|---|---|---|---|
factorial_iterative(n) | $\mathcal{O}(n)$ | $\mathcal{O}(n^2 \log n)$ | $\mathcal{O}(1)$ |
factorial_recursive(n) | $\mathcal{O}(n)$ | $\mathcal{O}(n^2 \log n)$ | $\mathcal{O}(n)$ (Call stack) |
squares(n) | $\mathcal{O}(n)$ | $\mathcal{O}(n)$ | $\mathcal{O}(n)$ (Output array) |
Arithmetic vs. Bit-Operation Time Complexity
Under standard uniform cost criteria (treating basic operations as $\mathcal{O}(1)$), both factorial approaches execute $n$ multiplication steps, giving $\mathcal{O}(n)$ time.
However, in Python, integers have arbitrary precision. The exact bit-length of $n!$ is $\Theta(n \log n)$ by Stirling's approximation. Multiplying a multi-precision integer of size $\mathcal{O}(k \log k)$ by a smaller scalar requires work proportional to the bit-length. Summing this over $k = 1 \dots n$ yields a tighter bit-complexity bound of $\mathcal{O}(n^2 \log n)$.
Key Discussion Points & Trade-offs
1. Iteration vs. Recursion
- Memory Usage: The iterative function uses $\mathcal{O}(1)$ auxiliary space beyond storing the final result. The recursive variant allocates a new call stack frame for each call level, consuming $\mathcal{O}(n)$ stack memory.
- Recursion Limits: Standard Python interpreters enforce a default maximum recursion ceiling (typically $1000$). Executing
factorial_recursive(1500)triggers aRecursionError. Whilesys.setrecursionlimit()can raise this bound, doing so risks stack overflow crashes at the OS level. - Tail Call Optimization (TCO): Python does not implement Tail Call Optimization. Even if written in tail-recursive style (e.g., passing an accumulator
acc), stack frames are retained. - Production Recommendation: In standard library code,
math.factorialshould be preferred. It is implemented natively in C using a divide-and-conquer prime factorization scheme that runs significantly faster than simple sequential loops.
2. Input Validation & Edge Cases
- Zero Input ($n = 0$):
factorial(0)returns1by definition of the empty product.squares(0)returns[]because zero terms were requested.
- Negative Numbers ($n < 0$): Factorials of negative integers are mathematically undefined in this context, and requesting a negative count of square numbers is invalid. Explicitly raising a
ValueErrorprevents unintended behavior (such asrange(-5)producing an empty loop silently). - Type Safety & Python Peculiarities:
- Floating point inputs (e.g.,
factorial(4.0)) are rejected viaTypeErrorto enforce strict integer domain contracts. - Because
issubclass(bool, int)evaluates toTruein Python (isinstance(True, int) == True), booleans must be checked explicitly to avoid silently treatingfactorial(True)asfactorial(1).
- Floating point inputs (e.g.,
3. Large Datasets ($n \to \infty$)
If $n$ is very large (e.g., $n = 10^7$), constructing the entire list in squares(n) will exhaust system RAM. Presenting a memory-efficient generator expression alternative—squares_gen = (i * i for i in range(n))—enables lazy evaluation in $\mathcal{O}(1)$ auxiliary memory.