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.
class Program {
public static bool TwoPointerSearch(int[] arr, int target) {
int left = 0, right = arr.Length - 1;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == target) return true;
else if (sum < target) left++;
else right--;
}
return false;
}
static void Main() {
int[] arr = {1, 2, 3, 4, 5};
int target = 8;
bool result = TwoPointerSearch(arr, target);
Console.WriteLine("Pair found: " + (result ? "Yes" : "No"));
}
}
This C# code implements the two-pointer technique. It assesses if the sum of numbers pointed by left
and right
equates to the target, modifying their references intelligently to prevent exhaustive iterations.