Sunday, July 9th
Substrings and letter counts are the topics for the LeetCode problem for today
Given a string, we are tasked with finding a substring that has the largest "variance." Here, variance is defined as the difference in letter counts between any 2 letters, e.g.:
With input string s = "aababbb" , the substring "babbb" has a variance of of 3, because 4 b's and 1a
I opened with brute force, finding every possible substring with 2 for loops, storing in a map to avoid duplicates, calculating variances, then returning the max. The first 2 test cases were correctly solved, affirming I understood the problem. However, time was exceeded on a string of 421 characters. Considering the input string could be up to 10^4 characters, a more efficient solution was needed.
An alternative is to count the frequencies of each letter, then consider all possible pairs of letters using a variation of Kidane's algorithm, which can find the maximum subarray sum in an array of integers.
First, a nifty way to calculate character frequencies:
vector<int> counter(26, 0);
Comments
Post a Comment