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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit