Maximum Length Substring With Two Occurrences - Sliding Window [JS]

Description 

Solution: Sliding Window

Maintain a sliding window where no character has more than 2 occurances.
Keep track of the count of characters in the window.
If a count exceeds 2, move the left pointer up until the count is no longer exceeding 2.
Record and return the maximum window length.

Time Complexity: O(n)
Space Complexity: O(1)

var maximumLengthSubstring = function(s) {
  let n = s.length, count = Array(26).fill(0), ans = 0;
  for (let j = 0, i = 0; j < n; j++) {
    count[s.charCodeAt(j) - 97]++;
    while (count[s.charCodeAt(j) - 97] > 2) {
      count[s.charCodeAt(i) - 97]--;
      i++;
    }
    ans = Math.max(ans, j - i + 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]