1. Linear Scan Insertion Point
Intuition
Scan the array from left to right. The first element nums[i] that is greater than or equal to target marks the insertion index. If no such element exists, target is larger than all elements; return nums.length.
When to apply: Unsorted or small arrays where O(N) is acceptable.
Algorithm
- Step 1: Iterate index i from 0 to nums.length - 1.
- Step 2: If nums[i] >= target, return index i immediately.
- Step 3: If loop completes without returning, return nums.length.
#include <iostream>#include <vector> using namespace std; class Solution {public: int searchInsert(vector<int>& nums, int target) { for (int i = 0; i < (int)nums.size(); i++) { if (nums[i] >= target) return i; } return nums.size(); }}; int main() { Solution sol; vector<int> nums = {1, 3, 5, 6}; cout << "Linear search insert index: " << sol.searchInsert(nums, 2) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Worst case scans all N elements when target exceeds every element. - Space complexity:
O(1)— Uses a single index counter variable.