704. Binary Search LeetCode Solution

In this guide, you will get 704. Binary Search LeetCode Solution with the best time and space complexity. The solution to Binary Search problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Binary Search solution in C++
  4. Binary Search solution in Java
  5. Binary Search solution in Python
  6. Additional Resources
704. Binary Search LeetCode Solution image

Problem Statement of Binary Search

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.

Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4

Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1

Constraints:

1 <= nums.length <= 104
-104 < nums[i], target < 104
All the integers in nums are unique.
nums is sorted in ascending order.

Complexity Analysis

  • Time Complexity: O(\log n)
  • Space Complexity: O(1)

704. Binary Search LeetCode Solution in C++

class Solution {
 public:
  int search(vector<int>& nums, int target) {
    const auto it = ranges::lower_bound(nums, target);
    return (it == nums.cend() || *it != target) ? -1
                                                : distance(nums.begin(), it);
  }
};
/* code provided by PROGIEZ */

704. Binary Search LeetCode Solution in Java

class Solution {
  public int search(int[] nums, int target) {
    final int i = Arrays.binarySearch(nums, target);
    return i < 0 ? -1 : i;
  }
}
// code provided by PROGIEZ

704. Binary Search LeetCode Solution in Python

class Solution:
  def search(self, nums: list[int], target: int) -> int:
    i = bisect.bisect_left(nums, target)
    return -1 if i == len(nums) or nums[i] != target else i
# code by PROGIEZ

Additional Resources

See also  654. Maximum Binary Tree LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.