Kth Smallest Number in Multiplication Table — LeetCode 668 Python Solution

HardMathBinary Search
Problem
#668
Reading time
2 min

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

Python
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 left

Complexity

MeasureComplexity
TimeO(log n) or O(n log n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview