Program to find index, where we can insert element to keep list sorted in Python

Finding the correct insertion index to maintain sorted order is a common problem that can be efficiently solved using binary search. We need to find the rightmost position where we can insert the target element while keeping the list sorted in ascending order.

Given a sorted list nums and a target value, we want to find the index where the target should be inserted. If the target already exists, we return the largest possible index (after all existing occurrences).

Problem Example

For nums = [1,5,6,6,8,9] and target = 6, the output should be 4. Since 6 already exists at indices 2 and 3, we can insert another 6 at index 4 to get [1,5,6,6,6,8,9].

Algorithm Steps

We use binary search with these steps ?

  • Initialize left = 0 and right = len(nums) - 1
  • Initialize ans = 0 to store the insertion index
  • While left :
    • Calculate mid = (left + right) // 2
    • If target >= nums[mid], move right and update ans = mid + 1
    • Otherwise, move left by setting right = mid - 1
  • Return ans

Implementation

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

# Test with the given example
nums = [1, 5, 6, 6, 8, 9]
target = 6
result = solve(nums, target)
print(f"Insert {target} at index: {result}")

# Test with other cases
test_cases = [
    ([1, 3, 5, 6], 2),  # Insert between elements
    ([1, 3, 5, 6], 7),  # Insert at end
    ([1, 3, 5, 6], 0),  # Insert at beginning
]

for nums_test, target_test in test_cases:
    result = solve(nums_test, target_test)
    print(f"nums={nums_test}, target={target_test} ? index={result}")
Insert 6 at index: 4
nums=[1, 3, 5, 6], target=2 ? index=1
nums=[1, 3, 5, 6], target=7 ? index=4
nums=[1, 3, 5, 6], target=0 ? index=0

How It Works

The algorithm uses binary search to achieve O(log n) time complexity. The key insight is that we want the rightmost insertion position, so whenever target >= nums[mid], we move to the right half and update our answer to mid + 1.

This ensures that if the target already exists, we find the position after all existing occurrences.

Time and Space Complexity

Aspect Complexity Explanation
Time O(log n) Binary search halves search space each iteration
Space O(1) Only uses constant extra space

Conclusion

This binary search approach efficiently finds the correct insertion index in O(log n) time. The key is checking target >= nums[mid] to find the rightmost position, ensuring we handle duplicate values correctly.

---
Updated on: 2026-03-26T17:18:12+05:30

765 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements