Skip to content

763. Partition Labels 👍

  • Time: $O(n)$
  • Space: $O(128) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  vector<int> partitionLabels(string S) {
    vector<int> ans;
    vector<int> rightmost(128);

    for (int i = 0; i < S.length(); ++i)
      rightmost[S[i]] = i;

    int l = 0;  // first index of current running string
    int r = 0;  // right most so far

    for (int i = 0; i < S.length(); ++i) {
      r = max(r, rightmost[S[i]]);
      if (r == i) {
        ans.push_back(i - l + 1);
        l = i + 1;
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public List<Integer> partitionLabels(String S) {
    List<Integer> ans = new ArrayList<>();
    int[] rightmost = new int[128];

    for (int i = 0; i < S.length(); ++i)
      rightmost[S.charAt(i)] = i;

    int l = 0; // first index of current running string
    int r = 0; // right most so far

    for (int i = 0; i < S.length(); ++i) {
      r = Math.max(r, rightmost[S.charAt(i)]);
      if (r == i) {
        ans.add(i - l + 1);
        l = i + 1;
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def partitionLabels(self, S: str) -> List[int]:
    ans = []
    letterToRightmostIndex = {c: i for i, c in enumerate(S)}

    l = 0
    r = 0

    for i, c in enumerate(S):
      r = max(r, letterToRightmostIndex[c])
      if i == r:
        ans.append(r - l + 1)
        l = r + 1

    return ans