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(26);

    for (int i = 0; i < s.length(); ++i)
      rightmost[s[i] - 'a'] = i;

    int l = 0;  // the leftmost index of the current running string
    int r = 0;  // the rightmost index of the current running string

    for (int i = 0; i < s.length(); ++i) {
      r = max(r, rightmost[s[i] - 'a']);
      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[26];

    for (int i = 0; i < s.length(); ++i)
      rightmost[s.charAt(i) - 'a'] = i;

    int l = 0; // the leftmost index of the current running string
    int r = 0; // the rightmost index of the current running string

    for (int i = 0; i < s.length(); ++i) {
      r = Math.max(r, rightmost[s.charAt(i) - 'a']);
      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  # the leftmost index of the current running string
    r = 0  # the rightmost index of the current running string

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

    return ans