LeetCode 1492: The kth Factor of n Solution

Master LeetCode problem 1492 (The kth Factor of n), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1492. The kth Factor of n

Problem Explanation

Explanation

To solve this problem efficiently, we can iterate from 1 to sqrt(n) and for each divisor i, we can check if n % i == 0. If it is true, then both i and n/i are factors of n. We can add them to a list and keep track of the count of factors found. Once we reach k factors, we return the kth factor. If k exceeds the count of factors found, we return -1.

  • Time complexity: O(sqrt(n))
  • Space complexity: O(k)

Solution Code

class Solution {
    public int kthFactor(int n, int k) {
        List<Integer> factors = new ArrayList<>();
        for (int i = 1; i * i <= n; i++) {
            if (n % i == 0) {
                factors.add(i);
                if (i != n / i) {
                    factors.add(n / i);
                }
            }
        }
        if (k > factors.size()) {
            return -1;
        }
        return factors.get(k - 1);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1492 (The kth Factor of n)?

This page provides optimized solutions for LeetCode problem 1492 (The kth Factor of n) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1492 (The kth Factor of n)?

The time complexity for LeetCode 1492 (The kth Factor of n) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1492 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1492 in Java, C++, or Python.

Back to LeetCode Solutions