Binary search
Finding the insertion point is finding the index where a value goes so the array stays sorted. Without duplicates, if the value is already there, the point is its index: the new one goes to its left. If it isn't there, binary search ends with i on the first larger element: that's the point. So the same binary search solves the problem by returning i instead of β1.
If there are duplicate values, regular binary search finds any one of them, not necessarily the first. To find the first, one detail changes: when nums[m] equals the target, instead of returning m, the search keeps going left with j = m β 1. When it ends, i is on the first duplicate. Walking left from any one also works, but costs O(n) if there are many duplicates.
Finding the left boundary, a value's first index, is the same as finding its insertion point. You just need to check that the value is there: if i ended up outside the array, or if nums[i] is another number, the value isn't there and β1 is returned. That way one function solves 2 problems.
For the right boundary, a value's last index, there's a shortcut: look for the first of the next value. If the array holds integers, the last 4 is right before the first 5. So you find 5's insertion point and subtract 1. It works even if 5 doesn't exist: its insertion point is still the first element greater than 4.
Another trick for boundaries: search for a value that surely isn't there. Since the array has only integers, searching for 4.5 never finds anything, and when it ends, i lands on the first element greater than 4.5 and j on the last smaller one. For the first 4, search for 3.5 and use i; for the last 4, search for 4.5 and use j. The target needs a type with decimals.
These variants solve common problems in O(log n): where to insert a value in a sorted list, how many times a value appears, how many elements are in a range, or the first day an account passed a certain balance. The underlying idea is always the same: give each pointer a goal and let binary search bring them closer.
