- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 57 lines of C++ from the credited upstream file minimum-operations-to-make-binary-palindrome.cpp.
- The implementation visibly relies on sequence storage.
- 6 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1234 56const auto& precompute = [](int n) {7 const auto& bit_length = [](int x) {8 return (x ? std::__lg(x) : -1) + 1;9 };10 11 const auto& l = bit_length(n);12 vector<int> palindromes;13 for (int d = 1; d <= l; ++d) {14 const auto& h = (d + 1) / 2;15 for (int prefix = (1 << (h - 1)); prefix < (1 << h); ++prefix) {16 int p = prefix, t = prefix;17 t >>= d % 2;18 for (int i = 0; i < h - d % 2; ++i) {19 p = (p << 1) | (t & 1);20 t >>= 1;21 }22 if (p <= n) {23 palindromes.emplace_back(p);24 }25 }26 }27 vector<int> lookup(n + 1, numeric_limits<int>::max());28 for (int x = 1, i = 0; x <= n; ++x) {29 for (; i < size(palindromes); ++i) {30 if (palindromes[i] > x) {31 break;32 }33 }34 if (i < size(palindromes)) {35 lookup[x] = min(lookup[x], palindromes[i] - x);36 }37 if (i - 1 >= 0) {38 lookup[x] = min(lookup[x], x - palindromes[i - 1]);39 }40 }41 return lookup;42};43 44const auto& MAX_NUM = 5000;45const auto& LOOKUP = precompute(MAX_NUM);46class Solution {47public:48 vector<int> minOperations(vector<int>& nums) {49 vector<int> result;50 result.reserve(size(nums));51 for (const auto& x : nums) {52 result.emplace_back(LOOKUP[x]);53 }54 return result;55 }56};57