1. Linear Scan
Intuition
Loop through the array starting from index 0. Check if (arr[i] >= x) return i;. If loop completes without finding any element >= x, return n.
When to apply: Unsorted collections or very small array sizes.
Algorithm
- Step 1: Iterate index i from 0 to arr.length - 1.
- Step 2: Check if arr[i] >= x.
- Step 3: If true, return index i immediately.
- Step 4: If no such element exists, return arr.length.
#include <iostream>#include <vector> using namespace std; int lowerBound(const vector<int>& arr, int x) { for (int i = 0; i < (int)arr.size(); i++) { if (arr[i] >= x) return i; } return arr.size();} int main() { vector<int> arr = {1, 2, 8, 10, 10, 12, 19}; cout << "Linear Lower Bound for 10: " << lowerBound(arr, 10) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Worst case scans all N elements when all values are less than x. - Space complexity:
O(1)— Uses a single loop index variable.