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
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.