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.
1def binary_search(arr, target):
2 left, right = 0, len(arr) - 1
3 while left <= right:
4 mid = left + (right - left) // 2
5 if arr[mid] == target:
6 return mid
7 elif arr[mid] < target:
8 left = mid + 1
9 else:
10 right = mid - 1
11 return -1
12
13arr = [1, 2, 3, 4, 5]
14target = 3
15result = binary_search(arr, target)
16print(f"Element found at index: {result}")
17
This Python implementation reads a sorted array and performs binary search to find the target value. It continuously halves the search space and checks positions using mid
indices, resulting in an efficient search.
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 JavaScript code takes advantage of the two-pointer technique to find if a pair within a sorted array sums to the target. By summing elements at both ends and moving pointers smartly, it quickly finds or rules out solutions.