Searching is not just about finding an element.
In interviews and competitive programming, searching is about reducing the search space intelligently.
Most high-level problems are disguised as:
Linear search checks elements sequentially, one by one.
It does not require sorting, which makes it universally applicable but inefficient for large inputs.
int search(int[] arr, int key){
for(int i = 0; i < arr.length; i++){
if(arr[i] == key)
return i;
}
return -1;
}
Interview insight:
If constraints are small (n ≤ 10³), linear search is acceptable.
Binary search works on the principle:
“If the data is sorted, we don’t need to look everywhere.”
Each step removes half of the remaining elements.
int binarySearch(int[] arr, int key){
int low = 0, high = arr.length - 1;
while(low <= high){
int mid = low + (high - low) / 2;
if(arr[mid] == key)
return mid;
else if(arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
low + (high - low) / 2?Prevents integer overflow when low and high are large.
int binarySearch(int[] arr, int low, int high, int key){
if(low > high) return -1;
int mid = low + (high - low) / 2;
if(arr[mid] == key) return mid;
else if(arr[mid] < key)
return binarySearch(arr, mid + 1, high, key);
else
return binarySearch(arr, low, mid - 1, key);
}
Interview tip:
Use iterative unless recursion is explicitly asked.
Instead of searching in an array, we search within a range of possible answers.
Used when:
while(low <= high){
int mid = low + (high - low) / 2;
if(isPossible(mid)){
answer = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
If problem says:
First index where element ≥ target.
Example:
int lowerBound(int[] arr, int key){
int low = 0, high = arr.length;
while(low < high){
int mid = (low + high) / 2;
if(arr[mid] < key)
low = mid + 1;
else
high = mid;
}
return low;
}
First index where element > target.
Used together to find frequency:
frequency = upperBound - lowerBound;
Used heavily in:
Even after rotation:
[4,5,6,7,0,1,2]
This problem tests logical decision-making, not memorization.
lengthint low = 0, high = 1;
while(arr[high] < key){
low = high;
high = high * 2;
}
Then apply binary search.
This is common in:
An element greater than its neighbors.
Key fact:
Every array has at least one peak.
If slope is rising → peak on right
If slope is falling → peak on left
if(arr[mid] < arr[mid + 1])
low = mid + 1;
else
high = mid;
Time: O(log n)
Used on unimodal functions (first increases, then decreases).
Divides range into three parts.
Used in:
Less common in interviews, but important conceptually.
Binary search appears in: