#include #include #include #include #include class Solution { public: std::string smallestPalindrome(std::string s, int k) { std::string half = s.substr(0, s.size() / 2); char middle = (s.size() % 2 == 1) ? s[s.size() / 2] : '\0'; std::ranges::sort(half); std::set permutations; do { permutations.insert(half); } while (std::ranges::next_permutation(half).found); if (permutations.size() > std::numeric_limits::max()) { throw std::overflow_error("Number of permutations exceeds int limit"); } int size = static_cast(permutations.size()); if (k > size) { return std::string(); } auto it = permutations.begin(); std::advance(it, k - 1); std::string mirroredHalf = *it; std::ranges::reverse(mirroredHalf); if (middle != '\0') { return *it + std::string(1, middle) + mirroredHalf; } return *it + mirroredHalf; } };