Leetcode 1492: The kth Factor of n

grid47
grid47
Exploring patterns and algorithms
Jun 10, 2024 4 min read

You are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0. Consider a sorted list of all factors of n in ascending order. Return the kth factor from this list or return -1 if n has less than k factors.
Problem
Approach
Steps
Complexity
Input: You are given two integers n and k. The integer n represents the number for which we need to find the factors, and k represents the position of the factor to return.
Example: n = 18, k = 4
Constraints:
• 1 <= k <= n <= 1000
Output: Return the kth factor in the list of factors of n, or -1 if n has fewer than k factors.
Example: Output: 6
Constraints:
• If n has less than k factors, return -1.
Goal: To find the kth factor of n by iterating through its divisors and returning the kth one.
Steps:
• Iterate through integers from 1 to n.
• Check if each integer divides n without a remainder.
• Count the divisors and return the kth divisor if it exists.
• If fewer than k divisors are found, return -1.
Goal: The integer n must be between 1 and 1000, and k is a positive integer less than or equal to n.
Steps:
• 1 <= k <= n <= 1000
Assumptions:
• The input values of n and k will always be valid integers within the specified range.
Input: n = 18, k = 4
Explanation: The factors of 18 are [1, 2, 3, 6, 9, 18]. The 4th factor is 6.

Input: n = 9, k = 3
Explanation: The factors of 9 are [1, 3, 9]. The 3rd factor is 9.

Input: n = 10, k = 5
Explanation: The factors of 10 are [1, 2, 5, 10]. There are only 4 factors, so the result is -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus