Factor Combinations — LeetCode 254 Python Solution

MediumLeetCode PremiumBacktracking
Problem
#254
Reading time
3 min

The problem

Numbers can be regarded as the product of their factors. For example, 8 = 2 x 2 x 2 = 2 x 4.

Example

Input
n = 1
Output
[]

Python solution

Python
class Solution:
    def getFactors(self, n: int) -> List[List[int]]:
        def dfs(n, i):
            if t:
                ans.append(t + [n])
            j = i
            while j * j <= n:
                if n % j == 0:
                    t.append(j)
                    dfs(n // j, j)
                    t.pop()
                j += 1

        t = []
        ans = []
        dfs(n, 2)
        return ans

Complexity

MeasureComplexity
TimeExponential (worst case)
SpaceO(depth) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 254. Factor Combinations is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 254. Factor Combinations?
LeetCode 254. Factor Combinations is rated Medium on LeetCode.
What topics does LeetCode 254. Factor Combinations cover?
LeetCode 254. Factor Combinations is tagged Backtracking on LeetCode.
Is LeetCode 254. Factor Combinations a premium problem?
Yes. LeetCode 254. Factor Combinations is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview