Sponsored
Sponsored
This approach utilizes binary search to efficiently find the target element in a sorted array. Since the array is sorted, binary search can be applied, reducing the time complexity significantly compared to a linear search.
The core idea is to repeatedly divide the search interval in half. If the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half until the target is found or the interval is empty.
Time Complexity: O(log n), where n is the number of elements in the array.
Space Complexity: O(1), as no extra space is utilized.
1function binarySearch(arr, target) {
2 let left = 0, right = arr.length - 1;
3 while (left <= right) {
4 const mid = Math.floor(left + (right - left) / 2);
5 if (arr[mid] === target) return mid;
6 else if (arr[mid] < target) left = mid + 1;
7 else right = mid - 1;
8 }
9 return -1;
10}
11
12const arr = [1, 2, 3, 4, 5];
13const target = 3;
14const result = binarySearch(arr, target);
15console.log(`Element found at index: ${result}`);
16
This JavaScript function searches for a target integer within a sorted array using binary search. By recalculating the middle index for a shrinking range on each not-found try, it rapidly converges to the target's index.
The two-pointer approach helps to solve the problem with pointers or two index variables. This technique is beneficial when you need to minimize the number of iterations or traverse the array with controlled steps. Often used in problems involving arrays, especially when the sum or difference needs to be calculated between distinct elements.
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(1), as no extra space is consumed.
This Python function operates with two pointers set initially at opposite ends of the array, inspecting possibilities for a sum match to the target. It strategically adjusts the pointers based on their current sum until results are achieved.