

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Program to find index, where we can insert element to keep list sorted 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
- Related Questions & Answers
- Python program to insert an element into sorted list
- Program to find number of sublists we can partition so given list is sorted finally in python
- Program to merge two sorted list to form larger sorted list in Python
- Can we keep Python modules in compiled format?
- Program to find out the index in an array where the largest element is situated in Python
- Program to find squared elements list in sorted order in Python
- Python program to compute the power by Index element in List
- C# program to find the index of an element in a List
- Program to find number of starting point from where we can start travelling in Python
- Where can we find Blue Whales?
- How we can update a Python list element value?
- Can we insert null values in a Java list?
- Program to find buildings from where sea can be visible in Python
- Program to find number of islands, from where we cannot leave in Python
- Program to find largest kth index value of one list in Python
Advertisements