Why my C++ code TLE? while the same Python code are Accepted.

  • 0

    Here is my C++ code, which always TLE:

    class Solution {
        int firstBadVersion(int n) {
            int l = 1, r = n;
            while (l < r) {
                int mid = (l+r)/2;
                if (isBadVersion(mid)) {
                    r = mid;
                } else {
                    l = mid +1;
            return l;

    Here is my python code, the same binary search algo as C++, but this solution is accepted:

    def firstBadVersion(n):
        l = 1
        r = n
        while l < r:
            if isBadVersion(mid):
                r = mid
                l = mid+1
        return l

  • 5

    If l and r are very large , (l+r) would exceed the limit of INT_MAX,cause that mid is not correct and you could not meet the condition l<r so the loop would not end.

    Python can auto convert type 'int' to type 'long' to avoid this problem.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.