VOOZH about

URL: https://www.geeksforgeeks.org/dsa/search-insert-position-of-k-in-a-sorted-array/

⇱ Search insert position of K in a sorted array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Search insert position of K in a sorted array

Last Updated : 1 Aug, 2025

Given a 0 based sorted array arr[] of distinct integers and an integer k, find the index of k if it is present. If not, return the index where k should be inserted to maintain the sorted order.

Examples:

Input: arr[] = [1, 3, 5, 6], k = 5
Output: 2
Explanation: Since 5 is found at index 2 as arr[2] = 5, the output is 2.

Input: arr[] = [1, 3, 5, 6], k = 2
Output: 1
Explanation: The element 2 is not present in the array, but inserting it at index 1 will maintain the sorted order.

[Naive Approach] Traverse and Find - O(n) Time and O(1) Space

The idea is to iterate through the array and find the first position where k is less than or equal to arr[i] (current element). We traverse the array linearly, checking each element to determine if k should be placed at or before it. If k is larger than all elements, it is inserted at the end, returning the array size.


Output
2

[Expected Approach] Using Binary Search - O(log n) Time and O(1) Space

The idea is to use binary search, instead of scanning the entire array linearly. The thought process begins by recognizing that a sorted array allows us to use binary search.

=> We use two pointers (left and right) to narrow down the search space by comparing k with the middle element, halving the problem at each step.
=> If k is found, return its index; otherwise, the left pointer will naturally point to the correct insertion position when the search ends.


Output
2

[Alternate Approach] Using Binary Search - O(log n) Time and O(1) Space

The idea is to refine the traditional binary search by ensuring that we always land on the first position where the target could be inserted. Unlike the previous approach, here we eliminate elements from the right by setting right = mid instead of right = mid - 1, ensuring left never skips a potential insert position.

This guarantees that when the loop ends, left directly points to the first index where k should be placed. The final check ensures that if arr[left] is still smaller than k, we return left + 1, otherwise, we return left.


Output
2
Comment