LeetCode
Binary Search (Find Element in Sorted Array)
EasyBinary Search & ArraysDay 8
Problem Statement
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.
Examples (Test Cases & Output)
Example 1:
Input:
nums = [2, 7, 11, 15], target = 9Output:
[0, 1]Explanation: Standard algorithmic evaluation matching the problem constraints.
Example 2:
Input:
nums = [3, 2, 4], target = 6Output:
[1, 2]Constraints
- 1 <= input.length <= 10^5
- Optimized time complexity: O(log N)
- Optimized space complexity: O(1)
Target Complexities
Optimal TimeO(log N)
Optimal SpaceO(1)
Core Algorithmic Insight:
Using low + Math.floor((high - low) / 2) avoids integer overflow compared to (low + high) / 2 in large arrays.
Font:Hack
Active Mode:Optimal Solution
Time: O(log N)•Space: O(1)
Loading VS Code Hack Editor...
How This Code Works:
Two pointers low = 0, high = nums.length - 1. Calculate mid = low + Math.floor((high - low) / 2) to prevent 32-bit integer overflow. Compare nums[mid] with target: if equal return mid, if target < nums[mid] discard right half (high = mid - 1), else discard left half (low = mid + 1). Halves the search space every step!