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.
1#include <stdio.h>
2
3int binarySearch(int arr[], int size, int target) {
4 int left = 0, right = size - 1;
5 while (left <= right) {
6 int mid = left + (right - left) / 2;
7 if (arr[mid] == target) return mid;
8 else if (arr[mid] < target) left = mid + 1;
9 else right = mid - 1;
10 }
11 return -1;
12}
13
14int main() {
15 int arr[] = {1, 2, 3, 4, 5};
16 int target = 3;
17 int result = binarySearch(arr, 5, target);
18 printf("Element found at index: %d\n", result);
19 return 0;
20}
This C code implements a binary search. It initializes two pointers, left
and right
, and iteratively adjusts them based on comparisons with the middle element of the active subarray. When the target is found, it immediately returns the index. If not found, it returns -1.
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.
1#include <vector>
bool twoPointerSearch(const std::vector<int>& arr, int target) {
int left = 0, right = arr.size() - 1;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == target) return true;
else if (sum < target) left++;
else right--;
}
return false;
}
int main() {
std::vector<int> arr = {1, 2, 3, 4, 5};
int target = 8;
bool result = twoPointerSearch(arr, target);
std::cout << "Pair found: " << (result ? "Yes" : "No") << std::endl;
return 0;
}
This C++ implementation uses two pointers to scan predominantly from both ends of the vector. It relies on the sum of these two to make decisions about adjusting the pointers, ultimately determining if a pair is found.