709245. Kth Smallest Number in Multiplication Table
Hard
Kth Smallest Number in Multiplication Table
Slug: kth-smallest-number-in-multiplication-table
Difficulty: Hard
Id: 709245
Topic Tags: Binary Search, Algorithms
Company Tags: None
Summary
Given a multiplication table from 1 to n (inclusive), find the Kth smallest number in it. The table is represented as a sorted array where each element at index i represents the product of i+1 and its corresponding row number.
Detailed Explanation
To solve this problem, we can use binary search. We first calculate the total numbers in the multiplication table which is (n * (n + 1)) / 2. Then we start a binary search from 0 to the total numbers. For each mid value, we calculate the sum of numbers up to that value in the multiplication table and check if it's equal to K. If not, we move the search range accordingly.
Here is the step-by-step breakdown:
- Calculate the total numbers in the multiplication table:
n * (n + 1) / 2 - Start a binary search from 0 to the total numbers.
- For each mid value:
- Calculate the sum of numbers up to that value in the multiplication table.
- Check if it's equal to K.
- If not, move the search range accordingly.
The time complexity of this solution is O(log(n^2)) and space complexity is O(1).
Optimized Solutions
Java
public int findKthSmallest(int n, int k) {
int total = (n * (n + 1)) / 2;
int left = 0, right = total;
while (left <= right) {
int mid = left + (right - left) / 2;
int sum = getSum(mid, n);
if (sum == k) {
return mid;
} else if (sum < k) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // not found
}
int getSum(int mid, int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
if (i * (i + 1) / 2 > mid) {
break;
}
sum += i;
}
return sum;
}