- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 48 lines of C++ from the credited upstream file 564.cpp.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 string nearestPalindromic(string n) {4 const auto& [prevPalindrome, nextPalindrome] = getPalindromes(n);5 return abs(prevPalindrome - stol(n)) <= abs(nextPalindrome - stol(n))6 ? to_string(prevPalindrome)7 : to_string(nextPalindrome);8 }9 10 private:11 12 pair<long, long> getPalindromes(const string& s) {13 const long num = stol(s);14 const int n = s.length();15 pair<long, long> palindromes;16 const string half = s.substr(0, (n + 1) / 2);17 const string reversedHalf = reversed(half.substr(0, n / 2));18 const long candidate = stol(half + reversedHalf);19 20 if (candidate < num)21 palindromes.first = candidate;22 else {23 const string prevHalf = to_string(stol(half) - 1);24 const string reversedPrevHalf = reversed(prevHalf.substr(0, n / 2));25 if (n % 2 == 0 && stol(prevHalf) == 0)26 palindromes.first = 9;27 else if (n % 2 == 0 && prevHalf == "9")28 palindromes.first = stol(prevHalf + '9' + reversedPrevHalf);29 else30 palindromes.first = stol(prevHalf + reversedPrevHalf);31 }32 33 if (candidate > num)34 palindromes.second = candidate;35 else {36 const string& nextHalf = to_string(stol(half) + 1);37 const string& reversedNextHalf = reversed(nextHalf.substr(0, n / 2));38 palindromes.second = stol(nextHalf + reversedNextHalf);39 }40 41 return palindromes;42 }43 44 string reversed(const string& s) {45 return {s.rbegin(), s.rend()};46 }47};48