I have already been working on LeetCode's top interview problems. I started a couple months ago
in preparation for my interviews with Google. Although that has passed, more opportunities are becoming available.
So, we are back on the grind.
The Problem
Today we are working on 35. Search Insert Position. The problem is as follows:
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7
Output: 4
The Solution
I like to format my answers using the UMPIRE method:
Understand
We are given a sorted array, and we are searching for an expected value.
Match
We can match this problem to a binary search problem, given the O(log N) complexity.
Plan
We will want a function that takes in an array and returns an integer.