
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- 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
- Python program to compute the power by Index element in List
- Program to merge two sorted list to form larger sorted list in Python
- Program to find squared elements list in sorted order in Python
- Python Program to insert an element into the array at the specified index
- Program to find out the index in an array where the largest element is situated in Python
- 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
- Program to check we can update a list index by its current sum to reach target or not in python
- Program to insert new element into a linked list before the given position in Python
- Program to find largest kth index value of one list in Python
- Can we keep Python modules in compiled format?
- Program to find the number of unique integers in a sorted list in Python
- Python – Negative index of Element in List

Advertisements