Skip to content

Instantly share code, notes, and snippets.

@kuntalchandra
Created September 4, 2020 11:42
Show Gist options
  • Select an option

  • Save kuntalchandra/e32fd118fc31d6eac89ebaae762e0dfa to your computer and use it in GitHub Desktop.

Select an option

Save kuntalchandra/e32fd118fc31d6eac89ebaae762e0dfa to your computer and use it in GitHub Desktop.
Partition Labels
"""
A string S of lowercase English letters is given. We want to partition this string into as many parts as possible so
that each letter appears in at most one part, and return a list of integers representing the size of these parts.
Example 1:
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
"""
class Solution:
def partitionLabels(self, S: str) -> List[int]:
last = {c: i for i, c in enumerate(S)}
left = right = 0
res = []
for i, c in enumerate(S):
right = max(right, last[c])
if i == right:
res.append(right - left + 1)
left = i + 1
return res
@kuntalchandra

Copy link
Copy Markdown
Author

Selection_001

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment