Leetcode 704: Binary Search

grid47
grid47
Exploring patterns and algorithms
Aug 28, 2024 6 min read

A sorted array where binary search is applied, each step softly glowing to highlight the search process.
Solution to LeetCode 704: Binary Search Problem

You are given a sorted array of integers and a target value. Your task is to search for the target in the array. If the target exists, return its index. If it does not exist, return -1. You must achieve a time complexity of O(log n).
Problem
Approach
Steps
Complexity
Input: The input consists of a sorted array of integers and a target integer. The array is sorted in ascending order.
Example: nums = [1, 3, 5, 7, 9, 11], target = 5
Constraints:
• 1 <= nums.length <= 10^4
• -10^4 < nums[i], target < 10^4
• All integers in nums are unique.
• nums is sorted in ascending order.
Output: The function should return the index of the target if it exists in the array. If the target does not exist, return -1.
Example: Output: 2
Constraints:
• The result should be the index of the target value in the sorted array.
Goal: Implement an efficient search algorithm to find the target in the sorted array using binary search.
Steps:
• 1. Initialize two pointers: left and right, pointing to the first and last elements of the array.
• 2. Calculate the middle index as the average of left and right.
• 3. If the middle element is equal to the target, return the middle index.
• 4. If the middle element is less than the target, update the left pointer to mid + 1.
• 5. If the middle element is greater than the target, update the right pointer to mid - 1.
• 6. If the left pointer exceeds the right, return -1 indicating the target is not in the array.
Goal: The array is sorted in ascending order, and the target is an integer within the given range.
Steps:
• The array is guaranteed to be sorted in ascending order.
• All integers in the array are unique.
Assumptions:
• The target is a valid integer within the given range.
• The array is sorted and contains unique integers.
Input: Input: nums = [1, 3, 5, 7, 9, 11], target = 5
Explanation: The target 5 exists at index 2 in the sorted array, so the function will return 2.

Input: Input: nums = [1, 3, 5, 7, 9, 11], target = 8
Explanation: The target 8 does not exist in the array, so the function will return -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus