pythonbinary-search

LeetCode Python Interpreter giving a different answer from local interpreter


I was practicing some of the binary search based questions on LeetCode. I was working on the question 1283 (Find The Smallest Divisor). My python code was giving the wrong answer every time. I decided to use my local debugger to see where I got it wrong but unexpectedly my local debugger gave me the right answer for the same code. I contacted a friend who had already completed this question in CPP and asked him to run my code from his account and my solution was accepted on LeetCode from his account. While posting this question I took one more look at the question and found out that on changing line 10 s += math.ceil(i/mid) to s += -(-i//mid)(As far as I know both have same meaning), LeetCode accepted my solution from my account itself. Does anyone have an idea what was the reason for this. I am really curious about this.

Screenshot from Leetcode

This is my code

import math
class Solution(object):
    def smallestDivisor(self, nums, threshold):   
        l,r = 1,max(nums)
        div = float('inf')
        while l <= r:
            mid = (l+r)//2
            s = 0
            for i in nums:
                s += math.ceil(i/mid)
            if s <= threshold:
                div = mid
                r = mid - 1
            else: l = mid + 1
        return div

I changed the last line to print(div) for running in local debugger.


Solution

  • In your screenshot you are using Python 2.

    Using the Python 3 compiler will give the correct result.

    Click on "Python"

    enter image description here

    Select "Python3"

    enter image description here

    Result when ran using Python 3

    enter image description here