- 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
- 44 lines of C++ from the credited upstream file 336.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 4 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.
1class Solution {2 public:3 vector<vector<int>> palindromePairs(vector<string>& words) {4 vector<vector<int>> ans;5 unordered_map<string, int> map; 6 7 for (int i = 0; i < words.size(); ++i) {8 string word = words[i];9 ranges::reverse(word);10 map[word] = i;11 }12 13 for (int i = 0; i < words.size(); ++i) {14 const string& word = words[i];15 16 if (const auto it = map.find("");17 it != map.cend() && it->second != i && isPalindrome(word))18 ans.push_back({i, it->second});19 for (int j = 1; j <= word.length(); ++j) {20 const string& l = word.substr(0, j);21 const string& r = word.substr(j);22 if (const auto it = map.find(l);23 it != map.cend() && it->second != i && isPalindrome(r))24 ans.push_back({i, it->second});25 if (const auto it = map.find(r);26 it != map.cend() && it->second != i && isPalindrome(l))27 ans.push_back({it->second, i});28 }29 }30 31 return ans;32 }33 34 private:35 bool isPalindrome(const string& word) {36 int l = 0;37 int r = word.length() - 1;38 while (l < r)39 if (word[l++] != word[r--])40 return false;41 return true;42 }43};44