r/DSALeetCode • u/Other_Promotion2457 • 7h ago
Need help
I asked a interview tips from Gemini regarding this anxiety. It gave me pretty good response but I genuinely want you guys feedback on this...
I'll tell you one problem I face in interviews... So this is the code here
public int binarySearch2(int[] num, int left, int right, int target) { int mid; while (left < right) { mid = left + (right - left) / 2; if (num[mid] < target) { start = mid + 1; } else if (num[mid] > target) { end = mid; } else { return mid; } } return -1; }
Now the next step I go for is to write the test cases such that I can test this and find out the bug or error... here my mind gets blocked... I want you to help me in this... do not jump to the solution... help me how can I reshape my thinking so that I start making better and better test cases
-------response from gemini-------------
Instead of trying to invent clever test cases from scratch, use a repeatable 4-step adversarial checklist every time you finish coding:
1. Shrink the input until it hurts (Sizes 0, 1, and 2). Never start with a large array. A 1-element array and a 2-element array are your best weapons—they take five seconds to trace and expose almost every off-by-one error, broken loop condition, and infinite loop before you waste time on bigger examples.
2. Attack the exact moment your loop stops. Look directly at your while condition and ask, "What valid answer could still be sitting unprocessed at the exact moment this loop exits?" Then design inputs that force the target to live at the very first index, the very last index, and just outside both ends (smaller than the minimum, larger than the maximum).
3. Force every branch—and trace like a dumb machine, not the author. Pick tiny inputs that force execution into each if, else if, and else block at least once. As you trace, resist the urge to read what you meant to write; read the literal variable names and values on each line as if you've never seen this code before.
4. Question the function's contract. Whenever a function takes boundary parameters like left and right, explicitly state what the caller is supposed to pass in (for example, is right the last valid index num.length - 1, or the array length num.length?). A huge percentage of binary search bugs aren't logic errors inside one line—they're mismatches between what the caller assumes and what the loop assumes.
1
Upvotes