1. All Pairs String Concatenation
Intuition
Two nested loops generating all pairs. Concatenate words[i] + words[j] and run a two-pointer check. Add [i, j] if valid.
When to apply: Basic baseline check.
Algorithm
- Step 1: Loop
ifrom 0 to N-1. - Step 2: Loop
jfrom 0 to N-1: ifi == j, continue. - Step 3: Check if
words[i] + words[j]is a palindrome. - Step 4: If yes, add
[i, j]to output list.
#include <iostream>#include <vector>#include <string>using namespace std; class Solution { bool isPalindrome(const string& s) { int l = 0, r = s.length() - 1; while (l < r) { if (s[l++] != s[r--]) return false; } return true; } public: vector<vector<int>> palindromePairs(vector<string>& words) { vector<vector<int>> result; int n = words.size(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) continue; if (isPalindrome(words[i] + words[j])) { result.push_back({i, j}); } } } return result; }}; int main() { Solution sol; vector<string> words = {"abcd","dcba","lls","s","sssll"}; auto res = sol.palindromePairs(words); for (const auto& p : res) cout << "[" << p[0] << "," << p[1] << "] "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2 * L)— N2 pairs each taking O(L) to concatenate and verify. - Space complexity:
O(L)— Allocates combined string.
Why Brute Force Doesn't Scale:
N = 5,000 creates 25,000,000 pairs, exceeding time limits by 100x.
Reversed Trie with cached palindrome suffixes processes all 5,000 words in O(N * L2) ~ 50ms.