Math Fundamentals18 sections · 814 units
Open in Course

Search Insert - Walkthrough (Tracing execution)

Step-by-step example

Let's trace nums=[1,3,5,6]nums = [1, 3, 5, 6] and target=2target = 2. Initially, left=0left = 0 and right=3right = 3.

Step 1: mid=1mid = 1, nums[1]=3>2nums[1] = 3 > 2, so right=0right = 0. Step 2: mid=0mid = 0, nums[0]=1<2nums[0] = 1 < 2, so left=1left = 1. Now left>rightleft > right, so the loop exits and returns left=1left = 1.

The answer is 11, which is correct: insert 22 at index 11 to keep the array sorted. You made 22 comparisons, which is O(log4)=2O(\log 4) = 2.