Problem 35

Abstract / Summary

Given a sorted list of numbers and a target value find where the target should be placed to keep the list sorted.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0035.cpp

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        return lower_bound(nums.begin(), nums.end(), target) - nums.begin();
    }
};
6 lines | 171 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 52% (9+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a single public method searchInsert inside a class named Solution. The method receives a reference to a vector of integers, nums, which is assumed to be sorted in non-decreasing order, and an integer target. Its purpose is to determine the index at which target should be inserted to maintain the sorted order. The method accomplishes this by delegating the core work to the standard library algorithm lower_bound and then converting the resulting iterator into a zero-based index.

Key Steps

Invocation of lower_bound

The first logical step is a call to lower_bound, passing the beginning and ending iterators of the vector along with the target value.

auto it = lower_bound(nums.begin(), nums.end(), target);

lower_bound performs a binary search over the range [nums.begin(), nums.end()) and returns an iterator pointing to the first element that is not less than target. If every element in the vector is smaller than target, the returned iterator equals nums.end().

Conversion of iterator to index

The second step translates the iterator returned by lower_bound into an integer index by subtracting the beginning iterator of the vector.

int index = it - nums.begin();

The subtraction yields the distance between the two iterators, which corresponds to the position where target either already exists or should be inserted.

Return of the computed index

Finally, the method returns the computed index directly to the caller.

return index;

Edge Cases Handled

When the vector is empty, nums.begin() and nums.end() are identical. lower_bound immediately returns nums.begin(), and the subtraction yields zero, correctly indicating that the insertion point for any target is at indexβ€―0.

If target is smaller than the smallest element in the vector, lower_bound returns an iterator to the first element. The subtraction yields zero, which is the correct insertion position at the front of the vector.

When target exceeds the largest element, lower_bound returns nums.end(). Subtracting nums.begin() from nums.end() yields the size of the vector, indicating that the insertion point is immediately after the last element.

If target matches one or more elements in the vector, lower_bound points to the first occurrence of that value. The subtraction therefore returns the index of the first matching element, satisfying the requirement to insert before any duplicates.

Performance Optimizations Observed

The implementation leverages the highly optimized lower_bound algorithm from the C++ Standard Library. This algorithm is implemented with careful attention to iterator categories and branch prediction, providing a fast binary search without manual loop constructs. By using the library function, the code benefits from potential inlining, cache-friendly access patterns, and compiler-level optimizations that are difficult to replicate manually.

The subtraction of iterators to obtain the index is a constant-time operation, avoiding any additional traversal of the container. The overall approach eliminates the need for explicit loops or conditional checks, resulting in a concise and efficient solution that operates directly on iterator arithmetic.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long row of numbered toy blocks lined up from smallest to largest on the floor. There is a specific number written on a card that needs a spot in this line. If the number is already there, the task is to find exactly where it sits. If the number is missing, the task is to find the perfect place to put it so the line stays in the right order.

The code uses a special helper called lower bound that scans through the blocks very quickly. It looks at the row starting from the very first block and keeps going until it finds the first spot where a block is either the same as the target number or bigger than it. Once that spot is found, the computer calculates how far away that spot is from the very beginning of the line. This distance tells the computer exactly which position the number belongs in so that everything stays perfectly organized.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 29 | median = 9 | μ = 9.28 | σ = 0.64

Complexity Analysis

Time: logarithmic
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust JS Go PHP TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
DimitrisJim C
everthis JS
fartem Ruby
fengvyi C++
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C#
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
Shamik07 Dart
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vthwang Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, PHP, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fengvyi C++
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C#
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
Shamik07 Dart
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vthwang Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
62 links | 45 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Search Insert Position - Binary Search - Leetcode 35 - Python'
NeetCode 14 mins
Search Insert Position - Binary Search - Leetcode 35 - Python
YouTube video 'Search Insert Position (LeetCode 35) | Full solution with examples animations  | Study Algorithms'
Nikhil Lohia 15 mins
Search Insert Position (LeetCode 35) | Full solution with examples animations | Study Algorithms
YouTube video 'Search Insert Position - Leetcode 35 - Binary Search (Python)'
Greg Hogg 6 mins
Search Insert Position - Leetcode 35 - Binary Search (Python)
YouTube video 'Leetcode | 35. Search Insert Position | Easy | Java Solution'
Developer Docs 6 mins
Leetcode | 35. Search Insert Position | Easy | Java Solution
YouTube video 'Search Insert Position | LeetCode 35 | C++, Java, Python'
Knowledge Center 16 mins
Search Insert Position | LeetCode 35 | C++, Java, Python
YouTube video 'Leetcode 35. Search Insert Position [Java] | Binary search explained'
if else statement 9 mins
Leetcode 35. Search Insert Position [Java] | Binary search explained
YouTube video 'Search Insert Position - LeetCode 35 - JavaScript'
AlgoJS 4 mins
Search Insert Position - LeetCode 35 - JavaScript
YouTube video 'Search Insert Position | Java | Leetcode 35 | Binary Search'
SkillYaan | Deepali Shinde 13 mins
Search Insert Position | Java | Leetcode 35 | Binary Search
YouTube video 'How to Solve "35 Search Insert Position" on LeetCode? - Javascript'
Becoming A Better Dev (with David) 5 mins
How to Solve "35 Search Insert Position" on LeetCode? - Javascript
YouTube video '35. Search Insert Position | JavaScript | Binary Search | O(logn) TC | LeetCode Daily Challenge'
LeetCodeWithMonu 10 mins
35. Search Insert Position | JavaScript | Binary Search | O(logn) TC | LeetCode Daily Challenge
YouTube video 'Search Insert Position | Day 10 | [June LeetCoding Challenge] [Leetcode #35] [2020]'
Algorithms Made Easy 3 mins
Search Insert Position | Day 10 | [June LeetCoding Challenge] [Leetcode #35] [2020]
YouTube video 'Search Insert Position Python Solution - LeetCode #35'
Professor Oakes 4 mins
Search Insert Position Python Solution - LeetCode #35
YouTube video 'SEARCH INSERT POSITION | LEETCODE # 35 | LEARN BINARY SEARCH (PYTHON)'
Cracking FAANG 16 mins
SEARCH INSERT POSITION | LEETCODE # 35 | LEARN BINARY SEARCH (PYTHON)
YouTube video 'Search Insert Position | Leetcode 35 | Live coding session πŸ”₯πŸ”₯πŸ”₯ | Binary Search'
Coding Decoded 7 mins
Search Insert Position | Leetcode 35 | Live coding session πŸ”₯πŸ”₯πŸ”₯ | Binary Search
YouTube video 'Search Insert Position | Binary Search Iterative Recursive | Leetcode 35 | June Day 10'
Naresh Gupta 7 mins
Search Insert Position | Binary Search Iterative Recursive | Leetcode 35 | June Day 10
YouTube video '35. Search Insert Position | Leetcode | Arrays | Fundamentals'
Coding with Tamilarasan 9 mins
35. Search Insert Position | Leetcode | Arrays | Fundamentals
YouTube video 'Daily Leetcode #1056: Feb 20, 2023 - 35. Search Insert Position'
Programming Live with Larry 6 mins
Daily Leetcode #1056: Feb 20, 2023 - 35. Search Insert Position
YouTube video 'LeetCode 35 Search Insert Position'
Jeevan Kumar - Cracckify 8 mins
LeetCode 35 Search Insert Position
YouTube video 'Daily Leetcode #605: Nov 26, 2021 - 35. Search Insert Position'
Programming Live with Larry 6 mins
Daily Leetcode #605: Nov 26, 2021 - 35. Search Insert Position
YouTube video 'LeetCode 35: Search Insert Position | C# Solution | Binary Search Algorithm'
Code Scribbler 6 mins
LeetCode 35: Search Insert Position | C# Solution | Binary Search Algorithm
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

39 easy 31 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality