HackerRank Past Contest

can anyone help me find the correct approach to solve this problem . I’ve tried using naive approach and also tried using priority queues to get the kth smallest element from the given matrice but both the solutions are fetching me runtime error for few TestCases/partially correct because of big constraints.

Do share your approach . Thankyou in adv :slight_smile:

I’ve discussed my solution in this thread, feel free to ping me if you don’t get it.

2 Likes

Thankyou so much senior .
but i’m afraid i am not able to understand this part of code .

 auto ok = [&](int x)->int{
    int c=0 ;
    for(int i=1;i<=n;i++)
      c+=min(x/i,n) ;
    return c<=k  ;
  } ;

Are you familiar with lambda functions? or you didn’t get the logic itself ?

3 Likes
#include "bits/stdc++.h"
using namespace std ;
#define int long long 

bool ok(int x , int n){
    int c=0 ;
    for(int i=1;i<=n;i++)
      c+=min(x/i,n) ;
    return (c<=k);
  } 

signed main(){
  int n,k ;
  cin >> n >> k ;--k;
  int lb = 1,rb=n*n ;
  while(lb<rb){
    int mb=(lb+rb)/2 ;
    if(ok(mb,n))
      lb =mb+1 ;
    else
      rb=mb  ;
  }
  cout << lb  ;
}

If u don’t know lambda function then : " Lambda expression in C++ - GeeksforGeeks"

2 Likes

i didn’t get the logic behind choosing the minimum between (x/i, n) and adding up them to compare with k.

Thankyou :slight_smile:

Have you checked these already? if you still don’t get it do let me know

2 Likes

Thankyou @cubefreak777 for this perfect explaination. Now i’ve understood it . :smile:

1 Like