1. Linear Search
Intuition
Iterate across the array using a simple for-loop. Check if (nums[i] == target) return i;. If loop finishes without a match, return -1. This ignores the sorted property of the array.
When to apply: Unsorted arrays or very small arrays (N <= 5) where binary search overhead is negligible.
Algorithm
- Step 1: Iterate index i from 0 to nums.length - 1.
- Step 2: Check if nums[i] equals target.
- Step 3: If equal, return index i immediately.
- Step 4: If loop completes without finding target, return -1.
#include <iostream>#include <vector> using namespace std; class Solution {public: int search(vector<int>& nums, int target) { for (int i = 0; i < (int)nums.size(); i++) { if (nums[i] == target) return i; } return -1; }}; int main() { Solution sol; vector<int> nums = {-1, 0, 3, 5, 9, 12}; cout << "Linear Search result: " << sol.search(nums, 9) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— In the worst case (target at last index or absent), scans all N elements. - Space complexity:
O(1)— Only uses a single loop counter index variable.