#763

Partition Labels

Medium
Hash TableTwo PointersStringGreedyHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a greedy approach with a hashmap to track the last occurrence of each character. This allows us to expand our partition until we have included all instances of the characters in the current partition.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a hashmap to store the last index of each character in the string.
  2. 2Step 2: Initialize variables to track the current partition's end index and the start index.
  3. 3Step 3: Iterate through the string, updating the end index to the maximum last index of the characters seen so far.
  4. 4Step 4: When the current index matches the end index, record the size of the partition and update the start index.
solution.py13 lines
1# Full working Python code
2from collections import defaultdict
3
4def partition_labels(s):
5    last = {c: i for i, c in enumerate(s)}
6    partitions = []
7    start, end = 0, 0
8    for i, c in enumerate(s):
9        end = max(end, last[c])
10        if i == end:
11            partitions.append(end - start + 1)
12            start = i + 1
13    return partitions

Complexity note: This complexity is linear because we make a single pass to record the last indices and another pass to determine the partitions, resulting in O(n) time overall.

  • 1Understanding the last occurrence of characters is crucial for determining valid partitions.
  • 2Greedy approaches can often lead to optimal solutions by making local optimal choices.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.