
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Index to Insert Element in Sorted List in Python
Suppose we have a list of numbers called nums, they are sorted in ascending order, we also have another number target, we have to find the index where target should be inserted to keep nums sorted. If target already present in nums, then return the largest index where target can be inserted. We have to solve this without using library functions and solve it in O(log n) time.
So, if the input is like nums = [1,5,6,6,8,9] target = 6, then the output will be 4, because 6 is already there, so to insert it, the largest possible index is 4, so the array will be like [1,5,6,6,6,8,9].
To solve this, we will follow these steps −
- left := 0
- right :=
- size of nums - 1
- ans := 0
- while left <= right, do
- mid := floor of (left + right) / 2
- if target >= nums[mid], then
- ans := mid + 1
- left := mid + 1
- otherwise,
- right := mid - 1
- return ans
Example
Let us see the following implementation to get better understanding −
def solve(nums, target): left, right = 0, len(nums) - 1 ans = 0 while left <= right: mid = (left + right) // 2 if target >= nums[mid]: ans = mid + 1 left = mid + 1 else: right = mid - 1 return ans nums = [1,5,6,6,8,9] target = 6 print(solve(nums, target))
Input
[1,5,6,6,8,9], 6
Output
4
Advertisements