6. Search Insert Position
easyAsked at WixBinary search for an insert position; Wix uses this when placing newly dragged components in a sorted layout array.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a sorted array of distinct integers and a target value, return the index where it is found. If not found, return the index where it would be inserted.
Constraints
1 <= nums.length <= 10^4nums is sorted ascending
Examples
Example 1
nums=[1,3,5,6], target=52Example 2
nums=[1,3,5,6], target=21Approaches
1. Linear scan
Walk the array.
- Time
- O(n)
- Space
- O(1)
for(let i=0;i<nums.length;i++) if(nums[i]>=target) return i; return nums.length;Tradeoff:
2. Binary search
Standard lo/hi sweep; lo lands on insert position.
- Time
- O(log n)
- Space
- O(1)
function searchInsert(nums,target){
let lo=0,hi=nums.length;
while(lo<hi){
const m=(lo+hi)>>1;
if(nums[m]<target) lo=m+1; else hi=m;
}
return lo;
}Tradeoff:
Wix-specific tips
Wix grades for correct boundary handling on the empty/end cases — they hit those edges constantly with single-row mobile layouts in their drag-drop builder.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Search Insert Position and other Wix interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →