1. Brute Force (Linear Scan)
Intuition
Find first occurrence from start, and last occurrence by scanning from end or updating during iteration.
Algorithm
- Step 1: Initialize first = -1, last = -1.
- Step 2: Iterate i from 0 to nums.length - 1. If nums[i] == target: if first == -1 set first = i; always set last = i.
- Step 3: Return [first, last].
Linear Scan from Both Ends (O(N) Time)
2 of 2 questions left todayFirst occurrence of target 8 found at index 3
First occurrence of target 8 found at index 3.
#include <iostream>#include <vector> class Solution {public: std::vector<int> searchRange(std::vector<int>& nums, int target) { int first = -1, last = -1; for (int i = 0; i < (int)nums.size(); i++) { if (nums[i] == target) { if (first == -1) first = i; last = i; } } return {first, last}; }}; int main() { Solution sol; std::vector<int> nums = {5, 7, 7, 8, 8, 10}; std::vector<int> res = sol.searchRange(nums, 8); std::cout << "Range: [" << res[0] << ", " << res[1] << "]" << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Brute Force (Linear Scan). - Space complexity:
O(1)— Space complexity for Brute Force (Linear Scan).
Why Brute Force Doesn't Scale:
On a database table with 10 million rows sharing the same timestamp, a linear scan requires reading millions of disk blocks, whereas two B-Tree / binary index lookups take only ~24 comparisons.
With N = 1,000,000, linear scan takes up to 1,000,000 operations; binary search boundary takes at most 2 * 20 = 40 operations.