🔍 Searching
Learn important searching techniques in C from basic linear search to interview-oriented advanced searching methods.
📖 Introduction to Searching
Searching is the process of finding whether a particular value exists in a collection of data and, if it exists, determining its position.
The choice of searching algorithm depends mainly on whether the data is sorted, how uniformly the values are distributed, and whether the data structure supports random access.
🔎 Linear Search
Check each element one by one until the target is found or the collection ends.
💡 Key Idea
Start from the first element and compare every element with the target. The first matching position is returned. If no element matches, report that the target is not present.
🧠 Example
For [12, 7, 25, 9, 18] and target 25,
compare 12 → 7 → 25.
The target is found at index 2.
🔹 Step-by-Step Algorithm
- Read the array and target value.
- Start from index 0.
- Compare the current element with the target.
- If equal, return the index.
- Otherwise move to the next element.
- If the array ends, report not found.
🎬 Premium Linear Search Visualizer
Watch the search pointer move one element at a time until the target is found.
📦 Live Search State
Ready📊 Live Statistics
🧠 Current Search State
🧾 Recent Actions
#include <stdio.h>
int main() {
int n, target, i, position = -1;
scanf("%d", &n);
int a[n];
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &target);
for (i = 0; i < n; i++) {
if (a[i] == target) {
position = i;
break;
}
}
if (position != -1)
printf("Element found at index %d\n", position);
else
printf("Element not found\n");
return 0;
}
Sample Input
5
12 7 25 9 18
25Sample Output
Element found at index 2Input explanation: First enter the number of elements, then the elements, followed by the target.
💻 Program
🧠 What is happening?
📊 Live Variables
📦 Live Array — Linear Search
⚡ Complexity
Space: O(1) because only a few variables are used apart from the input array.
⚡ Binary Search
Repeatedly divide a sorted search range into two halves.
💡 Key Idea
Binary Search compares the target with the middle element. If the target is smaller, continue in the left half; if larger, continue in the right half. The process continues until the target is found or the range becomes empty.
🔁 Approaches
💡 Example
For [3, 7, 11, 18, 25, 31, 40], searching for 25
starts at the middle, eliminates the left or right half based on comparison,
and quickly reaches 25.
🔹 Iterative Algorithm
- Set
low = 0andhigh = n - 1. - Calculate
mid = low + (high - low) / 2. - If
a[mid] == target, return the position. - If target is smaller, set
high = mid - 1. - Otherwise set
low = mid + 1. - Repeat while
low <= high.
🎬 Premium Iterative Binary Search Visualizer
See low, high and mid shrink the sorted search range after each comparison.
📦 Live Search State
Ready📊 Live Statistics
🧠 Current Search State
🧾 Recent Actions
#include <stdio.h>
int main() {
int n, target, low, high, mid, position = -1;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &target);
low = 0;
high = n - 1;
while (low <= high) {
mid = low + (high - low) / 2;
if (a[mid] == target) {
position = mid;
break;
} else if (target < a[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
if (position != -1)
printf("Element found at index %d\n", position);
else
printf("Element not found\n");
return 0;
}
Sample Input
7
3 7 11 18 25 31 40
25Sample Output
Element found at index 4💻 Program
🧠 What is happening?
📊 Live Variables
📦 Live Array — Binary Search Range
🔁 Recursive Binary Search
The recursive version uses the same divide-and-conquer idea. Instead of updating the search range inside a loop, it calls itself on the appropriate half.
- Check whether
low > high. If so, return -1. - Find the middle index.
- If the middle value is the target, return it.
- Search the left or right half recursively.
🎬 Premium Recursive Binary Search Visualizer
Follow each recursive call, active range and midpoint at every depth.
📦 Live Search State
Ready📊 Live Statistics
🧠 Current Search State
🧾 Recent Actions
#include <stdio.h>
int binarySearch(int a[], int low, int high, int target) {
if (low > high)
return -1;
int mid = low + (high - low) / 2;
if (a[mid] == target)
return mid;
if (target < a[mid])
return binarySearch(a, low, mid - 1, target);
return binarySearch(a, mid + 1, high, target);
}
int main() {
int n, target;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &target);
int position = binarySearch(a, 0, n - 1, target);
if (position != -1)
printf("Element found at index %d\n", position);
else
printf("Element not found\n");
return 0;
}
Sample Input
7
3 7 11 18 25 31 40
31Sample Output
Element found at index 5💻 Program
🧠 What is happening?
📊 Live Variables
📚 Recursive Call Stack
📦 Live Array — Recursive Binary Search Range
⚡ Complexity
Space: Iterative = O(1); Recursive = O(log n) because of the call stack.
🔄 Rotated Binary Search
Search efficiently in a sorted array that has been rotated around a pivot.
💡 Key Idea
At least one half of a rotated sorted array is always normally sorted. Identify the sorted half, determine whether the target lies inside it, and discard the appropriate half.
💡 Example
For [15, 18, 2, 3, 6, 12], the array was originally sorted but rotated.
The algorithm determines which half remains sorted at every step.
🔹 Step-by-Step Algorithm
- Set low and high.
- Find mid.
- If the middle element is the target, return mid.
- Check whether the left half is sorted.
- If the target belongs to the sorted half, search there; otherwise search the other half.
- Repeat until the range is empty.
🎬 Premium Rotated Binary Search Visualizer
See which half is sorted and which half can be discarded.
📦 Live Search State
Ready📊 Live Statistics
🧠 Current Search State
🧾 Recent Actions
#include <stdio.h>
int searchRotated(int a[], int n, int target) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] == target)
return mid;
if (a[low] <= a[mid]) {
if (a[low] <= target && target < a[mid])
high = mid - 1;
else
low = mid + 1;
} else {
if (a[mid] < target && target <= a[high])
low = mid + 1;
else
high = mid - 1;
}
}
return -1;
}
int main() {
int n, target;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &target);
int pos = searchRotated(a, n, target);
if (pos != -1)
printf("Element found at index %d\n", pos);
else
printf("Element not found\n");
return 0;
}
Sample Input
6
15 18 2 3 6 12
3Sample Output
Element found at index 3💻 Program
🧠 What is happening?
📊 Live Variables
📦 Live Array — Rotated Search Range
⚡ Complexity
Space: O(1) for the iterative implementation.
⏩ Jump Search
Search a sorted array by jumping fixed-size blocks and then performing a linear scan.
💡 Key Idea
Jump approximately √n positions at a time. Once a block containing the target is identified, perform a linear search inside that block.
🔹 Algorithm
- Choose block size √n.
- Jump through the array until the current value is at least the target.
- Linearly search the identified block.
- Return the index if found; otherwise return -1.
🎬 Premium Jump Search Visualizer
Watch fixed-size jumps locate a candidate block, then a linear scan finish the search.
📦 Live Search State
Ready📊 Live Statistics
🧠 Current Search State
🧾 Recent Actions
#include <stdio.h>
int jumpSearch(int a[], int n, int target) {
int step = 1;
while (step * step < n)
step++;
int prev = 0;
int next = step;
while (prev < n && a[(next < n ? next : n) - 1] < target) {
prev = next;
next += step;
if (prev >= n)
return -1;
}
while (prev < n && prev < next) {
if (a[prev] == target)
return prev;
if (a[prev] > target)
return -1;
prev++;
}
return -1;
}
int main() {
int n, target;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &target);
int pos = jumpSearch(a, n, target);
if (pos != -1)
printf("Element found at index %d\n", pos);
else
printf("Element not found\n");
return 0;
}
Sample Input
10
2 5 8 12 16 21 27 31 36 40
27Sample Output
Element found at index 6💻 Program
🧠 What is happening?
📊 Live Variables
📦 Live Array — Jump Search Block
⚡ Complexity
Space: O(1).
📍 Interpolation Search
Estimate the likely position of the target using the values at the boundaries.
💡 Key Idea
Unlike Binary Search, which always chooses the middle, Interpolation Search estimates a position. It works especially well when sorted values are approximately uniformly distributed.
🔹 Position Formula
🔹 Algorithm
- Set low and high.
- Check that the target is within the boundary values.
- Estimate the position using the interpolation formula.
- Compare the estimated value with the target.
- Move low or high accordingly.
- Repeat until found or the range becomes invalid.
🎬 Premium Interpolation Search Visualizer
See the estimated probe position move according to the target and boundary values.
📦 Live Search State
Ready📊 Live Statistics
🧠 Current Search State
🧾 Recent Actions
#include <stdio.h>
int interpolationSearch(int a[], int n, int target) {
int low = 0, high = n - 1;
while (low <= high && target >= a[low] && target <= a[high]) {
if (a[high] == a[low]) {
if (a[low] == target)
return low;
return -1;
}
int pos = low + (int)((long long)(target - a[low]) *
(high - low) /
(a[high] - a[low]));
if (a[pos] == target)
return pos;
if (a[pos] < target)
low = pos + 1;
else
high = pos - 1;
}
return -1;
}
int main() {
int n, target;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &target);
int pos = interpolationSearch(a, n, target);
if (pos != -1)
printf("Element found at index %d\n", pos);
else
printf("Element not found\n");
return 0;
}
Sample Input
10
10 20 30 40 50 60 70 80 90 100
70Sample Output
Element found at index 6💻 Program
🧠 What is happening?
📊 Live Variables
📦 Live Array — Interpolation Search Range
⚡ Complexity
Space: O(1).
🌀 Fibonacci Search
Use Fibonacci numbers to divide a sorted array into search ranges.
💡 Key Idea
Fibonacci Search divides the search range using Fibonacci numbers instead of using a direct midpoint. It requires sorted data and achieves logarithmic search time.
🔹 Algorithm
- Generate Fibonacci numbers until one is at least n.
- Use the Fibonacci values to choose a probe position.
- Compare the probe element with the target.
- Reduce the Fibonacci range toward the left or right.
- Continue until the target is found or the range is exhausted.
🎬 Premium Fibonacci Search Visualizer
Follow Fibonacci offsets as they choose probe positions and reduce the remaining range.
📦 Live Search State
Ready📊 Live Statistics
🧠 Current Search State
🧾 Recent Actions
#include <stdio.h>
int fibonacciSearch(int a[], int n, int target) {
int fib2 = 0;
int fib1 = 1;
int fib = fib1 + fib2;
while (fib < n) {
fib2 = fib1;
fib1 = fib;
fib = fib1 + fib2;
}
int offset = -1;
while (fib > 1) {
int i = offset + fib2;
if (i >= n)
i = n - 1;
if (a[i] < target) {
fib = fib1;
fib1 = fib2;
fib2 = fib - fib1;
offset = i;
}
else if (a[i] > target) {
fib = fib2;
fib1 = fib1 - fib2;
fib2 = fib - fib1;
}
else {
return i;
}
}
if (fib1 && offset + 1 < n && a[offset + 1] == target)
return offset + 1;
return -1;
}
int main() {
int n, target;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &target);
int pos = fibonacciSearch(a, n, target);
if (pos != -1)
printf("Element found at index %d\n", pos);
else
printf("Element not found\n");
return 0;
}
Sample Input
10
10 20 30 40 50 60 70 80 90 100
80Sample Output
Element found at index 7💻 Program
🧠 What is happening?
📊 Live Variables
📦 Live Array — Fibonacci Search
⚡ Complexity
Space: O(1).
⛓️ Skip List Search
Search an ordered linked structure using multiple levels of forward links.
💡 Key Idea
A Skip List augments a sorted linked list with extra forward links. Higher levels skip over many nodes, allowing the search to move quickly and then drop down to lower levels near the target.
🔹 Search Algorithm
- Start from the highest available level.
- Move forward while the next node is smaller than the target.
- When moving further would pass the target, drop one level.
- Repeat until level 0.
- Check the next node for equality.
🎬 Premium Skip List Search Visualizer
Move across higher levels first and drop down when the next jump would pass the target.
📦 Live Search State
Ready📊 Live Statistics
🧠 Current Search State
🧾 Recent Actions
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEVEL 3
typedef struct Node {
int key;
struct Node *forward[MAX_LEVEL + 1];
} Node;
Node *createNode(int key) {
Node *node = (Node *)malloc(sizeof(Node));
node->key = key;
for (int i = 0; i <= MAX_LEVEL; i++)
node->forward[i] = NULL;
return node;
}
void insert(Node *head, int key, int level) {
Node *update[MAX_LEVEL + 1];
Node *current = head;
for (int i = MAX_LEVEL; i >= 0; i--) {
while (current->forward[i] != NULL &&
current->forward[i]->key < key)
current = current->forward[i];
update[i] = current;
}
current = current->forward[0];
if (current != NULL && current->key == key)
return;
Node *newNode = createNode(key);
for (int i = 0; i <= level; i++) {
newNode->forward[i] = update[i]->forward[i];
update[i]->forward[i] = newNode;
}
}
int search(Node *head, int key) {
Node *current = head;
for (int i = MAX_LEVEL; i >= 0; i--) {
while (current->forward[i] != NULL &&
current->forward[i]->key < key)
current = current->forward[i];
}
current = current->forward[0];
if (current != NULL && current->key == key)
return 1;
return 0;
}
int main() {
Node *head = createNode(-1);
insert(head, 10, 0);
insert(head, 20, 1);
insert(head, 30, 2);
insert(head, 40, 1);
insert(head, 50, 3);
insert(head, 60, 2);
int target;
scanf("%d", &target);
if (search(head, target))
printf("Element found\n");
else
printf("Element not found\n");
return 0;
}
Sample Input
40Sample Output
Element found💻 Program
🧠 What is happening?
📊 Live Variables
⛓️ Live Skip List
⚡ Complexity
Space: O(n) because extra forward pointers are stored.
📊 Searching Algorithm Comparison
Compare the major searching algorithms at a glance.
| Algorithm | Data Requirement | Best | Average | Worst | Space |
|---|---|---|---|---|---|
| Linear Search | Sorted or Unsorted | O(1) | O(n) | O(n) | O(1) |
| Binary Search | Sorted | O(1) | O(log n) | O(log n) | O(1)* |
| Recursive Binary Search | Sorted | O(1) | O(log n) | O(log n) | O(log n) |
| Rotated Binary Search | Rotated Sorted Array | O(1) | O(log n) | O(log n) | O(1) |
| Jump Search | Sorted | O(1) | O(√n) | O(√n) | O(1) |
| Interpolation Search | Sorted & Uniformly Distributed | O(1) | O(log log n) | O(n) | O(1) |
| Fibonacci Search | Sorted | O(1) | O(log n) | O(log n) | O(1) |
| Skip List Search | Skip List | O(1) | O(log n) | O(n) | O(n) |
* Iterative Binary Search uses O(1) auxiliary space; recursive implementation uses O(log n) stack space.
📝 Important Interview Points
Key facts to remember before solving searching problems.
- Binary Search requires sorted data.
- Use
low + (high - low) / 2to calculate the midpoint safely. - Linear Search works on unsorted data.
- Binary Search reduces the search space by approximately half each step.
- Recursive Binary Search has O(log n) auxiliary stack space.
- Rotated Binary Search identifies a sorted half at every step.
- Interpolation Search is excellent for uniformly distributed sorted values.
- Jump Search uses √n-sized blocks.
- Fibonacci Search uses Fibonacci numbers to partition the search area.
- Skip Lists use multiple levels of links to speed up ordered searches.
- Always ask whether duplicate values are possible.
- For duplicate arrays, interviewers may ask for first occurrence, last occurrence, or count of occurrences.
💡 Interview Tips
- First identify whether the input is sorted.
- Look for words such as "minimum", "maximum", "first", "last", or "closest"; they often indicate a Binary Search variation.
- Always define the search range clearly.
- Check boundary cases: empty array, one element, target at beginning, target at end, and target absent.
- For rotated arrays, determine which half is sorted before deciding where to move.
- Explain why the complexity is logarithmic instead of simply stating O(log n).
❓ Common Interview Questions
Think about each question first. If you are unsure, open the answer and learn the short interview-ready explanation.
Binary Search decides whether to continue in the left half or right half by comparing the target with the middle element. That decision is valid only when the values are ordered.
After each comparison, Binary Search keeps only about half of the current elements. So the search sizes become n → n/2 → n/4 → ... → 1.
The iterative version repeatedly updates low and high inside a loop. The recursive version calls itself with a smaller range. Both take O(log n) search time, but recursion additionally uses call-stack space.
Instead of mid = (low + high) / 2, use mid = low + (high - low) / 2. This avoids directly adding two potentially large indices.
low + (high - low) / 2 so low + high does not overflow.Find mid. At least one side of a rotated sorted array is normally sorted. Identify that sorted half, check whether the target lies inside it, and discard the other half.
Interpolation Search is most effective when the array is sorted and values are distributed approximately uniformly. Its estimated position can then land very close to the target.
If values are distributed very unevenly, the interpolation formula may repeatedly estimate poor positions and reduce the search range only a little at a time.
The usual block size is approximately √n. Jumping by about √n balances the number of jumps with the number of elements that may need to be scanned inside the final block.
A Skip List is a sorted linked structure with multiple levels of forward pointers. Higher levels skip over several nodes so the search can move quickly, then drop to lower levels near the target.
With distinct values, it is normally easy to identify which half is sorted. With many duplicates, values at low, mid, and high may be equal, so the algorithm may not know which side can safely be discarded.
🎯 20 Searching Practice Problems
Try each problem yourself first. Use 💻 Solve It Yourself to write and test your C program. Use Hint only when needed, and Show Program if you want to study the complete solution.
Given an array and a target, print its index or -1.
Input: n, n integers, target
Output: index or -1
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
int n, t, pos = -1;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &t);
for (int i = 0; i < n; i++) {
if (a[i] == t) {
pos = i;
break;
}
}
printf("%d\n", pos);
return 0;
}
Sample Input
5
4 8 2 9 6
9Sample Output
3Count how many times a value occurs in an array.
Input: n, array, target
Output: count
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
int n, t, c = 0;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &t);
for (int i = 0; i < n; i++)
if (a[i] == t)
c++;
printf("%d\n", c);
return 0;
}
Sample Input
7
2 4 2 7 2 8 2
2Sample Output
4Find the first index of a target.
Input: n, array, target
Output: first index or -1
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
int n, t, pos = -1;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &t);
for (int i = 0; i < n; i++) {
if (a[i] == t) {
pos = i;
break;
}
}
printf("%d\n", pos);
return 0;
}
Sample Input
6
5 3 8 3 9 3
3Sample Output
1Find the last index of a target.
Input: n, array, target
Output: last index or -1
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
int n, t, pos = -1;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &t);
for (int i = 0; i < n; i++)
if (a[i] == t)
pos = i;
printf("%d\n", pos);
return 0;
}
Sample Input
6
5 3 8 3 9 3
3Sample Output
5Search for a target in a sorted array using iteration.
Input: sorted array and target
Output: index or -1
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
int n, t, lo, hi, mid, pos = -1;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &t);
lo = 0;
hi = n - 1;
while (lo <= hi) {
mid = lo + (hi - lo) / 2;
if (a[mid] == t) {
pos = mid;
break;
}
if (a[mid] < t)
lo = mid + 1;
else
hi = mid - 1;
}
printf("%d\n", pos);
return 0;
}
Sample Input
5
10 20 30 40 50
40Sample Output
3Implement Binary Search using recursion.
Input: sorted array and target
Output: index or -1
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int bs(int a[], int l, int h, int t) {
if (l > h)
return -1;
int m = l + (h - l) / 2;
if (a[m] == t)
return m;
if (t < a[m])
return bs(a, l, m - 1, t);
return bs(a, m + 1, h, t);
}
int main() {
int n, t;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &t);
printf("%d\n", bs(a, 0, n - 1, t));
return 0;
}
Sample Input
6
2 5 8 11 14 19
14Sample Output
4Find the first occurrence of a duplicate target using Binary Search.
Input: sorted array and target
Output: first index
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
int n, t, l = 0, h, pos = -1;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &t);
h = n - 1;
while (l <= h) {
int m = l + (h - l) / 2;
if (a[m] == t) {
pos = m;
h = m - 1;
} else if (a[m] < t) {
l = m + 1;
} else {
h = m - 1;
}
}
printf("%d\n", pos);
return 0;
}
Sample Input
7
2 4 4 4 7 9 12
4Sample Output
1Find the last occurrence of a target using Binary Search.
Input: sorted array and target
Output: last index
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
int n, t, l = 0, h, pos = -1;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &t);
h = n - 1;
while (l <= h) {
int m = l + (h - l) / 2;
if (a[m] == t) {
pos = m;
l = m + 1;
} else if (a[m] < t) {
l = m + 1;
} else {
h = m - 1;
}
}
printf("%d\n", pos);
return 0;
}
Sample Input
7
2 4 4 4 7 9 12
4Sample Output
3Find how many times a target occurs.
Input: sorted array and target
Output: count
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int first(int a[], int n, int t) {
int l = 0, h = n - 1, p = -1;
while (l <= h) {
int m = l + (h - l) / 2;
if (a[m] == t) {
p = m;
h = m - 1;
} else if (a[m] < t) {
l = m + 1;
} else {
h = m - 1;
}
}
return p;
}
int last(int a[], int n, int t) {
int l = 0, h = n - 1, p = -1;
while (l <= h) {
int m = l + (h - l) / 2;
if (a[m] == t) {
p = m;
l = m + 1;
} else if (a[m] < t) {
l = m + 1;
} else {
h = m - 1;
}
}
return p;
}
int main() {
int n, t;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &t);
int f = first(a, n, t), l = last(a, n, t);
printf("%d\n", f == -1 ? 0 : l - f + 1);
return 0;
}
Sample Input
8
1 2 2 2 3 4 4 7
2Sample Output
3Search a target in a rotated sorted array.
Input: rotated sorted array and target
Output: index or -1
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
int n, t, l = 0, h, pos = -1;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &t);
h = n - 1;
while (l <= h) {
int m = l + (h - l) / 2;
if (a[m] == t) {
pos = m;
break;
}
if (a[l] <= a[m]) {
if (a[l] <= t && t < a[m])
h = m - 1;
else
l = m + 1;
} else {
if (a[m] < t && t <= a[h])
l = m + 1;
else
h = m - 1;
}
}
printf("%d\n", pos);
return 0;
}
Sample Input
7
8 9 10 2 3 5 6
5Sample Output
5Search a sorted array using Jump Search.
Input: sorted array and target
Output: index or -1
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
int n, t, step = 1, prev = 0, pos = -1;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &t);
while (step * step < n)
step++;
int next = step;
while (prev < n && a[(next < n ? next : n) - 1] < t) {
prev = next;
next += step;
if (prev >= n)
break;
}
while (prev < n && prev < next) {
if (a[prev] == t) {
pos = prev;
break;
}
if (a[prev] > t)
break;
prev++;
}
printf("%d\n", pos);
return 0;
}
Sample Input
9
1 4 7 10 13 16 19 22 25
19Sample Output
6Search uniformly distributed sorted data using interpolation.
Input: sorted array and target
Output: index or -1
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
int n, t, l = 0, h, pos = -1;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &t);
h = n - 1;
while (l <= h && t >= a[l] && t <= a[h]) {
if (a[l] == a[h]) {
if (a[l] == t)
pos = l;
break;
}
int p = l + (int)((long long)(t - a[l]) * (h - l) / (a[h] - a[l]));
if (a[p] == t) {
pos = p;
break;
}
if (a[p] < t)
l = p + 1;
else
h = p - 1;
}
printf("%d\n", pos);
return 0;
}
Sample Input
10
10 20 30 40 50 60 70 80 90 100
90Sample Output
8Search a sorted array using Fibonacci partitions.
Input: sorted array and target
Output: index or -1
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
int n, t;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &t);
int f2 = 0, f1 = 1, f = f1 + f2;
while (f < n) {
f2 = f1;
f1 = f;
f = f1 + f2;
}
int off = -1, pos = -1;
while (f > 1) {
int i = off + f2;
if (i >= n)
i = n - 1;
if (a[i] < t) {
f = f1;
f1 = f2;
f2 = f - f1;
off = i;
} else if (a[i] > t) {
f = f2;
f1 = f1 - f2;
f2 = f - f1;
} else {
pos = i;
break;
}
}
if (pos == -1 && f1 && off + 1 < n && a[off + 1] == t)
pos = off + 1;
printf("%d\n", pos);
return 0;
}
Sample Input
8
5 10 15 20 25 30 35 40
30Sample Output
5Find the first index whose value is greater than or equal to the target.
Input: sorted array and target
Output: lower-bound index
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
int n, t, l = 0, h, pos;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &t);
h = n;
pos = n;
while (l < h) {
int m = l + (h - l) / 2;
if (a[m] >= t) {
pos = m;
h = m;
} else {
l = m + 1;
}
}
printf("%d\n", pos);
return 0;
}
Sample Input
6
2 4 7 9 12 15
8Sample Output
3Find the first index whose value is greater than the target.
Input: sorted array and target
Output: upper-bound index
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
int n, t, l = 0, h, pos;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &t);
h = n;
pos = n;
while (l < h) {
int m = l + (h - l) / 2;
if (a[m] > t) {
pos = m;
h = m;
} else {
l = m + 1;
}
}
printf("%d\n", pos);
return 0;
}
Sample Input
6
2 4 7 9 12 15
9Sample Output
4Find the position where a target should be inserted in sorted order.
Input: sorted array and target
Output: insertion index
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
int n, t, l = 0, h;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &t);
h = n;
while (l < h) {
int m = l + (h - l) / 2;
if (a[m] < t)
l = m + 1;
else
h = m;
}
printf("%d\n", l);
return 0;
}
Sample Input
5
10 20 30 40 50
35Sample Output
3Find an index of an element that is not smaller than its neighbors.
Input: n and array
Output: peak index
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
int l = 0, h = n - 1;
while (l < h) {
int m = l + (h - l) / 2;
if (a[m] < a[m + 1])
l = m + 1;
else
h = m;
}
printf("%d\n", l);
return 0;
}
Sample Input
6
1 3 8 7 5 2Sample Output
2Find floor(√x) without using a square-root library.
Input: non-negative integer x
Output: floor square root
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
long long x;
scanf("%lld", &x);
long long l = 0, h = x, ans = 0;
while (l <= h) {
long long m = l + (h - l) / 2;
if (m == 0 || m <= x / m) {
ans = m;
l = m + 1;
} else {
h = m - 1;
}
}
printf("%lld\n", ans);
return 0;
}
Sample Input
50Sample Output
7Each element may be at its correct position or one position away. Find the target.
Input: nearly sorted array and target
Output: index or -1
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
int n, t;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d", &t);
int l = 0, h = n - 1, pos = -1;
while (l <= h) {
int m = l + (h - l) / 2;
if (a[m] == t) {
pos = m;
break;
}
if (m - 1 >= l && a[m - 1] == t) {
pos = m - 1;
break;
}
if (m + 1 <= h && a[m + 1] == t) {
pos = m + 1;
break;
}
if (t < a[m])
h = m - 2;
else
l = m + 2;
}
printf("%d\n", pos);
return 0;
}
Sample Input
6
10 20 30 25 40 50
25Sample Output
3Find the minimum element in a rotated sorted array.
Input: rotated sorted array
Output: minimum value
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
int l = 0, h = n - 1;
while (l < h) {
int m = l + (h - l) / 2;
if (a[m] > a[h])
l = m + 1;
else
h = m;
}
printf("%d\n", a[l]);
return 0;
}
Sample Input
7
15 18 2 3 6 12 13Sample Output
2