Problem Statement
Given a sorted array and a target value, find the element in the array that is closest to the target using binary search.
Sample Test Case
Approaches
Brute Force
Idea
Iterate over the array and check the absolute difference between each element and the target. Track the element with the smallest difference.
Steps
- Initialize
minDiff
to a large number.
- Traverse each element in the array.
- Calculate the absolute difference between the current element and the target.
- Update
minDiff
and closestElement
if a smaller difference is found.
- Return the closest element.
Time Complexity
- O(n) where
n
is the length of the array.
Space Complexity
- O(1) since only a few extra variables are used.
Example Code
Dry Run
For arr = [1, 3, 5, 8, 12, 15]
and target = 7
, iterate through each element:
- Compare with 1 → diff = 6
- Compare with 3 → diff = 4
- Compare with 5 → diff = 2
- Compare with 8 → diff = 1 (update closest)
- Compare with 12 → diff = 5
- Compare with 15 → diff = 8
Result: 8
Efficient Approach (Binary Search)
Idea
Use binary search to efficiently find the closest element by narrowing down the search space.
Steps
- Use binary search to find the closest element or the position where the target would fit.
- Compare the target with the nearest elements (left and right).
- Return the closest element.
Time Complexity
- O(log n) due to the binary search.
Space Complexity
- O(1) as no additional space is required.
Example Code
Dry Run
For arr = [1, 3, 5, 8, 12, 15]
and target = 7
:
- First
mid = 2
, compare with 5 → target is greater, so left = 3
.
- Second
mid = 4
, compare with 12 → target is smaller, so right = 3
.
- Now, check the elements at
right = 2
(5) and left = 3
(8).
- Result: 8
Example Test Case
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
- Brute Force is simple but inefficient for large arrays, with O(n) time complexity.
- Binary Search provides an efficient solution with O(log n) time complexity and should be preferred for large datasets.