Program to find second largest digit in a string using Python

Suppose we have an alphanumeric string s, we have to find the second largest numerical digit that appears in s, if there is no such string then return -1.

So, if the input is like s = "p84t3ho1n", then the output will be 4 as the digits are [1,3,4,8], so second largest digit is 4.

To solve this, we will follow these steps −

  • lst := a new set

  • for each let in s, do

    • if let is not alphabetic, then

      • insert let as integer in lst

  • if size of lst <= 1, then

    • return -1

  • return the second last element after sorting lst

Let us see the following implementation to get better understanding −


 Live Demo

def solve(s):
   lst = set()
   for let in s:
      if not let.isalpha():
   if len(lst) <= 1:
         return -1
   return sorted(list(lst))[len(lst) - 2]
s = "p84t3ho1n"


"hello", "hlelo"