The kth Factor of n (LeetCode 1492): Solution and Explanation

Medium
Math
Number Theory

Given positive integers n and k, list the factors of n in ascending order and return the kth one, or -1 if n has fewer than k factors.

Intuition

The direct approach tests every i from 1 to n and counts the divisors. That is O(n) and passes for n up to 1000, but there is a neater view of the problem.

Divisors come in pairs. If d divides n, then n / d does too, and of the two numbers one is at most sqrt(n) and the other is at least sqrt(n). So every factor can be found by testing only d from 1 to sqrt(n).

Order falls out for free. As d climbs from 1 to sqrt(n), the small halves appear in ascending order. As d then walks back down, the partners n / d get larger, so the large halves also appear in ascending order. Count k down along that U-shaped walk and stop when it reaches zero.

Approach: Factor pairs, up then down

  1. Walk d from 1 while d * d <= n. Each time d divides n, decrement k; if k hits 0, return d.
  2. After the loop, step d back to floor(sqrt(n)).
  3. If d * d == n, decrement d once more: the square root pairs with itself and was already counted.
  4. Walk d down to 1. Each time d divides n, decrement k; if k hits 0, return n / d.
  5. If the walk ends without k reaching 0, return -1.

Step-by-step example

n = 12, k = 3
  1. sqrt(12) is about 3.46, so the candidates on the way up are 1, 2 and 3.
  2. d = 1 divides 12 (partner 12). It is factor #1, so k = 2.
  3. d = 2 divides 12 (partner 6). It is factor #2, so k = 1.
  4. d = 3 divides 12 (partner 4). It is factor #3, so k = 0 and the answer is 3.
  5. The way down was never needed. Had k been 5, the walk down would visit partners 4 and then 6, and return 6.

Code: Python, Java, C++

1class Solution:
2    def kthFactor(self, n: int, k: int) -> int:
3        d = 1
4        while d * d <= n:
5            if n % d == 0:
6                k -= 1
7                if k == 0:
8                    return d
9            d += 1
10        d -= 1
11        if d * d == n:
12            d -= 1
13        while d >= 1:
14            if n % d == 0:
15                k -= 1
16                if k == 0:
17                    return n // d
18            d -= 1
19        return -1
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(sqrt(n))

Each of the two walks visits at most sqrt(n) candidates.

Space

O(1)

Only the counter d and the remaining k are stored.

Other approaches

Test every number (time O(n), space O(1))

Loop i from 1 to n, decrement k whenever i divides n, and return i when k reaches 0. It is the simplest correct answer and fine for n up to 1000.

Collect both halves into a list (time O(sqrt(n)), space O(sqrt(n)))

Gather small factors into one list and their partners into another, then join the first list with the reversed second list and index k - 1. Same O(sqrt n) time but O(sqrt n) extra space.

Common mistakes

  • Counting sqrt(n) twice when n is a perfect square. For n = 36, the pair 6 x 6 is a single factor.
  • Walking the large halves in the wrong direction. Partners n / d grow as d shrinks, so the second loop must count d downward.
  • Starting the second loop at the d where the first loop stopped. That d already failed d * d <= n, so step back by one first.

Frequently asked questions

Why does walking d downward list the large factors in ascending order?

The partner of d is n / d, and n / d gets bigger as d gets smaller. Visiting d = 3, 2, 1 for n = 12 gives partners 4, 6, 12.

Why is checking up to sqrt(n) enough?

If d and n / d were both larger than sqrt(n), their product would exceed n. So every pair has a half at or below sqrt(n), and testing those finds every factor.

Is the O(n) loop accepted?

Yes. With n at most 1000 it runs instantly. The pair walk matters as a follow-up question, or when n is large.

What is returned when k is larger than the number of factors?

Both walks finish with k still positive, and the function returns -1.