1. Linear Scan from Left
Intuition
Iterate from index 0 to n - 1. As soon as arr[i] == target, return i immediately since it is the first match encountered.
When to apply: Unsorted arrays or tiny collections.
Algorithm
- Step 1: Iterate index i from 0 to arr.length - 1.
- Step 2: If arr[i] == target, return index i immediately.
- Step 3: If loop completes without match, return -1.
#include <iostream>#include <vector> using namespace std; int firstOccurrence(const vector<int>& arr, int target) { for (int i = 0; i < (int)arr.size(); i++) { if (arr[i] == target) return i; } return -1;} int main() { vector<int> arr = {1, 3, 5, 5, 5, 5, 67, 123, 125}; cout << "Linear First Occurrence of 5: " << firstOccurrence(arr, 5) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Worst case checks all N elements when target is absent or at the end. - Space complexity:
O(1)— Uses a single loop counter variable.