Substring with highest frequency length product
Last Updated :
26 Mar, 2024
Given a string which contains lower alphabetic characters, we need to find out such a substring of this string whose product of length and frequency in string is maximum among all possible choices of substrings.
Examples:
Input : String str = “abddab”
Output : 6
All unique substring with product of their
frequency and length are,
Val["a"] = 2 * 1 = 2
Val["ab"] = 2 * 2 = 4
Val["abd"] = 1 * 3 = 3
Val["abdd"] = 1 * 4 = 4
Val["abdda"] = 1 * 5 = 5
Val["abddab"] = 1 * 6 = 6
Val["b"] = 2 * 1 = 2
Val["bd"] = 1 * 2 = 2
Val["bdd"] = 1 * 3 = 3
Val["bdda"] = 1 * 4 = 4
Val["bddab"] = 1 * 5 = 5
Val["d"] = 2 * 1 = 2
Val["da"] = 1 * 2 = 2
Val["dab"] = 1 * 3 = 3
Val["dd"] = 1 * 2 = 2
Val["dda"] = 1 * 3 = 3
Val["ddab"] = 1 * 4 = 4
Input : String str = “zzzzzz”
Output : 12
In above string maximum value 12 can
be obtained with substring “zzzz”
A simple solution is to consider all substrings one by one. For every substring, count number of occurrences of it in whole string.
An efficient solution to solve this problem by first constructing longest common prefix array, now suppose value of lcp[i] is K then we can say that i-th and (i+1)-th suffix has K length prefix in common i.e. there is a substring of length K which is repeating twice. In the same way, let three consecutive values of lcp are (K, K-2, K+1) then we can say that there is a substring of length (K-2) which is repeating three times in the string.
Now after above observation, we can see that our result will be such a range of lcp array whose smallest element times number of elements in the range is maximum because range will correspond to the frequency of string and smallest element of range will correspond to length of repeating string now this reformed problem can be solved similar to largest rectangle in histogram problem.
In below code lcp array is constructed by Kasai’s algorithm.
CPP
// C++ program to find substring with highest
// frequency length product
#include <bits/stdc++.h>
using namespace std;
// Structure to store information of a suffix
struct suffix
{
int index; // To store original index
int rank[2]; // To store ranks and next rank pair
};
// A comparison function used by sort() to compare
// two suffixes. Compares two pairs, returns 1 if
// first pair is smaller
int cmp(struct suffix a, struct suffix b)
{
return (a.rank[0] == b.rank[0])?
(a.rank[1] < b.rank[1] ?1: 0):
(a.rank[0] < b.rank[0] ?1: 0);
}
// This is the main function that takes a string
// 'txt' of size n as an argument, builds and
// return the suffix array for the given string
vector<int> buildSuffixArray(string txt, int n)
{
// A structure to store suffixes and their indexes
struct suffix suffixes[n];
// Store suffixes and their indexes in an array
// of structures. The structure is needed to sort
// the suffixes alphabetically and maintain their
// old indexes while sorting
for (int i = 0; i < n; i++)
{
suffixes[i].index = i;
suffixes[i].rank[0] = txt[i] - 'a';
suffixes[i].rank[1] = ((i+1) < n)? (txt[i + 1] - 'a'): -1;
}
// Sort the suffixes using the comparison function
// defined above.
sort(suffixes, suffixes+n, cmp);
// At his point, all suffixes are sorted according to first
// 2 characters. Let us sort suffixes according to first 4
// characters, then first 8 and so on
// This array is needed to get the index in suffixes[]
// from original index. This mapping is needed to get
// next suffix.
int ind[n];
for (int k = 4; k < 2*n; k = k*2)
{
// Assigning rank and index values to first suffix
int rank = 0;
int prev_rank = suffixes[0].rank[0];
suffixes[0].rank[0] = rank;
ind[suffixes[0].index] = 0;
// Assigning rank to suffixes
for (int i = 1; i < n; i++)
{
// If first rank and next ranks are same as
// that of previous suffix in array, assign
// the same new rank to this suffix
if (suffixes[i].rank[0] == prev_rank &&
suffixes[i].rank[1] == suffixes[i-1].rank[1])
{
prev_rank = suffixes[i].rank[0];
suffixes[i].rank[0] = rank;
}
else // Otherwise increment rank and assign
{
prev_rank = suffixes[i].rank[0];
suffixes[i].rank[0] = ++rank;
}
ind[suffixes[i].index] = i;
}
// Assign next rank to every suffix
for (int i = 0; i < n; i++)
{
int nextindex = suffixes[i].index + k/2;
suffixes[i].rank[1] = (nextindex < n)?
suffixes[ind[nextindex]].rank[0]: -1;
}
// Sort the suffixes according to first k characters
sort(suffixes, suffixes+n, cmp);
}
// Store indexes of all sorted suffixes in the suffix array
vector<int>suffixArr;
for (int i = 0; i < n; i++)
suffixArr.push_back(suffixes[i].index);
// Return the suffix array
return suffixArr;
}
/* To construct and return LCP */
vector<int> kasai(string txt, vector<int> suffixArr)
{
int n = suffixArr.size();
// To store LCP array
vector<int> lcp(n, 0);
// An auxiliary array to store inverse of suffix array
// elements. For example if suffixArr[0] is 5, the
// invSuff[5] would store 0. This is used to get next
// suffix string from suffix array.
vector<int> invSuff(n, 0);
// Fill values in invSuff[]
for (int i=0; i < n; i++)
invSuff[suffixArr[i]] = i;
// Initialize length of previous LCP
int k = 0;
// Process all suffixes one by one starting from
// first suffix in txt[]
for (int i=0; i<n; i++)
{
/* If the current suffix is at n-1, then we don’t
have next substring to consider. So lcp is not
defined for this substring, we put zero. */
if (invSuff[i] == n-1)
{
k = 0;
continue;
}
/* j contains index of the next substring to
be considered to compare with the present
substring, i.e., next string in suffix array */
int j = suffixArr[invSuff[i]+1];
// Directly start matching from k'th index as
// at-least k-1 characters will match
while (i+k<n && j+k<n && txt[i+k]==txt[j+k])
k++;
lcp[invSuff[i]] = k; // lcp for the present suffix.
// Deleting the starting character from the string.
if (k>0)
k--;
}
// return the constructed lcp array
return lcp;
}
// method to get LCP array
vector<int> getLCPArray(string str)
{
vector<int>suffixArr = buildSuffixArray(str, str.length());
return kasai(str, suffixArr);
}
// The main function to find the maximum rectangular
// area under given histogram with n bars
int getMaxArea(int hist[], int n)
{
// Create an empty stack. The stack holds indexes
// of hist[] array. The bars stored in stack are
// always in increasing order of their heights.
stack<int> s;
int max_area = 0; // Initialize max area
int tp; // To store top of stack
// To store area with top bar as the smallest bar
int area_with_top;
// Run through all bars of given histogram
int i = 0;
while (i < n)
{
// If this bar is higher than the bar on
// top stack, push it to stack
if (s.empty() || hist[s.top()] <= hist[i])
s.push(i++);
// If this bar is lower than top of stack,
// then calculate area of rectangle with
// stack top as the smallest (or minimum
// height) bar. 'i' is 'right index' for
// the top and element before top in stack
// is 'left index'
else
{
tp = s.top(); // store the top index
s.pop(); // pop the top
// Calculate the area with hist[tp]
// stack as smallest bar
area_with_top = hist[tp] * (s.empty() ?
(i + 1) : i - s.top());
// update max area, if needed
if (max_area < area_with_top)
max_area = area_with_top;
}
}
// Now pop the remaining bars from stack
// and calculate area with every
// popped bar as the smallest bar
while (s.empty() == false)
{
tp = s.top();
s.pop();
area_with_top = hist[tp] * (s.empty() ?
(i + 1) : i - s.top());
if (max_area < area_with_top)
max_area = area_with_top;
}
return max_area;
}
// Returns maximum product of frequency and length
// of a substring.
int maxProductOfFreqLength(string str)
{
// get LCP array by Kasai's algorithm
vector<int> lcp = getLCPArray(str);
int hist[lcp.size()];
// copy lcp array into hist array
for (int i = 0; i < lcp.size(); i++)
hist[i] = lcp[i];
// get the maximum area under lcp histogram
int substrMaxValue = getMaxArea(hist, lcp.size());
// if string length itself is greater than
// histogram area, then return that
if (str.length() > substrMaxValue)
return str.length();
else
return substrMaxValue;
}
// Driver code to test above methods
int main()
{
string str = "abddab";
cout << maxProductOfFreqLength(str) << endl;
return 0;
}
Java
import java.util.*;
class Suffix {
int index;
int[] rank = new int[2];
}
class Main {
// A comparison function used to compare two suffixes
static int cmp(Suffix a, Suffix b) {
return (a.rank[0] == b.rank[0]) ?
Integer.compare(a.rank[1], b.rank[1]) :
Integer.compare(a.rank[0], b.rank[0]);
}
// This function builds the suffix array for the given string
static ArrayList<Integer> buildSuffixArray(String txt, int n) {
ArrayList<Suffix> suffixes = new ArrayList<>();
// Store suffixes and their indexes
for (int i = 0; i < n; i++) {
Suffix suffix = new Suffix();
suffix.index = i;
suffix.rank[0] = txt.charAt(i) - 'a';
suffix.rank[1] = (i + 1) < n ? txt.charAt(i + 1) - 'a' : -1;
suffixes.add(suffix);
}
// Sort the suffixes
suffixes.sort(Main::cmp);
// At this point, all suffixes are sorted according to first 2 characters
// Sort suffixes according to first 4 characters, then first 8 and so on
int[] ind = new int[n];
for (int k = 4; k < 2 * n; k = k * 2) {
int rank = 0;
int prev_rank = suffixes.get(0).rank[0];
suffixes.get(0).rank[0] = rank;
ind[suffixes.get(0).index] = 0;
for (int i = 1; i < n; i++) {
if (suffixes.get(i).rank[0] == prev_rank && suffixes.get(i).rank[1] == suffixes.get(i - 1).rank[1]) {
prev_rank = suffixes.get(i).rank[0];
suffixes.get(i).rank[0] = rank;
} else {
prev_rank = suffixes.get(i).rank[0];
suffixes.get(i).rank[0] = ++rank;
}
ind[suffixes.get(i).index] = i;
}
for (int i = 0; i < n; i++) {
int nextindex = suffixes.get(i).index + k / 2;
suffixes.get(i).rank[1] = (nextindex < n) ? suffixes.get(ind[nextindex]).rank[0] : -1;
}
suffixes.sort(Main::cmp);
}
// Store indexes of all sorted suffixes
ArrayList<Integer> suffixArr = new ArrayList<>();
for (Suffix suffix : suffixes) {
suffixArr.add(suffix.index);
}
// Return the suffix array
return suffixArr;
}
// Construct and return the LCP array
static ArrayList<Integer> kasai(String txt, ArrayList<Integer> suffixArr) {
int n = suffixArr.size();
ArrayList<Integer> lcp = new ArrayList<>(Collections.nCopies(n, 0));
int[] invSuff = new int[n];
for (int i = 0; i < n; i++) {
invSuff[suffixArr.get(i)] = i;
}
int k = 0;
for (int i = 0; i < n; i++) {
if (invSuff[i] == n - 1) {
k = 0;
continue;
}
int j = suffixArr.get(invSuff[i] + 1);
while (i + k < n && j + k < n && txt.charAt(i + k) == txt.charAt(j + k)) {
k++;
}
lcp.set(invSuff[i], k);
if (k > 0) {
k--;
}
}
return lcp;
}
// Get the LCP array
static ArrayList<Integer> getLCPArray(String str) {
ArrayList<Integer> suffixArr = buildSuffixArray(str, str.length());
return kasai(str, suffixArr);
}
// Get maximum area under histogram
static int getMaxArea(int[] hist, int n) {
Stack<Integer> s = new Stack<>();
int max_area = 0;
int tp;
int area_with_top;
int i = 0;
while (i < n) {
if (s.isEmpty() || hist[s.peek()] <= hist[i]) {
s.push(i++);
} else {
tp = s.pop();
area_with_top = hist[tp] * (s.isEmpty() ? (i + 1) : (i - s.peek()));
if (max_area < area_with_top) {
max_area = area_with_top;
}
}
}
while (!s.isEmpty()) {
tp = s.pop();
area_with_top = hist[tp] * (s.isEmpty() ? (i + 1) : (i - s.peek()));
if (max_area < area_with_top) {
max_area = area_with_top;
}
}
return max_area;
}
// Returns maximum product of frequency and length of a substring.
static int maxProductOfFreqLength(String str) {
ArrayList<Integer> lcp = getLCPArray(str);
int[] hist = new int[lcp.size()];
for (int i = 0; i < lcp.size(); i++) {
hist[i] = lcp.get(i);
}
int substrMaxValue = getMaxArea(hist, lcp.size());
if (str.length() > substrMaxValue) {
return str.length();
} else {
return substrMaxValue;
}
}
public static void main(String[] args) {
String str = "abddab";
System.out.println(maxProductOfFreqLength(str));
}
}
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class Suffix
{
public int Index { get; set; }
public int[] Rank { get; set; } = new int[2];
}
public class Program
{
// Custom comparison function for sorting suffixes
public static int Cmp(Suffix a, Suffix b)
{
return (a.Rank[0] == b.Rank[0]) ?
(a.Rank[1] < b.Rank[1] ? 1 : 0) :
(a.Rank[0] < b.Rank[0] ? 1 : 0);
}
// Function to build the suffix array of a given string
public static List<int> BuildSuffixArray(string txt, int n)
{
Suffix[] suffixes = new Suffix[n];
// Create suffixes with their ranks
for (int i = 0; i < n; i++)
{
suffixes[i] = new Suffix
{
Index = i,
Rank = new int[]
{
txt[i] - 'a',
(i + 1) < n ? (txt[i + 1] - 'a') : -1
}
};
}
// Sort the suffixes using custom comparison function
Array.Sort(suffixes, Cmp);
// Ind array to store indexes of sorted suffixes
int[] ind = new int[n];
// Iterate to sort the suffixes by their first k characters
for (int k = 4; k < 2 * n; k = k * 2)
{
int rank = 0;
int prevRank = suffixes[0].Rank[0];
suffixes[0].Rank[0] = rank;
ind[suffixes[0].Index] = 0;
for (int i = 1; i < n; i++)
{
if (suffixes[i].Rank[0] == prevRank &&
suffixes[i].Rank[1] == suffixes[i - 1].Rank[1])
{
prevRank = suffixes[i].Rank[0];
suffixes[i].Rank[0] = rank;
}
else
{
prevRank = suffixes[i].Rank[0];
suffixes[i].Rank[0] = ++rank;
}
ind[suffixes[i].Index] = i;
}
for (int i = 0; i < n; i++)
{
int nextIndex = suffixes[i].Index + k / 2;
suffixes[i].Rank[1] = (nextIndex < n) ?
suffixes[ind[nextIndex]].Rank[0] : -1;
}
// Sort the suffixes according to first k characters
Array.Sort(suffixes, Cmp);
}
// Store indexes of all sorted suffixes in the suffix array
List<int> suffixArr = new List<int>();
for (int i = 0; i < n; i++)
suffixArr.Add(suffixes[i].Index);
return suffixArr;
}
// Function to compute the longest common prefix array
public static List<int> Kasai(string txt, List<int> suffixArr)
{
int n = suffixArr.Count;
List<int> lcp = new List<int>(new int[n]);
List<int> invSuff = new List<int>(new int[n]);
// Fill values in invSuff[]
for (int i = 0; i < n; i++)
invSuff[suffixArr[i]] = i;
int k = 0;
// Compute the LCP array
for (int i = 0; i < n; i++)
{
if (invSuff[i] == n - 1)
{
k = 0;
continue;
}
int j = suffixArr[invSuff[i] + 1];
while (i + k < n && j + k < n && txt[i + k] == txt[j + k])
k++;
lcp[invSuff[i]] = k;
if (k > 0)
k--;
}
return lcp;
}
// Function to compute the LCP array
public static List<int> GetLCPArray(string str)
{
List<int> suffixArr = BuildSuffixArray(str, str.Length);
return Kasai(str, suffixArr);
}
// Function to get the maximum area under a histogram
public static int GetMaxArea(int[] hist, int n)
{
Stack<int> s = new Stack<int>();
int maxArea = 0;
int tp;
int areaWithTop;
int i = 0;
while (i < n)
{
if (s.Count == 0 || hist[s.Peek()] <= hist[i])
s.Push(i++);
else
{
tp = s.Pop();
areaWithTop = hist[tp] * (s.Count == 0 ? (i + 1) : (i - s.Peek()));
if (maxArea < areaWithTop)
maxArea = areaWithTop;
}
}
while (s.Count > 0)
{
tp = s.Pop();
areaWithTop = hist[tp] * (s.Count == 0 ? (i + 1) : (i - s.Peek()));
if (maxArea < areaWithTop)
maxArea = areaWithTop;
}
return maxArea;
}
// Function to compute the maximum product of frequency and length of a substring
public static int MaxProductOfFreqLength(string str)
{
List<int> lcp = GetLCPArray(str);
int[] hist = lcp.ToArray();
int substrMaxValue = GetMaxArea(hist, lcp.Count);
if (str.Length > substrMaxValue)
return str.Length;
else
return substrMaxValue;
}
// Main function
public static void Main(string[] args)
{
string str = "abddab";
Console.WriteLine(MaxProductOfFreqLength(str));
}
}
JavaScript
// A comparison function used to compare two suffixes
function cmp(a, b) {
return (a.rank[0] === b.rank[0]) ?
a.rank[1] - b.rank[1] :
a.rank[0] - b.rank[0];
}
// This function builds the suffix array for the given string
function buildSuffixArray(txt) {
let n = txt.length;
let suffixes = [];
// Store suffixes and their indexes
for (let i = 0; i < n; i++) {
let suffix = {
index: i,
rank: [txt.charCodeAt(i) - 'a'.charCodeAt(0), (i + 1) < n ? txt.charCodeAt(i + 1) - 'a'.charCodeAt(0) : -1]
};
suffixes.push(suffix);
}
// Sort the suffixes
suffixes.sort(cmp);
// At this point, all suffixes are sorted according to first 2 characters
// Sort suffixes according to first 4 characters, then first 8 and so on
let ind = new Array(n).fill(0);
for (let k = 4; k < 2 * n; k *= 2) {
let rank = 0;
let prev_rank = suffixes[0].rank[0];
suffixes[0].rank[0] = rank;
ind[suffixes[0].index] = 0;
for (let i = 1; i < n; i++) {
if (suffixes[i].rank[0] === prev_rank && suffixes[i].rank[1] === suffixes[i - 1].rank[1]) {
prev_rank = suffixes[i].rank[0];
suffixes[i].rank[0] = rank;
} else {
prev_rank = suffixes[i].rank[0];
suffixes[i].rank[0] = ++rank;
}
ind[suffixes[i].index] = i;
}
for (let i = 0; i < n; i++) {
let nextindex = suffixes[i].index + k / 2;
suffixes[i].rank[1] = (nextindex < n) ? suffixes[ind[nextindex]].rank[0] : -1;
}
suffixes.sort(cmp);
}
// Store indexes of all sorted suffixes
let suffixArr = [];
for (let i = 0; i < suffixes.length; i++) {
suffixArr.push(suffixes[i].index);
}
// Return the suffix array
return suffixArr;
}
// Construct and return the LCP array
function kasai(txt, suffixArr) {
let n = suffixArr.length;
let lcp = new Array(n).fill(0);
let invSuff = new Array(n);
for (let i = 0; i < n; i++) {
invSuff[suffixArr[i]] = i;
}
let k = 0;
for (let i = 0; i < n; i++) {
if (invSuff[i] === n - 1) {
k = 0;
continue;
}
let j = suffixArr[invSuff[i] + 1];
while (i + k < n && j + k < n && txt[i + k] === txt[j + k]) {
k++;
}
lcp[invSuff[i]] = k;
if (k > 0) {
k--;
}
}
return lcp;
}
// Get the LCP array
function getLCPArray(str) {
let suffixArr = buildSuffixArray(str);
return kasai(str, suffixArr);
}
// Get maximum area under histogram
function getMaxArea(hist) {
let s = [];
let max_area = 0;
let tp;
let area_with_top;
let i = 0;
while (i < hist.length) {
if (s.length === 0 || hist[s[s.length - 1]] <= hist[i]) {
s.push(i++);
} else {
tp = s.pop();
area_with_top = hist[tp] * (s.length === 0 ? (i + 1) : (i - s[s.length - 1]));
if (max_area < area_with_top) {
max_area = area_with_top;
}
}
}
while (s.length !== 0) {
tp = s.pop();
area_with_top = hist[tp] * (s.length === 0 ? (i + 1) : (i - s[s.length - 1]));
if (max_area < area_with_top) {
max_area = area_with_top;
}
}
return max_area;
}
// Returns maximum product of frequency and length of a substring.
function maxProductOfFreqLength(str) {
let lcp = getLCPArray(str);
let hist = lcp.slice();
let substrMaxValue = getMaxArea(hist);
if (str.length > substrMaxValue) {
return str.length;
} else {
return substrMaxValue;
}
}
let str = "abddab";
console.log(maxProductOfFreqLength(str));
Python3
from typing import List
from collections import deque
# Structure to store information of a suffix
class Suffix:
def __init__(self):
self.index = 0 # To store original index
self.rank = [0, 0] # To store ranks and next rank pair
# A comparison function used by sort() to compare two suffixes
def cmp(a: Suffix, b: Suffix) -> int:
if a.rank[0] == b.rank[0]:
return 1 if a.rank[1] < b.rank[1] else 0
else:
return 1 if a.rank[0] < b.rank[0] else 0
# Function to build and return the suffix array for the given string
def build_suffix_array(txt: str) -> List[int]:
n = len(txt)
suffixes = [Suffix() for _ in range(n)]
# Store suffixes and their indexes in an array of structures
for i in range(n):
suffixes[i].index = i
suffixes[i].rank[0] = ord(txt[i]) - ord('a')
suffixes[i].rank[1] = ord(txt[i + 1]) - ord('a') if i + 1 < n else -1
# Sort the suffixes using the comparison function
suffixes.sort(key=lambda x: (x.rank[0], x.rank[1]))
# At this point, all suffixes are sorted according to first 2 characters
ind = [0] * n # This array is needed to get the index in suffixes[] from original index
for k in range(4, 2 * n, 2):
rank = 0
prev_rank = suffixes[0].rank[0]
suffixes[0].rank[0] = rank
ind[suffixes[0].index] = 0
# Assigning rank to suffixes
for i in range(1, n):
if suffixes[i].rank[0] == prev_rank and suffixes[i].rank[1] == suffixes[i - 1].rank[1]:
prev_rank = suffixes[i].rank[0]
suffixes[i].rank[0] = rank
else:
prev_rank = suffixes[i].rank[0]
rank += 1
suffixes[i].rank[0] = rank
ind[suffixes[i].index] = i
# Assign next rank to every suffix
for i in range(n):
nextindex = suffixes[i].index + k // 2
suffixes[i].rank[1] = suffixes[ind[nextindex]].rank[0] if nextindex < n else -1
# Sort the suffixes according to first k characters
suffixes.sort(key=lambda x: (x.rank[0], x.rank[1]))
# Store indexes of all sorted suffixes in the suffix array
suffix_arr = [suffixes[i].index for i in range(n)]
# Return the suffix array
return suffix_arr
# Function to construct and return LCP array
def kasai(txt: str, suffix_arr: List[int]) -> List[int]:
n = len(suffix_arr)
lcp = [0] * n # To store LCP array
inv_suff = [0] * n # To store inverse of suffix array elements
# Fill values in inv_suff[]
for i in range(n):
inv_suff[suffix_arr[i]] = i
k = 0 # Initialize length of previous LCP
for i in range(n):
if inv_suff[i] == n - 1:
k = 0
continue
j = suffix_arr[inv_suff[i] + 1] # Index of the next substring to be considered
while i + k < n and j + k < n and txt[i + k] == txt[j + k]:
k += 1
lcp[inv_suff[i]] = k # LCP for the present suffix
if k > 0:
k -= 1
# Return the constructed LCP array
return lcp
# Function to get LCP array
def get_lcp_array(txt: str) -> List[int]:
suffix_arr = build_suffix_array(txt)
return kasai(txt, suffix_arr)
# Function to find the maximum rectangular area under given histogram with n bars
def get_max_area(hist: List[int]) -> int:
n = len(hist)
s = deque()
max_area = 0
i = 0
while i < n:
if not s or hist[s[-1]] <= hist[i]:
s.append(i)
i += 1
else:
tp = s.pop()
area_with_top = hist[tp] * ((i - s[-1] - 1) if s else i)
max_area = max(max_area, area_with_top)
while s:
tp = s.pop()
area_with_top = hist[tp] * ((i - s[-1] - 1) if s else i)
max_area = max(max_area, area_with_top)
return max_area
# Function to get the maximum product of frequency and length of a substring
def max_product_of_freq_length(txt: str) -> int:
lcp = get_lcp_array(txt)
hist = lcp[:]
substr_max_value = get_max_area(hist)
return max(len(txt), substr_max_value)
# Driver code to test above methods
if __name__ == "__main__":
str_val = "abddab"
print(max_product_of_freq_length(str_val))
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem