This problem looks busy at first, but the accepted solution is built around one steady invariant. For 35. Search Insert Position, the solution in this repository is mainly a two pointers solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: two pointers.
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are searchInsert.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 8 ms, faster than 98.48% of C++ online submissions for Search Insert Position.
02//Memory Usage: 8.9 MB, less than 97.84% of C++ online submissions for Search Insert Position.
03
04class Solution {
05public:
06 int searchInsert(vector<int>& nums, int target) {
07 //find the first number larger than target
08 for(int i = 0; i < nums.size(); i++){
09 if(nums[i] >= target) return i;
10 }
11 //if target is the largest
12 return nums.size();
13 }
14};
15
16//binary search
17//Runtime: 4 ms, faster than 99.20% of C++ online submissions for Search Insert Position.
18//Memory Usage: 9.7 MB, less than 57.82% of C++ online submissions for Search Insert Position.
19class Solution {
20public:
21 int searchInsert(vector<int>& nums, int target) {
22 int n = nums.size();
23 int l = 0, r = n-1;
24 int mid;
25
26 //find lower bound
27 while(l <= r){
28 mid = l + (r-l)/2;
29 if(nums[mid] == target){
30 return mid;
31 }else if(nums[mid] < target){
32 l = mid+1;
33 }else{
34 r = mid-1;
35 }
36 }
37
38 return l;
39 }
40};
Cost