Skip to content

Commit 0e340e3

Browse files
committed
Add problem 763 - Partition Labels
1 parent 840ee0c commit 0e340e3

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

problems/greedy/partition_labels.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from typing import List
2+
3+
4+
class PartitionLabels:
5+
@staticmethod
6+
def partitionLabels(s: str) -> List[int]:
7+
# List to store the sizes of partitions
8+
sizes = []
9+
# Special case
10+
if not s:
11+
return sizes
12+
13+
# Array to store last positions of characters
14+
last_position = [0] * 26
15+
for i in range(len(s)):
16+
last_position[ord(s[i]) - ord('a')] = i
17+
18+
# Pointers for the window
19+
left, right = 0, 0
20+
# Traverse through the string again
21+
for i in range(len(s)):
22+
right = max(right, last_position[ord(s[i]) - ord('a')])
23+
if right == i:
24+
sizes.append(right - left + 1)
25+
left = i + 1
26+
27+
return sizes

tests/greedy/partition_labels_test.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import unittest
2+
3+
from problems.greedy.partition_labels import PartitionLabels
4+
5+
6+
class TestPartitionLabels(unittest.TestCase):
7+
8+
def setUp(self):
9+
self.partition_labels = PartitionLabels()
10+
11+
def test_partition_labels(self):
12+
# Test null input
13+
self.assertEqual(self.partition_labels.partitionLabels(None), [])
14+
15+
# Test empty string
16+
self.assertEqual(self.partition_labels.partitionLabels(""), [])
17+
18+
# Test string with all unique characters
19+
self.assertEqual(self.partition_labels.partitionLabels("abcd"), [1, 1, 1, 1])
20+
21+
# Test string with all same characters
22+
self.assertEqual(self.partition_labels.partitionLabels("aaaa"), [4])
23+
24+
# Test string with multiple partitions
25+
self.assertEqual(self.partition_labels.partitionLabels("ababcbacadefegdehijhklij"), [9, 7, 8])
26+
27+
# Test string with overlapping partitions
28+
self.assertEqual(self.partition_labels.partitionLabels("eababcbaca"), [1, 9])
29+
30+
def test_edge_cases(self):
31+
# Test single character string
32+
self.assertEqual(self.partition_labels.partitionLabels("a"), [1])
33+
34+
# Test string with repeating characters
35+
self.assertEqual(self.partition_labels.partitionLabels("abacaba"), [7])
36+
37+
38+
if __name__ == '__main__':
39+
unittest.main()

0 commit comments

Comments
 (0)