CodeArchon

mediumGreedyAmazon

Letter Zone Splitter

A labeler splits a text into the maximum number of contiguous zones so that each character appears in only one zone.

Partition the string into as many parts as possible so that each letter appears in at most one part; return the sizes.

Choose approach

a
0
i
b
1
a
2
b
3
c
4
b
5
a
6
c
7
a
8
end
d
9
e
10
f
11
e
12
g
13
d
14
e
15
h
16
i
17
j
18
h
19
k
20
l
21
i
22
j
23
Setzones
empty
1/24
Narrationstep 1 of 24

i=0: end extends to 8.

1def partitionLabels(s):
2 last = {c: i for i, c in enumerate(s)}
3 out, start, end = [], 0, 0
4 for i, c in enumerate(s):
5 end = max(end, last[c])
6 if i == end:
7 out.append(end - start + 1); start = i + 1
8 return out
Variables
i=0
end=8
start=0
zones=

How to think about it

  1. All letters' last-seen indices define zone bounds.
  2. Close zone when i matches the running max.

Edge cases to catch in interview

  • Single char -> [1].
  • All same char -> [length].

Examples

Example 1[10]
{"s":"eccbbbbdec","values":["e","c","c","b","b","b","b","d","e","c"]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed