Problem Description
Given two positive integers n and k, find the kth factor of n when all factors of n are listed in ascending order. If n has fewer than k factors, return -1.
Key Insights
- Factors of n come in pairs (i and n/i), which allows iterating only up to sqrt(n) for efficiency.
- Use two lists: one to collect smaller factors (i) and one for their corresponding larger partners (n/i).
- Reverse the larger factor list and then merge with the smaller factor list to get a sorted order.
- Handle perfect squares carefully to avoid adding the same factor twice.
- For very small n (n <= 1000), this approach is very efficient, although it meets the follow-up challenge for reducing from O(n) to approximately O(sqrt(n)).
Space and Time Complexity
Time Complexity: O(√n) – looping only through numbers up to √n. Space Complexity: O(√n) – storing factors up to √n and their corresponding counterparts.
Solution
The basic idea is to iterate i from 1 to √n. If i divides n, then i is a factor and n/i is also a factor (if distinct). Append i into a "lowFactors" list and n/i into a "highFactors" list. After the loop, reverse the "highFactors" list to restore ascending order and then merge it with "lowFactors". Finally, check if the kth factor exists in the merged list; if yes, return it, otherwise, return -1.