#668

Kth Smallest Number in Multiplication Table

Hard
MathBinary SearchBinary SearchCounting Sort
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n² log(n²))
O(m log(m * n))
Space
O(n²)
O(1)
💡

Intuition

Time O(m log(m * n))Space O(1)

Instead of generating the entire multiplication table, we can use binary search to efficiently find the k-th smallest number by counting how many numbers are less than or equal to a mid value.

⚙️

Algorithm

5 steps
  1. 1Step 1: Set low = 1 and high = m * n (the largest possible value in the table).
  2. 2Step 2: While low < high, calculate mid = (low + high) // 2.
  3. 3Step 3: Count how many numbers in the multiplication table are less than or equal to mid using the formula: count += min(mid // i, n) for i from 1 to m.
  4. 4Step 4: If count < k, set low = mid + 1; otherwise, set high = mid.
  5. 5Step 5: Return low as the k-th smallest number.
solution.py10 lines
1def kthSmallest(m, n, k):
2    low, high = 1, m * n
3    while low < high:
4        mid = (low + high) // 2
5        count = sum(min(mid // i, n) for i in range(1, m + 1))
6        if count < k:
7            low = mid + 1
8        else:
9            high = mid
10    return low

Complexity note: The time complexity is O(m log(m * n)) because we perform binary search on the range of possible values and count the elements in O(m) time. The space complexity is O(1) since we only use a few variables.

  • 1The multiplication table is structured such that smaller numbers appear more frequently in the earlier rows and columns.
  • 2Using binary search allows us to efficiently narrow down the possible values without generating the entire table.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.