EASY NC#28 Binary Search
704. Binary Search
๐ Problem
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. You must write an algorithm with O(log n) runtime complexity.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขIn-place array updates
- โขSorted array traversal
- โขBoundary condition checks
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply Two Pointers reasoning pattern
- โขApply Binary Search reasoning pattern
- โขApply Recursion reasoning pattern
๐ก Approach
- โ Use two pointers (left and right)
- โ Calculate mid and compare with target
- โ Narrow search space by half each iteration
- โ Time: O(log n), Space: O(1)
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse two pointers (left and right)
- โขCalculate mid and compare with target
- โขNarrow search space by half each iteration
Common Pitfalls
- โขTime: O(log n), Space: O(1)
๐งช Test Cases
Hidden tests on submit: 5
Test Case 1
Not run Input:
search([-1, 0, 3, 5, 9, 12], 9); Expected:
4 Test Case 2
Not run Input:
search([-1, 0, 3, 5, 9, 12], -1); Expected:
0 Test Case 3
Not run Input:
search([-1, 0, 3, 5, 9, 12], 12); Expected:
5 ๐ Code Editor
๐ค Output