Decoded String at Index in Python

PythonServer Side ProgrammingProgramming

Suppose one encoded string S is given. We have to find and write the decoded string to a tape, here the encoded string is read one character at a time and the following steps are performed −

  • If the character read is a letter, that letter is simply written onto the tape.
  • If the character read is a digit, the entire current tape is repeatedly written digit – 1 more times in total.

Now if some encoded string S, and an index K is given, find and return the K-th letter (starting indices from 1) in the decoded string.

So if the string is “hello2World3” and k = 10, then the output will be “o”. This is because the decoded string will be “hellohelloWorldhellohelloWorldhellohelloWorld”, so 10th character is “o”.

To solve this, we will follow these steps −

  • size := 0
  • for i in string s
    • if i is a numeric character, then size := size * integer from of i, otherwise size := size + 1
  • for i in range length of s – 1 down to 0
    • k := k mod size
    • if s[i] is numeric and k = 0, then return s[i]
    • if s[i] is numeric, then decrease size by 1, otherwise size := size / integer of s[i]
  • return empty string

Let us see the following implementation to get better understanding −


 Live Demo

class Solution(object):
   def decodeAtIndex(self, s, k):
      :type S: str
      :type K: int
      :rtype: str
      size = 0
      for i in s:
         if i.isdigit():
            size *= int(i)
            size += 1
      for i in range(len(s) - 1, -1, -1):
         k %= size
         if s[i].isalpha() and k == 0:
            return s[i]
         if s[i].isalpha():
            size -=1
            size /= int(s[i])
      return ""
ob = Solution()
print(ob.decodeAtIndex("hello2World3", 10))


ob.decodeAtIndex("hello2World3", 10)


Updated on 30-Apr-2020 06:09:03