The Decomposer
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
- Asked in
- Citadel
Problem
Given an integer n > 1, return its prime factorization as a list of primes in ascending order. Repeated factors are included (for example, 12 -> [2, 2, 3]).
Every composite thing can be broken down to its simplest parts.
Example 1
Input:
n = 12
Output:
[2,2,3]
Example 2
Input:
n = 28
Output:
[2,2,7]
Worked solution and explanation
Why this problem exists in real interviews
This tests prime factorization via trial division, a fundamental number theory algorithm. It probes loop construction, modular arithmetic, and understanding of the optimization to only check up to the square root.
Break down the requirements
Step 1: Start dividing by 2
Extract all factors of 2 first, since it is the only even prime.
Step 2: Try odd divisors from 3 up to the square root
After removing all 2s, only odd factors remain. Check each odd number and extract all instances.
Step 3: Handle the remaining factor
If the number is still greater than 1 after the loop, it is itself a prime factor.
The solution
def prime_factors(n: int) -> list:
factors = []
d = 2
while d * d <= n:
while n % d == 0:
factors.append(d)
n = n // d
d += 1
if n > 1:
factors.append(n)
return factorsCommon follow-up questions
- How would you check if a number is prime? (Tests reusing the trial division pattern but returning a boolean.)
- What is the time complexity for very large numbers? (Tests awareness that trial division is not practical for cryptographic-size primes.)
- How would you find the prime factorization of many numbers efficiently? (Tests the Sieve of Eratosthenes for precomputing smallest prime factors.)