Find the time which is palindromic and comes after the given time in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string s that represents a time in the 24 hours format as HH:MM so that HH will be in range 0 to 23 and MM will be in range 0 to 59, We have to find the next closest time which is a palindrome when read as a string. If there is no such string, then return -1.

So, if the input is like "22:22", then the output will be "23:32".

To solve this, we will follow these steps −

  • n := size of s

  • hour_string := substring of s[from index 0 to 2]

  • minute := substring of s[from index 3 to 5] and convert it to integer

  • rev_hour := reverse the hour_string and convert it to number

  • rev_hr_str := reversed of hour_string

  • h := hour_string as integer

  • temp := blank string, res := blank string

  • if h is 23 and minute >= 32, then

    • res := -1

  • otherwise when minute < rev_hour , then

    • if h < 10, then

      • temp := "0"

    • temp := temp concatenate h

    • if rev_hour < 10, then

      • res := res concatenate temp concatenate ":0" concatenate rev_hr_str

    • otherwise,

      • res := res concatenate temp concatenate ":" concatenate rev_hr_str

  • otherwise,

    • h := h + 1

    • rev_hr_str := reversed of h as string

    • rev_hour := reversed of h

    • if h < 10, then

      • temp := "0"

    • temp := temp concatenate h

    • if rev_hour < 10, then

      • res := res concatenate temp concatenate ":0" concatenate rev_hr_str

    • otherwise,

      • res := res concatenate temp concatenate ":" concatenate rev_hr_str

  • return res

Example

Let us see the following implementation to get better understanding −

 Live Demo

def get_next_palindrome_time(s) :
   n = len(s)
   hour_string = s[0 : 2]
   minute = int(s[3 : 5])
   rev_hour = int(hour_string[::-1])
   rev_hr_str = hour_string[::-1]
   h = int(hour_string)
   temp = ""
   res = ""
   if (h == 23 and minute >= 32) :
      res = "-1"
   elif (minute < rev_hour) :
      if (h < 10) :
         temp = "0"
      temp = temp + str(h)
      if (rev_hour < 10) :
         res = res + temp + ":0" + rev_hr_str
      else :
         res = res + temp + ":" + rev_hr_str
   else :
      h += 1
      rev_hr_str = str(h)[::-1]
      rev_hour = int(rev_hr_str)
      if (h < 10) :
         temp = "0"
      temp = temp + str(h)
      if (rev_hour < 10) :
         res = res + temp + ":0" + rev_hr_str
      else :
         res = res + temp + ":" + rev_hr_str
return res
s = "22:22"
print(get_next_palindrome_time(s))

Input

"22:22"

Output

23:32
raja
Published on 27-Aug-2020 12:30:56
Advertisements