Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find size of each partition of a list where each letter appears at most one piece in Python
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"].
Algorithm
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 and break
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 and reset length := 0
return out
Example
Let us see the following implementation to get a better understanding ?
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.append(length)
length = 0
return out
# Test the solution
ob = Solution()
s = "momoplaykae"
print(ob.solve(s))
[4, 1, 1, 4, 1]
How It Works
The algorithm uses a character frequency counter and a stack to track when partitions can be completed. For each character:
Decrement its count and increase current partition length
Use a stack to track characters that still have remaining occurrences
When both the stack is empty and current character count reaches zero, a partition is complete
Add the partition length to results and reset for next partition
Alternative Approach: Using Last Position
A simpler approach tracks the last occurrence of each character ?
def partition_labels(s):
# Find last occurrence of each character
last = {}
for i, char in enumerate(s):
last[char] = i
result = []
start = 0
end = 0
for i, char in enumerate(s):
end = max(end, last[char])
if i == end:
result.append(end - start + 1)
start = i + 1
return result
# Test the alternative approach
s = "momoplaykae"
print(partition_labels(s))
[4, 1, 1, 4, 1]
Conclusion
Both approaches solve the partition problem effectively. The stack-based method tracks active characters, while the last-position approach extends partitions until all characters are complete. The second method is more intuitive and efficient.
---