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

PythonServer Side ProgrammingProgramming

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]

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

Let us see the following implementation to get better understanding −

Example

 Live Demo

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))

Input

[15, 7, 9, 16, 12, 25]

Output

[0, 15, 7, 7, 7, 7]
raja
Published on 06-Oct-2020 06:18:26
Advertisements