Optimal Partition of String - Greedy & Counting [JS]

Description 

Solution: Greedy & Counting

Greedily take the longest substrings possible with unique characters.
Once we come across a duplicate character, start a new substring.
Use an array of size 26 to keep track of the count of each character.

Time Complexity: O(n) 204ms
Space Complexity: O(1) 49.8MB

var partitionString = function(s) {
  let n = s.length, count = Array(26).fill(0), ans = 1;
  for (let i = 0; i < n; i++) {
    if (++count[s.charCodeAt(i) - 97] > 1) {
      ans++;
      count = Array(26).fill(0);
      count[s.charCodeAt(i) - 97] = 1;
    }
  }
  return ans;
};

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]