Kth Smallest Number in Multiplication Table in C++


Suppose we know about one Multiplication Table. But could we find out the k-th smallest number quickly from the multiplication table? So if we have to height m and the length n of a m * n Multiplication Table, and one positive integer k, we have need to find the k-th smallest number in this table.

So if m = 3 and n = 3 and k is 6, then the output will be 4., this is because the multiplication table is like −


123
1123
2246
3369

6th smallest element is 4 as [1,2,2,3,3,4,6,6,9]

To solve this, we will follow these steps −

  • Define a function ok(), this will take m, n, x,
  • ret := 0
  • for initialize i := 1, when i <= n, update (increase i by 1), do −
    • temp := minimum of x / i and m
    • ret := ret + temp
  • return ret
  • From the main method, do the following −
  • ret := -1, low := 1, high := m * n
  • while low <= high, do −
    • mid := low + (high - low) / 2
    • cnt := ok(m, n, mid)
    • if cnt >= k, then −
      • high := mid - 1
      • ret := mid
    • Otherwise
      • low := mid + 1
  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int ok(int m, int n, int x){
      int ret = 0;
      for(int i = 1; i <= n; i++){
         int temp = min(x / i, m);
         ret += temp;
      }
      return ret;
   }
   int findKthNumber(int m, int n, int k) {
      int ret = -1;
      int low = 1;
      int high = m * n ;
      while(low <= high){
         int mid = low + (high - low)/ 2;
         int cnt = ok(m, n, mid);
         if(cnt >= k){
            high = mid - 1;
            ret = mid;
         }else low = mid + 1;
      }
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.findKthNumber(3,3,6));
}

Input

“2*”

Output

4

Updated on: 01-Jun-2020

217 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements