- 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
- 36 lines of Java from the credited upstream file 336.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered 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 List<List<Integer>> palindromePairs(String[] words) {3 List<List<Integer>> ans = new ArrayList<>();4 Map<String, Integer> map = new HashMap<>(); 5 6 for (int i = 0; i < words.length; ++i)7 map.put(new StringBuilder(words[i]).reverse().toString(), i);8 9 for (int i = 0; i < words.length; ++i) {10 final String word = words[i];11 12 if (map.containsKey("") && map.get("") != i && isPalindrome(word))13 ans.add(Arrays.asList(i, map.get("")));14 for (int j = 1; j <= word.length(); ++j) {15 final String l = word.substring(0, j);16 final String r = word.substring(j);17 if (map.containsKey(l) && map.get(l) != i && isPalindrome(r))18 ans.add(Arrays.asList(i, map.get(l)));19 if (map.containsKey(r) && map.get(r) != i && isPalindrome(l))20 ans.add(Arrays.asList(map.get(r), i));21 }22 }23 24 return ans;25 }26 27 private boolean isPalindrome(final String word) {28 int l = 0;29 int r = word.length() - 1;30 while (l < r)31 if (word.charAt(l++) != word.charAt(r--))32 return false;33 return true;34 }35}36