Problem
The variance of a string is defined as the largest difference between the number of occurrences of any 2 characters present in the string. Note the two characters may or may not be the same.
Given a string s consisting of lowercase English letters only, return the largest variance possible among all substrings of s.
A substring is a contiguous sequence of characters within a string.
Examples
Example 1:
| |
Example 2:
| |
Solution
Method 1 - Kadane
Here is the approach:
- Character Pair Consideration: Since there are only 26 lowercase English letters, we can focus on pairs of these characters. Let’s denote the variables
aandbas the pair of characters we are considering. For every possible character paira(with minimum frequency) andb(with maximum frequency), we aim to find the substring with the maximum difference between the frequencies ofaandb. This can be achieved using Kadane’s algorithm. - Kadane’s Algorithm Adaptation: For each character pair, treat
aas-1,bas+1, and other characters as0. This transforms the problem into finding the maximum subarray sum in a modified array. Ensure that the subarray contains at least one occurrence ofa. - Track Maximum Variance: Iterate through all character pairs, compute the variance for each pair using the adapted Kadane’s algorithm, and track the maximum variance found.
Here are the steps:
- Iterate Through Character Pairs:
- Use a set to obtain all unique characters in the string.
- Iterate through each pair of unique characters
aandb.
- Adapt Kadane’s Algorithm:
- For each character pair:
- Initialize
current_varianceto track the current variance. - Use flags
has_bandinitial_has_bto ensure the subarray containsband manages resets. - Iterate through the string, treating occurrences of
aas-1andbas+1.
- Initialize
- For each character pair:
- Update Maximum Variance:
- After processing each pair, update the
max_varianceif a higher variance is found.
- After processing each pair, update the
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n),- Character Pair Iteration:
O(26 * 26) = O(1)because there are at most 26 lowercase English letters. - String Iteration: For each character pair, the algorithm iterates through the string of length
n. - Overall Time Complexity:
O(n)
- Character Pair Iteration:
- 🧺 Space complexity:
O(1)