1. Brute Force — Copy to Array & Two-Pointer Validation
Intuition
Convert the linked list into an array. Check if the array is a palindrome using two pointers moving toward the center.
Algorithm
- Step 1: Traverse list and copy each node's
valinto arrayvals. - Step 2: Initialize
left = 0,right = vals.length - 1. - Step 3: While
left < right: - a. If
vals[left] != vals[right], returnfalse. - b.
left++,right--. - Step 4: Return
true.
#include <iostream>#include <vector> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {}}; class Solution {public: bool isPalindrome(ListNode* head) { vector<int> vals; for (ListNode* c = head; c; c = c->next) { vals.push_back(c->val); } int left = 0, right = (int)vals.size() - 1; while (left < right) { if (vals[left] != vals[right]) return false; left++; right--; } return true; }}; int main() { ListNode* h = new ListNode(1); h->next = new ListNode(2); h->next->next = new ListNode(2); h->next->next->next = new ListNode(1); Solution sol; cout << "Brute Force isPalindrome: " << (sol.isPalindrome(h) ? "true" : "false") << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Traverses the linked list of N nodes in O(N) and compares array elements in O(N/2). - Space complexity:
O(N)— Allocates an array buffer of size N.
Why Brute Force Doesn't Scale:
Array conversion allocates O(N) memory, which for N = 105 uses ~1MB and triggers heap allocations.
For N = 100,000, in-place palindrome validation runs in <1.2ms with 0 extra heap memory.