Problem Statement
Given a sorted array nums
and a target value, return the index if the target is found. If the target is not found, return -1
.
Example
- Input:
nums = [1, 2, 3, 4, 5]
, target = 3
- Output:
2
Approaches
Brute Force Approach
Idea
We can iterate through the array and check each element one by one. If the target is found, return the index; otherwise, return -1
.
Steps
- Iterate through each element of the array.
- If an element matches the target, return its index.
- If no element matches, return
-1
.
Time Complexity
- O(n): We iterate through the entire array.
Space Complexity
- O(1): No extra space is used.
Code
Dry Run
For nums = [1, 2, 3, 4, 5]
and target = 3
, the function checks each element and returns 2
when it finds the target.
Efficient Approach: Binary Search
Idea
Since the array is sorted, we can apply binary search to halve the search space at each step. This reduces the time complexity significantly.
Steps
- Set two pointers
left
and right
to the start and end of the array.
- Calculate the middle index.
- If the middle element is equal to the target, return the index.
- If the middle element is greater than the target, continue searching in the left half.
- If the middle element is less than the target, continue searching in the right half.
- If no match is found, return
-1
.
Time Complexity
- O(log n): Each step reduces the search space by half.
Space Complexity
- O(1): No extra space is used.
Code
Dry Run
For nums = [1, 2, 3, 4, 5]
and target = 1
, the binary search process is as follows:
- The middle element is
3
, which is greater than the target 1
, so the search continues in the left half.
- The next middle element is
1
, which matches the target, so the index 0
is returned.
Example Test Cases
Test Case 1
Test Case 2
Complexity Analysis
Brute Force Approach
- Time Complexity: O(n)
- Space Complexity: O(1)
Efficient Approach (Binary Search)
- Time Complexity: O(log n)
- Space Complexity: O(1)
Conclusion
Binary search provides a much more efficient solution for finding an element in a sorted array, with a time complexity of O(log n). This makes it highly suitable for large datasets, compared to the linear search method, which operates in O(n) time.