Solvarch
DSA ProblemsProgressPlanRoadmapsReviewCheat SheetsCompaniesSystem DesignCS FundamentalsQuestion Bank
Theme
Problems

Search Insert Position

Easy
binary-searcharray

Given a sorted array of distinct integers nums and a target, return the index of target if found; otherwise return the index where it would be inserted to keep the array sorted. Must run in O(log n).

Input

  • Line 1: space-separated integers (sorted, distinct)
  • Line 2: integer target

Output: the index.

Example 1
Input:
1 3 5 6
5
Output:
2
Example 2
Input:
1 3 5 6
2
Output:
1
Example 3
Input:
1 3 5 6
7
Output:
4

Constraints

  • 1 ≤ nums.length ≤ 10^4
  • Distinct values, sorted ascending.
Watch a video walkthrough

Run your code against the sample tests, or Submit to run the full suite.