Program to find size of each partition of a list where each letter appears at most one piece in Python

PythonServer Side ProgrammingProgramming

Suppose we have a lowercase string s, we can partition s into as many pieces as possible such that each letter appears in at most one piece and find the sizes of the partitions as a list.

So, if the input is like s = "momoplaykae", then the output will be [4, 1, 1, 4, 1], as the string is split into ["momo", "p", "l", "ayka", "e"].

To solve this, we will follow these steps −

  • count := a map that contains characters in s and their occurrences

  • out := a new list, stk := an empty stack

  • length := 0

  • for each char in s, do

    • count[char] := count[char] - 1

    • length := length + 1

    • while count[char] is not same as 0 or stk is not empty, do

      • if count[char] is not same as 0, then

        • push char into stk

        • come out from loop

      • if stk is not empty and count[top of stk] is same as 0, then

        • pop from stk

      • otherwise,

        • come out from the loop

    • if stk is empty and count[char] is same as 0, then

      • insert length after out

      • length := 0

  • return out

Example  

Let us see the following implementation to get a better understanding −

 Live Demo

from collections import Counter
class Solution:
   def solve(self, s):
      count = Counter(s)
      out = []
      stk = []
      length = 0
      for char in s:
         count[char] -= 1
         length += 1
         while count[char] != 0 or stk:
            if count[char] != 0:
               stk.append(char)
               break
            if stk and count[stk[-1]] == 0:
               stk.pop()
            else:
               break
            if not stk and count[char] == 0:
               out += [length]
               length = 0
         return out
ob = Solution()
s = "momoplaykae"
print(ob.solve(s))

Input

"momoplaykae"

Output

[4, 1, 1, 4, 1]
raja
Updated on 22-Dec-2020 08:24:27

Advertisements