Python 1492.py
class Solution:
def kthFactor(self, n: int, k: int) -> int:
for i in range(1, n + 1):
if n % i == 0:
k -= 1
if k == 0:
return i
return -1
Difficulty
and has an acceptance rate of about 68% (300k+ submissions).
Typical patterns to solve this problem:
- Math
- Number Theory
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a method kthFactor that returns the k-th positive divisor of an integer n. If n has fewer than k divisors, the method returns -1. The algorithm proceeds by scanning every integer from 1 up to n, checking for divisibility, and counting the divisors until the desired position is reached.
Key Steps
Iterating through candidate divisors
The core of the method is a for loop that generates each integer i in the inclusive range [1, n].
for i in range(1, n + 1):
Testing divisibility
Inside the loop, the expression n % i == 0 determines whether i divides n without remainder, indicating that i is a factor.
if n % i == 0:
Updating the target position
When a factor is found, the counter k is decremented. This decrement tracks how many more factors must be encountered before reaching the k-th one.
k -= 1
Returning the result when the target is met
If the decrement operation reduces k to zero, the current divisor i is exactly the k-th factor, and the method returns it immediately.
if k == 0:
return i
Fallback when insufficient factors exist
If the loop completes without k reaching zero, it means n has fewer than the requested number of divisors. In that case, the method returns -1.
return -1
Edge Cases Handled
The algorithm naturally accommodates several boundary conditions without additional checks. When n is zero or negative, the range range(1, n + 1) produces no iterations, causing the method to fall through to the final return -1. This behavior correctly signals that no positive divisors exist in those scenarios.
If k is zero or negative at the start, the decrement operation will never satisfy the condition k == 0 during the loop, leading again to the final return -1. Thus the method treats non-positive k values as requests for an invalid factor position.
When k exceeds the total number of divisors of n, the loop exhausts all possible candidates without triggering the early return, and the method returns -1. This outcome correctly indicates that the requested factor order is out of range.
Performance Optimizations Observed
Although the algorithm examines each integer up to n, it incorporates an early-exit strategy. As soon as the k-th divisor is identified, the method returns immediately, bypassing any further unnecessary iterations. This early termination can significantly reduce work when k is small relative to the total number of divisors.
The use of the modulo operator (%) for divisibility testing is a direct and efficient primitive operation in Python, avoiding more elaborate arithmetic or data structures. By relying on this built-in operation, the code benefits from the interpreter’s optimized handling of integer arithmetic.
Overall, the implementation balances simplicity with a practical shortcut that prevents full traversal of the search space when the answer is found early.
ELI5 - Simplified Explanation
Imagine you have a big pile of building blocks and you want to see which smaller groups fit perfectly into that pile. This code acts like a little helper that looks at every number starting from one all the way up to the total size of your pile. Whenever it finds a group size that fits without leaving any blocks left over, it counts that group as a success. Since there might be many ways to group the blocks, it keeps track of how many successes have been found so far. When the count matches the specific spot you asked for, the helper points to that group size and says that is the answer. If the helper finishes looking at everything and still has not reached your target spot, it means the group size you wanted simply does not exist.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||
| Progiez | C++ | Python | Java | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| chandansgowda | Python | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| FelixFan1122 | C# | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| chandansgowda | Python | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| FelixFan1122 | C# | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 415: Add Strings
- problem 463: Island Perimeter
- problem 541: Reverse String II
- problem 1211: Queries Quality and Percentage
- problem 1251: Average Selling Price
- problem 1280: Students and Examinations
- problem 1327: List the Products Ordered in a Period
- problem 1378: Replace Employee ID With The Unique Identifier
- problem 1407: Top Travellers
- problem 1484: Group Sold Products By The Date
- problem 1517: Find Users With Valid E-Mails
- problem 1527: Patients With a Condition
- problem 1581: Customer Who Visited but Did Not Make Any Transactions
- problem 1587: Bank Account Summary II
- problem 1633: Percentage of Users Attended a Contest
- problem 1661: Average Time of Process per Machine
- problem 1667: Fix Names in a Table
- problem 1683: Invalid Tweets
- problem 1693: Daily Leads and Partners
- problem 1729: Find Followers Count
- problem 1731: The Number of Employees Which Report to Each Employee
- problem 1741: Find Total Time Spent by Each Employee
- problem 1757: Recyclable and Low Fat Products
- problem 1789: Primary Department for Each Employee
- problem 1795: Rearrange Products Table
- problem 1873: Calculate Special Bonus
- problem 1890: The Latest Login in 2020
- problem 1965: Employees With Missing Information
- problem 1978: Employees Whose Manager Left the Company
- problem 2356: Number of Unique Subjects Taught by Each Teacher
- problem 166: Fraction to Recurring Decimal
- problem 223: Rectangle Area
- problem 240: Search a 2D Matrix II
- problem 318: Maximum Product of Word Lengths
- problem 357: Count Numbers with Unique Digits
- problem 394: Decode String
- problem 1158: Market Analysis I
- problem 1341: Movie Rating
- problem 1498: Number of Subsequences That Satisfy the Given Sum Condition
- problem 1907: Count Salary Categories
- problem 1934: Confirmation Rate
- problem 2405: Optimal Partition of String
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality