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.
1using System;
2
3class Program {
4 public static int BinarySearch(int[] arr, int target) {
5 int left = 0, right = arr.Length - 1;
6 while (left <= right) {
7 int mid = left + (right - left) / 2;
8 if (arr[mid] == target) return mid;
9 else if (arr[mid] < target) left = mid + 1;
10 else right = mid - 1;
11 }
12 return -1;
13 }
14
15 static void Main() {
16 int[] arr = {1, 2, 3, 4, 5};
17 int target = 3;
18 int result = BinarySearch(arr, target);
19 Console.WriteLine("Element found at index: " + result);
20 }
21}
22
In this C# code, binary search is used to locate the target index within a sorted array. Using a loop, the mid-point is calculated and adjusted based on whether the median matches the target, is smaller, or larger.
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.