Can You Find The Bug? -- Longest subarray with sum at most S

Revision en1, by omtheprogrammer1, 2026-10-13 08:38:15

Okay, here's a challenge.

The code below is supposed to find the smallest integer x for which check(x) returns false, assuming check(x) is true for all smaller values and false for all larger values.

It compiles, and the logic looks pretty normal.

int l = -10, r = 10;

while (l < r) {
    int mid = (l + r) / 2;

    if (check(mid)) {
        l = mid + 1;
    }
    else {
        r = mid;
    }
}

Here, check(x) returns: - true if x is smaller than the target. - false if x is greater than or equal to the target.

Find a valid target for which this code gets stuck or fails.

Rules: - Give the smallest counterexample you can find. - Explain why the code fails. - Bonus: Fix it without changing the overall approach.

Try to find the bug before opening the comments.

Let's see who catches it first.

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English omtheprogrammer1 2026-10-13 08:38:53 53
en1 English omtheprogrammer1 2026-10-13 08:38:15 942 Initial revision (published)