Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Kth Missing Positive Number in a Sorted Array
Next article icon

Search insert position of K in a sorted array

Last Updated : 03 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a 0-based sorted array arr[] consisting of n distinct integers and an integer k, the task is to find the index of k, if it is present in the array arr[]. Otherwise, find the index where k must be inserted to keep the array sorted.

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: Since 2 is not present in the array but can be inserted at index 1 to make the array sorted.

Table of Content

  • [Brute Force Approach] Traverse and Find - O(n) Time and O(1) Space
  • [Expected Approach] Using Binary Search - O(logn) Time and O(1) Space
  • [Alternate Approach] Using Binary Search - O(logn) Time and O(1) Space

[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.

C++
#include <bits/stdc++.h> using namespace std;  // Function to find the index of k or the position  // where k should be inserted in sorted order int searchInsertK(vector<int> arr, int k) {        for(int i = 0; i < arr.size(); i++) {            // If k is found or needs to be inserted          // before arr[i]         if(arr[i] >= k) {               return i;           }       }        // If k is greater than all elements,     // insert at the end     return arr.size();   }    int main() {           vector<int> arr = {1, 3, 5, 6};       int k = 5;        cout << searchInsertK(arr, k) << endl;            return 0;   }   
Java
import java.util.*;  class GfG {      // Function to find the index of k or the position      // where k should be inserted in sorted order     static int searchInsertK(int arr[], int k) {            for(int i = 0; i < arr.length; i++) {                // If k is found or needs to be inserted              // before arr[i]             if(arr[i] >= k) {                   return i;               }           }            // If k is greater than all elements,         // insert at the end         return arr.length;       }        public static void main(String args[]) {            int arr[] = {1, 3, 5, 6};           int k = 5;            System.out.println(searchInsertK(arr, k));        }   }   
Python
# Function to find the index of k or the position  # where k should be inserted in sorted order def searchInsertK(arr, k):        for i in range(len(arr)):            # If k is found or needs to be inserted          # before arr[i]         if arr[i] >= k:               return i        # If k is greater than all elements,     # insert at the end     return len(arr)    if __name__ == "__main__":        arr = [1, 3, 5, 6]       k = 5        print(searchInsertK(arr, k))   
C#
using System;  class GfG {      // Function to find the index of k or the position      // where k should be inserted in sorted order     static int searchInsertK(int[] arr, int k) {            for(int i = 0; i < arr.Length; i++) {                // If k is found or needs to be inserted              // before arr[i]             if(arr[i] >= k) {                   return i;               }           }            // If k is greater than all elements,         // insert at the end         return arr.Length;       }        public static void Main() {            int[] arr = {1, 3, 5, 6};           int k = 5;            Console.WriteLine(searchInsertK(arr, k));        }   }   
JavaScript
// Function to find the index of k or the position  // where k should be inserted in sorted order function searchInsertK(arr, k) {        for(let i = 0; i < arr.length; i++) {            // If k is found or needs to be inserted          // before arr[i]         if(arr[i] >= k) {               return i;           }       }        // If k is greater than all elements,     // insert at the end     return arr.length;   }    let arr = [1, 3, 5, 6];   let k = 5;    console.log(searchInsertK(arr, k));   

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, which reduces time complexity from O(n) to O(log n).

  • 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.
C++
#include <bits/stdc++.h> using namespace std;  // Function to find the index of k or the position  // where k should be inserted in sorted order int searchInsertK(vector<int> arr, int k) {        int left = 0, right = arr.size() - 1;        while(left <= right) {            int mid = left + (right - left) / 2;            // If k is found at mid         if(arr[mid] == k) {               return mid;           }            // If k is smaller, search in left half         else if(arr[mid] > k) {               right = mid - 1;           }            // If k is larger, search in right half         else {               left = mid + 1;           }       }        // If k is not found, return insert position     return left;   }    int main() {           vector<int> arr = {1, 3, 5, 6};       int k = 5;        cout << searchInsertK(arr, k) << endl;            return 0;   }   
Java
import java.util.*;  class GfG {      // Function to find the index of k or the position      // where k should be inserted in sorted order     static int searchInsertK(int arr[], int k) {            int left = 0, right = arr.length - 1;            while(left <= right) {                int mid = left + (right - left) / 2;                // If k is found at mid             if(arr[mid] == k) {                   return mid;               }                // If k is smaller, search in left half             else if(arr[mid] > k) {                   right = mid - 1;               }                // If k is larger, search in right half             else {                   left = mid + 1;               }           }            // If k is not found, return insert position         return left;       }        public static void main(String args[]) {            int arr[] = {1, 3, 5, 6};           int k = 5;            System.out.println(searchInsertK(arr, k));        }   }   
Python
# Function to find the index of k or the position  # where k should be inserted in sorted order def searchInsertK(arr, k):        left, right = 0, len(arr) - 1        while left <= right:            mid = left + (right - left) // 2            # If k is found at mid         if arr[mid] == k:               return mid            # If k is smaller, search in left half         elif arr[mid] > k:               right = mid - 1            # If k is larger, search in right half         else:               left = mid + 1        # If k is not found, return insert position     return left    if __name__ == "__main__":        arr = [1, 3, 5, 6]       k = 5        print(searchInsertK(arr, k))   
C#
using System;  class GfG {      // Function to find the index of k or the position      // where k should be inserted in sorted order     static int searchInsertK(int[] arr, int k) {            int left = 0, right = arr.Length - 1;            while(left <= right) {                int mid = left + (right - left) / 2;                // If k is found at mid             if(arr[mid] == k) {                   return mid;               }                // If k is smaller, search in left half             else if(arr[mid] > k) {                   right = mid - 1;               }                // If k is larger, search in right half             else {                   left = mid + 1;               }           }            // If k is not found, return insert position         return left;       }        public static void Main() {            int[] arr = {1, 3, 5, 6};           int k = 5;            Console.WriteLine(searchInsertK(arr, k));        }   }   
JavaScript
// Function to find the index of k or the position  // where k should be inserted in sorted order function searchInsertK(arr, k) {        let left = 0, right = arr.length - 1;        while(left <= right) {            let mid = left + Math.floor((right - left) / 2);            // If k is found at mid         if(arr[mid] === k) {               return mid;           }            // If k is smaller, search in left half         else if(arr[mid] > k) {               right = mid - 1;           }            // If k is larger, search in right half         else {               left = mid + 1;           }       }        // If k is not found, return insert position     return left;   }    let arr = [1, 3, 5, 6];   let k = 5;    console.log(searchInsertK(arr, k));   

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.

C++
// C++ code to search insert position // of K in array using Binary Search #include <bits/stdc++.h> using namespace std;  // Function to find the index of k or the position  // where k should be inserted in sorted order int searchInsertK(vector<int> arr, int k) {        int left = 0, right = arr.size() - 1;        while(left < right) {            int mid = left + (right - left) / 2;            // If arr[mid] is less than k, move to the right part         if(arr[mid] < k) {               left = mid + 1;           }                    // Otherwise, move to the left part         else {               right = mid;           }       }        // Found place: arr[left] is the first element >= k     return (arr[left] < k) ? left + 1 : left;   }    int main() {           vector<int> arr = {1, 3, 5, 6};       int k = 5;        cout << searchInsertK(arr, k) << endl;            return 0;   }   
Java
// Java code to search insert position // of K in array using Binary Search import java.util.*;  class GfG {      // Function to find the index of k or the position      // where k should be inserted in sorted order     static int searchInsertK(int arr[], int k) {            int left = 0, right = arr.length - 1;            while(left < right) {                int mid = left + (right - left) / 2;                // If arr[mid] is less than k, move to the right part             if(arr[mid] < k) {                   left = mid + 1;               }                // Otherwise, move to the left part             else {                   right = mid;               }           }            // Found place: arr[left] is the first element >= k         return (arr[left] < k) ? left + 1 : left;       }        public static void main(String args[]) {            int arr[] = {1, 3, 5, 6};           int k = 5;            System.out.println(searchInsertK(arr, k));        }   }   
Python
# Python code to search insert position # of K in array using Binary Search  # Function to find the index of k or the position  # where k should be inserted in sorted order def searchInsertK(arr, k):        left, right = 0, len(arr) - 1        while left < right:            mid = left + (right - left) // 2            # If arr[mid] is less than k, move to the right part         if arr[mid] < k:               left = mid + 1            # Otherwise, move to the left part         else:               right = mid        # Found place: arr[left] is the first element >= k     return left + 1 if arr[left] < k else left    if __name__ == "__main__":        arr = [1, 3, 5, 6]       k = 5        print(searchInsertK(arr, k))   
C#
// C# code to search insert position // of K in array using Binary Search using System;  class GfG {      // Function to find the index of k or the position      // where k should be inserted in sorted order     static int searchInsertK(int[] arr, int k) {            int left = 0, right = arr.Length - 1;            while(left < right) {                int mid = left + (right - left) / 2;                // If arr[mid] is less than k, move to the right part             if(arr[mid] < k) {                   left = mid + 1;               }                // Otherwise, move to the left part             else {                   right = mid;               }           }            // Found place: arr[left] is the first element >= k         return (arr[left] < k) ? left + 1 : left;       }        public static void Main() {            int[] arr = {1, 3, 5, 6};           int k = 5;            Console.WriteLine(searchInsertK(arr, k));        }   } 
JavaScript
// JavaScript code to search insert position // of K in array using Binary Search  // Function to find the index of k or the position  // where k should be inserted in sorted order function searchInsertK(arr, k) {        let left = 0, right = arr.length - 1;        while (left < right) {            let mid = left + Math.floor((right - left) / 2);            // If arr[mid] is less than k, move to the right part         if (arr[mid] < k) {               left = mid + 1;           }            // Otherwise, move to the left part         else {               right = mid;           }       }        // Found place: arr[left] is the first element >= k     return arr[left] < k ? left + 1 : left;   }    // Driver code const arr = [1, 3, 5, 6];   const k = 5;    console.log(searchInsertK(arr, k));   

Output
2 



Next Article
Kth Missing Positive Number in a Sorted Array

D

deepanshu_rustagi
Improve
Article Tags :
  • Searching
  • DSA
  • Arrays
  • Binary Search
  • array-rearrange
  • array-traversal-question
Practice Tags :
  • Arrays
  • Binary Search
  • Searching

Similar Reads

  • Search, Insert, and Delete in an Sorted Array | Array Operations
    How to Search in a Sorted Array?In a sorted array, the search operation can be performed by using binary search. Below is the implementation of the above approach: [GFGTABS] C++ // C++ program to implement binary search in sorted array #include <bits/stdc++.h> using namespace std; int binarySe
    15+ min read
  • Search, Insert, and Delete in an Unsorted Array | Array Operations
    In this post, a program to search, insert, and delete operations in an unsorted array is discussed. Search Operation:In an unsorted array, the search operation can be performed by linear traversal from the first element to the last element. Coding implementation of the search operation:[GFGTABS] C++
    15+ min read
  • Front and Back Search in unsorted array
    Given an unsorted array of integers and an element x, find if x is present in array using Front and Back search. Examples : Input : arr[] = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170} x = 110; Output : Yes Input : arr[] = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170} x = 175; Output : No A simple so
    5 min read
  • Kth Missing Positive Number in a Sorted Array
    Given a sorted array of distinct positive integers arr[] and integer k, the task is to find the kth positive number that is missing from arr[]. Examples : Input: arr[] = [2, 3, 4, 7, 11], k = 5Output: 9Explanation: Missing are 1, 5, 6, 8, 9, 10, ... and 5th missing number is 9. Input: arr[] = [1, 2,
    10 min read
  • Search an element in a reverse sorted array
    Given an array arr[] sorted in decreasing order, and an integer X, the task is to check if X is present in the given array or not. If X is present in the array, print its index ( 0-based indexing). Otherwise, print -1. Examples: Input: arr[] = {5, 4, 3, 2, 1}, X = 4Output: 1Explanation: Element X (=
    8 min read
  • Sort a nearly sorted (or K sorted) array
    Given an array arr[] and a number k . The array is sorted in a way that every element is at max k distance away from it sorted position. It means if we completely sort the array, then the index of the element can go from i - k to i + k where i is index in the given array. Our task is to completely s
    6 min read
  • Find position of an element in a sorted array of infinite numbers
    Given a sorted array arr[] of infinite numbers. The task is to search for an element k in the array. Examples: Input: arr[] = [3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170], k = 10Output: 4Explanation: 10 is at index 4 in array. Input: arr[] = [2, 5, 7, 9], k = 3Output: -1Explanation: 3 is not presen
    15+ min read
  • Rotation Count in a Rotated Sorted array
    Given an array arr[] having distinct numbers sorted in increasing order and the array has been right rotated (i.e, the last element will be cyclically shifted to the starting position of the array) k number of times, the task is to find the value of k. Examples: Input: arr[] = {15, 18, 2, 3, 6, 12}O
    13 min read
  • k-th missing element in an unsorted array
    Given an unsorted sequence a[], the task is to find the K-th missing contiguous element in the increasing sequence of the array elements i.e. consider the array in sorted order and find the kth missing number. If no k-th missing element is there output -1. Note: Only elements exists in the range of
    6 min read
  • Create a Sorted Array Using Binary Search
    Given an array, the task is to create a new sorted array in ascending order from the elements of the given array.Examples: Input : arr[] = {2, 5, 4, 9, 8} Output : 2 4 5 8 9 Input : arr[] = {10, 45, 98, 35, 45} Output : 10 35 45 45 98 The above problem can be solved efficiently using Binary Search.
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences