Solution: Kth Smallest Number in Multiplication Table
Let’s solve the Kth Smallest Number in Multiplication Table using the Matrices pattern.
We'll cover the following
Statement
You are given a multiplication table of size m
n
, where each element at position mat[i][j]
is calculated as
Your task is to find the m
, n
, and k
values.
Constraints:
m
,n
k
m
n
Solution
We need to find the
The key intuition of this solution lies in two things:
Ordered table: The numbers in the multiplication table are naturally ordered. The multiplication table has a specific structure: for each row
, the numbers are in the form , which are multiples of . Counting elements: For any given value
, we can determine how many values in the table are less than or equal to by counting the elements in each row that satisfies this condition. For each row , largest value in the row that is less than or equal to is at position in that row. However, the number of elements in the row is also bounded by , so the count of values less than or equal to in the row is . By summing up these counts for all rows, we can determine if is a valid candidate for the smallest number in the table.
We use binary search and iterate over the range of possible values from
We implement a function
IsEnough(x)
that calculates how many numbers in the multiplication table are less than or equal tox
by summing up the counts across all rows.We then initialize binary search bounds:
low = 1
(the smallest possible value)high = m * n
(the largest possible value in the table)
Next, we perform a binary search as long as
low
is less thanhigh
:Calculate the midpoint
mid = (low + high) / 2
. This midpoint is our current candidate for thesmallest number. Check if
enough(mid)
returns TRUE (i.e., at leastk
numbers are less than or equal tomid
).If it is, we set the upper bound to
high = mid
(as we search for the smallest validmid
).Otherwise, it means we need a larger number, so we update the lower bound to
low = mid + 1
.
We return
low
whenlow
equalshigh
, representing thesmallest number.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.