Kth Smallest Number in Multiplication Table — LeetCode 668 Python Solution
- Problem
- #668
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed).
Example
- Input
- m = 3, n = 3, k = 5
- Output
- 3
- Explanation
- The 5th smallest number is 3.
Python solution
class Solution:
def findKthNumber(self, m: int, n: int, k: int) -> int:
left, right = 1, m * n
while left < right:
mid = (left + right) >> 1
cnt = 0
for i in range(1, m + 1):
cnt += min(mid // i, n)
if cnt >= k:
right = mid
else:
left = mid + 1
return leftComplexity
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 668. Kth Smallest Number in Multiplication Table is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 668. Kth Smallest Number in Multiplication Table?
- LeetCode 668. Kth Smallest Number in Multiplication Table is rated Hard on LeetCode.
- What topics does LeetCode 668. Kth Smallest Number in Multiplication Table cover?
- LeetCode 668. Kth Smallest Number in Multiplication Table is tagged Math and Binary Search on LeetCode.