Program to replace each element by smallest term at left side in Python

Suppose we have a list of numbers called nums, we have to replace every nums[i] with the smallest element left of i. We have to replace nums[0] with 0.

So, if the input is like [15, 7, 9, 16, 12, 25], then the output will be [0, 15, 7, 7, 7, 7].

Algorithm

To solve this, we will follow these steps ?

  • If nums is empty, then
    • return a new list
  • j := nums[0]
  • nums[0] := 0
  • For i in range 1 to size of nums - 1, do
    • k := nums[i]
    • nums[i] := j
    • j := minimum of j, k
  • Return nums

Example

Let us see the following implementation to get better understanding ?

class Solution:
    def solve(self, nums):
        if not nums:
            return []
        j = nums[0]
        nums[0] = 0
        for i in range(1, len(nums)):
            k = nums[i]
            nums[i] = j
            j = min(j, k)
        return nums

ob = Solution()
nums = [15, 7, 9, 16, 12, 25]
print(ob.solve(nums))
[0, 15, 7, 7, 7, 7]

How It Works

The algorithm works by maintaining a running minimum of all elements seen so far. For each position, we replace the current element with the smallest element found to its left, then update our running minimum to include the current element for future iterations.

Alternative Approach

Here's a more readable version using a simple function ?

def replace_with_left_minimum(nums):
    if not nums:
        return []
    
    result = [0]  # First element is always 0
    min_so_far = nums[0]
    
    for i in range(1, len(nums)):
        result.append(min_so_far)
        min_so_far = min(min_so_far, nums[i])
    
    return result

nums = [15, 7, 9, 16, 12, 25]
print(replace_with_left_minimum(nums))
[0, 15, 7, 7, 7, 7]

Conclusion

This algorithm efficiently replaces each element with the smallest element to its left in O(n) time complexity. The key insight is maintaining a running minimum while iterating through the array once.

Updated on: 2026-03-25T10:51:05+05:30

305 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements