Partition Labels — LeetCode 763 Python Solution
MediumGreedyHash TableTwo PointersString
- Problem
- #763
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Example
- Input
- s = "ababcbacadefegdehijhklij"
- Output
- [9,7,8]
- Explanation
- The partition is "ababcbaca", "defegde", "hijhklij".
Python solution
Python
class Solution:
def partitionLabels(self, s: str) -> List[int]:
last = {c: i for i, c in enumerate(s)}
mx = j = 0
ans = []
for i, c in enumerate(s):
mx = max(mx, last[c])
if mx == i:
ans.append(i - j + 1)
j = i + 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 763. Partition Labels is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
On a study list
This problem is on NeetCode 150.
Frequently asked questions
- How hard is LeetCode 763. Partition Labels?
- LeetCode 763. Partition Labels is rated Medium on LeetCode.
- What is the time complexity of LeetCode 763. Partition Labels?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 763. Partition Labels?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 763. Partition Labels cover?
- LeetCode 763. Partition Labels is tagged Greedy, Hash Table, Two Pointers and String on LeetCode.