Maximum Number of Equal Length Runs Problem
#3773
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3773.
You are given a string s consisting of lowercase English letters.
A run in s is a substring of equal letters that cannot be extended further. For example, the runs in "hello" are "h", "e", "ll", and "o".
You can select runs that have the same length in s.
Return an integer denoting the maximum number of runs you can select in s.
Example 1:
Input: s = "hello"
Output: 3
Explanation:
The runs in s are "h", "e", "ll", and "o". You can select "h", "e", and "o" because they have the same length 1.
Example 2:
Input: s = "aaabaaa"
Output: 2
Explanation:
The runs in s are "aaa", "b", and "aaa". You can select "aaa" and "aaa" because they have the same length 3.
Constraints:
1 <= s.length <= 10^5sconsists of lowercase English letters only.
Solution
Approach: Hash Table
Scan the string and split it into runs of equal characters. Count in a hash table how many runs have each length. The answer is the largest count.
Complexity: time O(n), space O(n), where n is the length of s.
from collections import Counter
from itertools import groupby
class Solution:
def maxSameLengthRuns(self, s: str) -> int:
cnt = Counter()
for _, g in groupby(s):
cnt[len(list(g))] += 1
return max(cnt.values())