Skip to content

Commit 2e91e9f

Browse files
committed
Sync LeetCode submission Runtime - 9 ms (12.52%), Memory - 17.9 MB (36.45%)
1 parent 00eb253 commit 2e91e9f

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

0768-partition-labels/README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<p>You are given a string <code>s</code>. We want to partition the string into as many parts as possible so that each letter appears in at most one part. For example, the string <code>&quot;ababcc&quot;</code> can be partitioned into <code>[&quot;abab&quot;, &quot;cc&quot;]</code>, but partitions such as <code>[&quot;aba&quot;, &quot;bcc&quot;]</code> or <code>[&quot;ab&quot;, &quot;ab&quot;, &quot;cc&quot;]</code> are invalid.</p>
2+
3+
<p>Note that the partition is done so that after concatenating all the parts in order, the resultant string should be <code>s</code>.</p>
4+
5+
<p>Return <em>a list of integers representing the size of these parts</em>.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
10+
<pre>
11+
<strong>Input:</strong> s = &quot;ababcbacadefegdehijhklij&quot;
12+
<strong>Output:</strong> [9,7,8]
13+
<strong>Explanation:</strong>
14+
The partition is &quot;ababcbaca&quot;, &quot;defegde&quot;, &quot;hijhklij&quot;.
15+
This is a partition so that each letter appears in at most one part.
16+
A partition like &quot;ababcbacadefegde&quot;, &quot;hijhklij&quot; is incorrect, because it splits s into less parts.
17+
</pre>
18+
19+
<p><strong class="example">Example 2:</strong></p>
20+
21+
<pre>
22+
<strong>Input:</strong> s = &quot;eccbbbbdec&quot;
23+
<strong>Output:</strong> [10]
24+
</pre>
25+
26+
<p>&nbsp;</p>
27+
<p><strong>Constraints:</strong></p>
28+
29+
<ul>
30+
<li><code>1 &lt;= s.length &lt;= 500</code></li>
31+
<li><code>s</code> consists of lowercase English letters.</li>
32+
</ul>

0768-partition-labels/solution.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Approach 1: Two Pointers
2+
3+
# k = no. of unique chars in s
4+
# Time: O(n)
5+
# Space: O(k)
6+
7+
class Solution:
8+
def partitionLabels(self, s: str) -> List[int]:
9+
last_occurrence = [0] * 26
10+
for i, char in enumerate(s):
11+
last_occurrence[ord(char) - ord('a')] = i
12+
13+
partition_end = 0
14+
partition_start = 0
15+
partition_sizes = []
16+
17+
for i, char in enumerate(s):
18+
partition_end = max(partition_end, last_occurrence[ord(char) - ord('a')])
19+
20+
if i == partition_end:
21+
partition_sizes.append(i - partition_start + 1)
22+
partition_start = i + 1
23+
24+
return partition_sizes
25+

0 commit comments

Comments
 (0)