✅ 🔥 95% Faster with 90% less memory | Array | No inbuilt algorithm used ✅ 🔥
IntuitionWe can use a basic array to find the frequency of each character from 'a' to 'z'. Then, sort the result in descending order from 'z' to 'a' based on th
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can use a basic array to find the frequency of each character from \'a\' to \'z\'. Then, sort the result in descending order from \'z\' to \'a\' based on the given conditions of maximum repetition and lexicographical order.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Find the frequency of each character.\n2. Add the values to the result string builder in descending order.\n3. If the frequency exceeds the given repeat limit, store the excess in a cache variable, insert the next smallest character once, and repeat the process.\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nKindly upvote if you reached till here.. :)\n\n# Code\n```java []\nclass Solution {\n    public String repeatLimitedString(String s, int repeatLimit) {\n        StringBuilder res = new StringBuilder();\n        int[] alpha = new int[26];\n        for(char ch: s.toCharArray()){\n            alpha[ch-\'a\']++;\n        }\n        char t = \'z\';\n        int val = 0;\n        for(int i=25; i>=0; i--){\n            if(alpha[i]>0){\n                while(val>0 && alpha[i]>0){\n                    res.append((char)(\'a\'+i));\n                    alpha[i]--;\n                    for(int j=0; j<Math.min(repeatLimit, val); j++){\n                        res.append(t);\n                    }\n                    val = val - Math.min(repeatLimit, val);\n                }\n                if(alpha[i]>0){\n                    for(int j=0; j<Math.min(repeatLimit, alpha[i]); j++){\n                        res.append((char)(\'a\'+i));\n                    }\n                    alpha[i] = alpha[i] - Math.min(repeatLimit, alpha[i]);\n                }\n                if(alpha[i]>0){\n                    t = (char)(\'a\'+i);\n                    val = alpha[i];\n                }\n            }\n        }\n        return res.toString();\n    }\n}\n```
['Array', 'Greedy', 'Java']