Advertisement

Binary Search - LeetCode 704 Solution

Binary Search - Complete Solution Guide

Binary Search is LeetCode problem 704, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

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 . 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

Detailed Explanation

The problem asks us to implement a binary search algorithm. Given a sorted array of integers `nums` and an integer `target`, we need to find the index of the `target` in the array. If the `target` exists in the array, return its index; otherwise, return -1. A critical constraint is that the algorithm must have O(log n) runtime complexity, which strongly suggests using binary search.

Solution Approach

The solution uses the standard binary search algorithm. We initialize `left` to 0 and `right` to the last index of the array. Then, while `left` is less than or equal to `right`, we calculate the middle index `mid`. If the element at `nums[mid]` is equal to the `target`, we return `mid`. If `nums[mid]` is less than the `target`, we update `left` to `mid + 1` to search in the right half. If `nums[mid]` is greater than the `target`, we update `right` to `mid - 1` to search in the left half. If the loop finishes without finding the `target`, we return -1.

Step-by-Step Algorithm

  1. Step 1: Initialize `left` to 0 and `right` to `len(nums) - 1`.
  2. Step 2: While `left <= right`, repeat steps 3-6.
  3. Step 3: Calculate `mid = left + (right - left) // 2`. This prevents potential integer overflow.
  4. Step 4: If `nums[mid] == target`, return `mid`.
  5. Step 5: If `nums[mid] < target`, set `left = mid + 1`.
  6. Step 6: If `nums[mid] > target`, set `right = mid - 1`.
  7. Step 7: If the loop finishes without finding the target, return -1.

Key Insights

  • Insight 1: The array is sorted, making binary search the natural choice for achieving O(log n) complexity.
  • Insight 2: Binary search repeatedly divides the search interval in half. It compares the middle element of the interval with the target and adjusts the interval accordingly.
  • Insight 3: Handling the edge cases of the target not being present in the array and ensuring proper loop termination is crucial for a correct solution.

Complexity Analysis

Time Complexity: O(log n)

Space Complexity: O(1)

Topics

This problem involves: Array, Binary Search.

Companies

Asked at: Accenture, Cognizant, EPAM Systems, Infosys, Wipro, Zoho, tcs.