Open In App

Substring with highest frequency length product

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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))

Output
6

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads