Solution For Substring With Largest Variance
The Substring With Largest Variance problem on LeetCode is a medium-level question that asks you to find the substring of a given string that has the largest variance of its characters.
The problem statement is as follows:
Given a string s containing n characters, find the substring of s that has the largest variance of its characters. The variance of a substring is defined as the difference between the maximum and minimum ASCII value of its characters.
Example:
Input: “abcdefg”
Output: 103
Explanation: The substring with the largest variance is “g” which has a variance of 103 (the ASCII value of ‘g’ is 103, and the ASCII value of ‘a’ is 97).
To solve this problem, we can use a sliding window technique. We will keep track of the minimum and maximum ASCII values of the characters in the current window and calculate the variance. We will move the window to the right one character at a time and update the minimum and maximum values accordingly.
Here is the step-by-step solution:
- Initialize variables
We start by initializing variables that we will use in the solution:
max_var
– the maximum variance that we will findstart
– the starting index of the substring with the largest variancemin_val
– the minimum ASCII value of the characters in the current windowmax_val
– the maximum ASCII value of the characters in the current window
We will set the initial values of max_var
and start
to 0.
- Start the sliding window
We will start the sliding window from the beginning of the string s. We will use a for loop to iterate through the string s.
For each iteration, we will do the following:
- Update the minimum and maximum values if necessary
- Calculate the variance of the current window
- Update
max_var
andstart
if the current variance is larger than the previous maximum variance.
Here is the code:
“`
max_var = 0
start = 0
min_val = ord(s[0])
max_val = ord(s[0])
for i in range(1, len(s)):
# update minimum and maximum values
if ord(s[i]) < min_val:
min_val = ord(s[i])
if ord(s[i]) > max_val:
max_val = ord(s[i])
# calculate variance
variance = max_val - min_val
# update max_var and start
if variance > max_var:
max_var = variance
start = i - (max_val == ord(s[i])) # the start index should be updated according to the maximum ASCII value
return max_var
“`
- Return the answer
After the for loop finishes, we return the max_var
variable.
This solution has a time complexity of O(n), where n is the length of the input string s, since we iterate through the string once. The space complexity is O(1), since we use only a constant amount of extra space to store the variables.
Step by Step Implementation For Substring With Largest Variance
class Solution { public int findSubstringInWraproundString(String p) { // keep track of the longest substring ending at each position int[] longest = new int[26]; // keep track of the length of the current substring int currLength = 0; for (int i = 0; i < p.length(); i++) { // if the current character is the next character in alphabetical order if (i > 0 && (p.charAt(i) - p.charAt(i - 1) == 1 || (p.charAt(i - 1) - p.charAt(i) == 25))) { currLength++; } // otherwise, the current substring ends else { currLength = 1; } // update the longest substring ending at this position // to be the maximum of the previous longest substring // ending at this position and the current substring length longest[p.charAt(i) - 'a'] = Math.max(longest[p.charAt(i) - 'a'], currLength); } // the total number of unique substring is the sum of the longest // substring at each position int sum = 0; for (int num : longest) { sum += num; } return sum; } }
Given a string s of lowercase letters, return the substring with the largest variance in letter frequencies. If there is more than one substring with the same variance, return the substring that occurs earliest in the string. def largest_variance_substring(s): # keep track of the maximum variance and the corresponding substring max_variance = 0 max_substring = "" # iterate through all possible substrings of s for i in range(len(s)): for j in range(i+1, len(s)+1): # get the current substring substring = s[i:j] # calculate the variance of the letter frequencies in the current substring variance = 0 for letter in set(substring): letter_frequency = substring.count(letter) / len(substring) variance += (letter_frequency - 0.5) ** 2 # update the maximum variance and corresponding substring if necessary if variance > max_variance: max_variance = variance max_substring = substring return max_substring
var largestVariance = function(s) { // create a hashmap to store the variance of each substring // key is the substring, value is the variance const map = {}; // create a variable to store the length of the longest substring let maxLength = 0; // create a variable to store the longest substring with the largest variance let maxString = ""; // iterate through the string for (let i = 0; i < s.length; i++) { // create a variable to store the current substring let currentString = ""; // create a variable to store the sum of the current substring let sum = 0; // create a variable to store the variance of the current substring let variance = 0; // iterate through the string again, starting at the current index for (let j = i; j < s.length; j++) { // add the current character to the current substring currentString += s[j]; // add the current character to the sum sum += s[j]; // calculate the length of the current substring const length = currentString.length; // calculate the mean of the current substring const mean = sum / length; // iterate through the current substring for (let k = 0; k < currentString.length; k++) { // calculate the variance of the current substring variance += Math.pow((currentString[k] - mean), 2); } // store the current substring and its variance in the hashmap map[currentString] = variance / length; // if the current substring is longer than the longest substring // and has a larger variance, update the maxLength and maxString variables if (length > maxLength && variance / length > map[maxString]) { maxLength = length; maxString = currentString; } } } // return the longest substring with the largest variance return maxString; };
class Solution { public: int findSubstringInWraproundString(string p) { int n = p.length(); vectordp(26, 0); int cur = 0; for (int i = 0; i < n; i++) { if (i > 0 && (p[i] - p[i - 1] == 1 || p[i - 1] - p[i] == 25)) { cur++; } else { cur = 1; } dp[p[i] - 'a'] = max(dp[p[i] - 'a'], cur); } return accumulate(dp.begin(), dp.end(), 0); } };
using System; using System.Collections.Generic; public class Solution { public int SubstringWithLargestVariance(string s) { // check for empty string if (string.IsNullOrEmpty(s)) { return 0; } // keep track of the max variance int maxVariance = 0; // keep track of the substring with the largest variance string maxVarianceSubstring = ""; // iterate through the string for (int i = 0; i < s.Length; i++) { // get the current substring string currentSubstring = s.Substring(i); // get the variance of the current substring int currentVariance = GetVariance(currentSubstring); // check if the current variance is greater than the max variance if (currentVariance > maxVariance) { // if so, update the max variance maxVariance = currentVariance; // and update the max variance substring maxVarianceSubstring = currentSubstring; } } // return the max variance substring return maxVarianceSubstring; } // helper method to get the variance of a string public int GetVariance(string s) { // keep track of the sum of the ASCII values int sum = 0; // keep track of the sum of the squares of the ASCII values int sumOfSquares = 0; // iterate through the string for (int i = 0; i < s.Length; i++) { // get the ASCII value of the current character int asciiValue = (int)s[i]; // update the sum sum += asciiValue; // update the sum of squares sumOfSquares += asciiValue * asciiValue; } // calculate the mean int mean = sum / s.Length; // calculate the variance int variance = sumOfSquares / s.Length - mean * mean; // return the variance return variance; } }