LeetCode Entry
35. Search Insert Position
For more robust code consider
35. Search Insert Position easy
fun searchInsert(nums: IntArray, target: Int): Int {
var lo = 0
var hi = nums.lastIndex
while (lo <= hi) {
val mid = lo + (hi - lo) / 2
if (target == nums[mid]) return mid
if (target > nums[mid]) lo = mid + 1
else hi = mid - 1
}
return lo
}
Join me on Telegram
https://t.me/leetcode_daily_unstoppable/124
Intuition
Just do a binary search
Approach
For more robust code consider:
- use only inclusive boundaries
loandhi - loop also the last case when
lo == hi - always move boundaries
mid + 1ormid - 1 - use distinct check for the exact match
nums[mid] == target - return
loposition - this is an insertion point
Complexity
- Time complexity: \(O(log_2(n))\)
- Space complexity: \(O(1)\)