C++ O(N) Time Greedy
See my latest update in repo LeetCode\n\n## Solution 1. Greedy\n\nIntuition: We can do it greedily:\n\n If picking a won\'t result in unsolvable problem, we pre
See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n\n## Solution 1. Greedy\n\n**Intuition**: We can do it greedily:\n\n* If picking `a` won\'t result in unsolvable problem, we prepend `a` to the start of the string.\n* Otherwise, if picking `z` won\'t result in unsolvable problem, we append `z` to the end of the string.\n* Otherwise, if there is still a non-zero `k` value left (which must be smaller than 26), we add `\'a\' + k - 1` in the middle.\n\n**Algorithm**:\n\nHow to check if it will become unsolvable problem?\n\nIf after picking `\'a\'`, the remainder numeric value `k - 1` can\'t be formed even if using all `\'z\'`s, i.e. `k - 1 >= (n - 1) * 26`, then it\'s unsolvable.\n\nSo if `n - 1 > 0 && k - 1 < (n - 1) * 26`, we should keep prepending `\'a\'`.\n\nIf after picking `\'z\'`, the remainder numeric value `k - 26` can\'t be formed even if using all `\'a\'`s, i.e. `k - 26 < n - 1`, then it\'s unsolvable.\n\nSo if `n - 1 > 0 && k - 26 >= n - 1`, we should keep appending `\'z\'`.\n\n\n```cpp\n// OJ: https://leetcode.com/contest/weekly-contest-216/problems/smallest-string-with-a-given-numeric-value/\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n    string getSmallestString(int n, int k) {\n        string s;\n        int a = 0, z = 0;\n        while (n - 1 > 0 && k - 1 < (n - 1) * 26) ++a, --k, --n;\n        while (n - 1 > 0 && k - 26 >= n - 1) ++z, k -= 26, --n;\n        while (a-- > 0) s += \'a\';\n        if (k) s += \'a\' + k - 1;\n        while (z-- > 0) s += \'z\';\n        return s;\n    }\n};\n```\n\n## Solution 2.\n\nStarts with all `\'a\'`, fill the `k` value from the end of the array backwards.\n\n```cpp\n// OJ: https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n    string getSmallestString(int n, int k) {\n        string s(n, \'a\');\n        k -= n;\n        for (int i = n - 1; k > 0; --i) {\n            int d = min(k, 25);\n            s[i] += d;\n            k -= d;\n        }\n        return s;\n    }\n};\n```
[]