Search Insert Position
Given a sorted array of distinct integers nums and an integer target, return the index if target is found.
If target is not found, return the index where it would be inserted in order.
You must write an algorithm with O(log n) runtime complexity.
Example 1
Input
n = 4 nums = [1, 3, 5, 6] target = 5
Output
2
Explanation
5 is already present in the array at index 2.
Example 2
Input
n = 4 nums = [1, 3, 5, 6] target = 2
Output
1
Explanation
2 is not present.
It should be inserted between 1 and 3, so its insertion index is 1.
Constraints
Hints:
Hint 1
Because the array is sorted, you do not need to check every element.
Hint 2
Use Binary Search.
If nums[mid] < target, search the right half.
Author & Technical Reviewer
Technically reviewed by: ExamAdda Technical Review Team
Technical Reviewers, ExamAdda
Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.
Published
Aug 22, 2026
Last updated
Aug 22, 2026
Content Verification Methodology
Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.
Expected Output