[LeetCode] Top Interview 150 Problems Solving # 35 Search Insert Position

Understanding the Problem
This should be a typical binary search algorithm problem. This problem is meticulous about the time efficiency as this has to be solved with the time complex of O(log n).
There is a number target
as an integer. It is to find the right spot for target
to be in the list nums
, where numbers are sorted low to high like [1, 3, 6, 7]
. If target = 2
, the returned value should be 1
, as target
should be in between 1 and 3, which has the index 1 as the position.
Approach
Binary search has not been considered by me. I have always dealt with sorting problems with sorted()
function and search problems with index()
or find()
methods.
My idea was to solve this problem with finding the middle as half
and slicing the list down as the loop goes on and on. This was completely a wrong approach, because I would not be able to find the index with it.
The final approach was to update left
and right
values with index. I had a little help by a LLM though.
Solution
The solution with left
and right
as index approach mitigated the complexity of the code.
First,
left
andright
was set with index values, the beginning and the end of the list.In
while
loop, it will be stopped ifleft
meetsright
so it will not be processed any further even whenleft
is bigger thanright
Take
half
to get the value in the middle. iftarget
is equal to the valuenums[half]
, return the index valuehalf
.If
target
is greater thannums[half]
,left
is updated by addinghalf + 1
. It is to jump the index to the half so the binary approach is applied.+ 1
is added though, because of index differenceFor instance, imagine the list is
nums = [1, 3, 5, 7]
andtarget
is6
. In the first loop,half
will be(0 + 3) // 2
, which will be 1.target
is greater thannums[half]
, which is 3, so updateleft
withleft = 1 + 1
, to make it to 2 so it will start from index 2.Then this time only
nums = [5, 7]
will be considered.
In other cases, update
right
to stick with the left half.
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums) - 1
while left <= right:
half = (left + right) // 2
if target == nums[half]:
return half
elif target > nums[half]:
left = half + 1
else:
right = half -1
return left
Reflection
From my perspective, algorithm problems often require searching methods with good time complexity. Binary search with time complexity of O(log n) is very typical and I should be familiar with it. The key is to use index values other than dealing with the actual list and slicing.
Subscribe to my newsletter
Read articles from Ramhee Yeon directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Ramhee Yeon
Ramhee Yeon
South Korean, master's degree of AI. Programmer for LLM, app and web development. I am seeking opportunities to go to the USA and Canada, and Europe. I used to live in Frankfurt, Moscow, Pretoria, Baguio. Where to next?