0
votes

Actually I am solving binary search problems from the Codestudio of Coding Ninjas, where there was one question, find the kth smallest element in the multiplication table. I solved the same problem on leetcode so I already know the solution of this question, but when I tried to solve the problem on Codestudio with similar approach, then it gives me wrong answer. But when I ran those testcases on leetcode then it gave me correct answer.

Problem Link:

Leetcode: [https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/]

Codestudio: [https://www.codingninjas.com/codestudio/problems/pahade_1262296]

My code:

class Solution {

public static int lesserThenMid(int i, int n, int x) {
    int low = 0, high = n - 1, mid;
    while (low <= high) {
        mid = low + (high - low) / 2;
        if (((mid+1)*(i+1)) <= x)
            low = mid + 1;
        else 
            high = mid - 1;
    }
    return low;
}

public int findKthNumber(int m, int n, int k) {
    int low = 1, high = m * n, mid, ans = -1, cnt;
    while (low <= high) {
        mid = low + (high - low) / 2;
        cnt = 0;
        for (int i = 0; i < m; i++) 
            cnt += Solution.lesserThenMid(i, n, mid);
        if (cnt >= k) {
            ans = mid;
            high = mid - 1;
        } else 
            low = mid + 1;
    }
    return ans;
}
}

Can anyone please help me. Is there any problem with Coding Ninjas Codestudio or there is some mistake in my code?

1
If in if (((mid+1)*(i+1)) <= x) it is equal, is it then correct to do low = mid +1? - Surt

1 Answers

0
votes

Your code seems fine to me. Do the test cases visible in coding ninjas on which our code fails like leetcode? If it is visible, I request you to please share the same.