Easy and Simple Greedy Solution with Linear Time
SolutionApproach:

Frequency Count:

Use an array hash of size 26 to store the frequency of each letter ('a' to 'z').



Greedy Selection:

Select the largest a
# Solution\n\n## Approach:\n1. **Frequency Count**:\n   - Use an array `hash` of size 26 to store the frequency of each letter (\'a\' to \'z\').\n\n2. **Greedy Selection**:\n   - Select the largest available character (from \'z\' to \'a\') that satisfies the repeat constraint.\n\n3. **Helper Function**:\n   - `getLastChar`: Finds the largest character index that is available in the `hash` array, skipping the last appended character if specified.\n\n4. **Significance of `end_char`**:\n   - `end_char` is used to identify the largest available character, ignoring any restrictions on the `last_vis` (last appended character).\n   - If the `last_vis` character still has occurrences left but is not the current `end_char`, it helps alternate between characters, ensuring that the result string satisfies the lexicographical order while adhering to the repeat constraints.\n\n5. **Iterate Until All Characters Are Used**:\n   - Repeatedly append characters to the result string until no valid characters remain.\n   - Append up to `repeatLimit` instances of the largest character. If constraints prevent appending further, switch to the next largest valid character.\n\n---\n\n## Code\n\n```cpp\nclass Solution {\n    int getLastChar(const vector<int>& hash, int last_vis) {\n        for (int i = 25; i >= 0; i--) \n            if (i != last_vis && hash[i] > 0)\n                return i;\n        return -1;\n    }\n\npublic:\n    string repeatLimitedString(string s, int lim) {\n        vector<int> hash(26, 0); // Frequency array for \'a\' to \'z\'\n        string res;\n\n        for (char ch : s) \n            hash[ch - \'a\']++;\n\n        int last_vis = -1; // Last appended character index\n\n        while (true) {\n            int last_char = getLastChar(hash, last_vis);\n            if (last_char == -1) break; // No valid character left\n\n\n            int end_char = getLastChar(hash, -1);\n\n            // If we can alternate with another character\n            if (last_vis != -1 && hash[last_vis] > 0 && last_char != end_char) {\n                res.push_back(\'a\' + last_char);\n                hash[last_char]--;\n                last_vis = last_char;\n                continue;\n            }\n\n            // Append up to `lim` instances of the largest character\n            int freq = min(hash[last_char], lim);\n            res.append(freq, \'a\' + last_char);\n            hash[last_char] -= freq;\n            last_vis = last_char;\n        }\n\n        return res;\n    }\n};\n
['String', 'Greedy', 'Counting', 'C++']