1. Linear Scan from Right
Intuition
Iterate backwards from n - 1 down to 0. The first element equal to target is the rightmost occurrence. If loop completes, return -1.
When to apply: Unsorted collections or very small arrays.
Algorithm
- Step 1: Iterate index i from arr.length - 1 down to 0.
- Step 2: If arr[i] == target, return index i immediately.
- Step 3: If loop finishes without match, return -1.
#include <iostream>#include <vector> using namespace std; int lastOccurrence(const vector<int>& arr, int target) { for (int i = (int)arr.size() - 1; i >= 0; 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 Last Occurrence of 5: " << lastOccurrence(arr, 5) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Worst case checks all N elements when target is at index 0 or absent. - Space complexity:
O(1)— Uses a single loop index variable.