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 <iostream>
2#include <vector>
3
4int binarySearch(const std::vector<int>& arr, int target) {
5 int left = 0, right = arr.size() - 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
15int main() {
16 std::vector<int> arr = {1, 2, 3, 4, 5};
17 int target = 3;
18 int result = binarySearch(arr, target);
19 std::cout << "Element found at index: " << result << std::endl;
20 return 0;
21}
This C++ solution uses a vector for easier manipulation of dynamic arrays and implements binary search similarly to the C version. It efficiently narrows down the index range by checking against mid
values until the target is located.
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 C code solves the problem using two pointers: one pointing to the start of the array, and the other pointing to the end. If the sum of the values at these two pointers matches the target, a flag is set. Otherwise, the pointers are adjusted to optimize towards the condition.