- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 57 lines of C++ from the credited upstream file next-special-palindrome-number.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1234 56const int MAX_LEN = 16;7 8const auto& precompute = []() {9 const auto& f = [](int mask) {10 string result, mid;11 for (int i = 0; i < 9; ++i) {12 if ((mask & (1 << i)) == 0) {13 continue;14 }15 if ((i + 1) % 2) {16 if (!empty(mid)) {17 return tuple(result, mid, false);18 }19 mid = to_string(i + 1);20 }21 for (int _ = 0; _ < (i + 1) / 2; ++_) {22 result.push_back('0' + (i + 1));23 }24 }25 return tuple(result, mid, true);26 };27 28 vector<int64_t> result;29 for (int mask = 1; mask < (1 << 9); ++mask) {30 auto [left, mid, ok] = f(mask);31 if (!ok) {32 continue;33 }34 do {35 string right = left;36 reverse(begin(right), end(right));37 string p = left;38 p += mid;39 p += right;40 if (size(p) > MAX_LEN) {41 break;42 }43 result.emplace_back(stoll(p));44 } while (next_permutation(begin(left), end(left)));45 }46 sort(begin(result), end(result));47 return result;48};49 50const auto& PALINDROMES = precompute();51class Solution {52public:53 long long specialPalindrome(long long n) {54 return *upper_bound(begin(PALINDROMES), end(PALINDROMES), n);55 }56};57