#1492
The kth Factor of n
MediumMathNumber TheoryBrute ForceCountingEarly Exit
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of storing all factors, we can directly count them until we reach the k-th factor. This way, we avoid using extra space for storing all factors and stop early if we find the k-th factor.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a count variable to track the number of factors found.
- 2Step 2: Loop through all integers from 1 to n.
- 3Step 3: For each integer, check if it divides n evenly (n % i == 0). If it does, increment the count.
- 4Step 4: If the count equals k, return the current integer i as the k-th factor.
- 5Step 5: If the loop ends and the count is less than k, return -1.
solution.py10 lines
1# Full working Python code
2
3def kth_factor(n, k):
4 count = 0
5 for i in range(1, n + 1):
6 if n % i == 0:
7 count += 1
8 if count == k:
9 return i
10 return -1ℹ
Complexity note: The time complexity remains O(n) since we still check each number from 1 to n. The space complexity is O(1) because we do not use any additional space to store factors.
- 1Factors are numbers that divide n evenly.
- 2We can optimize by counting factors instead of storing them.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.