C++ 0234.cpp
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<int> s;
while (head)
{
s.push_back(head->val);
head = head->next;
}
auto t = s;
reverse(t.begin(), t.end());
return s == t;
}
};
Difficulty
and has an acceptance rate of about 58% (4+ million submissions).
Typical patterns to solve this problem:
- Linked List
- Recursion
- Stack
- Two Pointers
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation determines whether a singly-linked list of integers reads the same forward and backward. It does so by extracting the node values into a dynamic array, creating a reversed copy of that array, and then comparing the two sequences for equality. The approach is straightforward, leveraging standard library containers and algorithms to keep the logic concise and readable.
Extraction of Node Values
The first logical phase walks through the linked list from its head to the tail, appending each node’s integer value to a std::vector<int>. This step materializes the list’s contents in contiguous memory, which is advantageous for subsequent operations that benefit from cache locality.
vector<int> s;
while (head)
{
s.push_back(head->val);
head = head->next;
}
During this traversal the code naturally accommodates lists of any length, including the degenerate cases where the list is empty (head is nullptr) or contains a single element. In both situations the loop either does not execute or executes exactly once, leaving s in a state that correctly reflects the list’s contents.
Creation of a Reversed Copy
After the original sequence is stored, a second vector t is initialized as a copy of s. The standard algorithm std::reverse is then applied to t, producing a reversed ordering of the values without altering the original vector.
auto t = s;
reverse(t.begin(), t.end());
The use of auto for the copy declaration allows the compiler to infer the exact type, preserving const-correctness and avoiding unnecessary verbosity. The in-place reversal operates directly on the contiguous storage of t, which is efficient due to sequential memory access patterns.
Comparison for Palindromicity
The final step leverages the equality operator defined for std::vector. This operator performs an element-wise comparison, returning true only if the two vectors have identical length and matching elements at each position.
return s == t;
Because s holds the original order and t holds the reversed order, the equality test directly answers whether the list reads the same forward and backward. The comparison automatically handles all edge cases: an empty vector compares equal to another empty vector, and a single-element vector is trivially equal to its reverse.
Edge-Case Handling
The algorithm gracefully manages several special conditions without additional code. When the input list is empty, the extraction loop leaves s empty; copying and reversing an empty vector are no-ops, and the equality check yields true, treating an empty list as a palindrome. For a list containing a single node, s ends up with one element; reversing a single-element vector leaves it unchanged, and the equality test again returns true. Lists with an odd number of elements produce a central element that maps to itself in the reversed copy, while even-length lists produce symmetric pairs; the element-wise comparison correctly validates both scenarios.
Performance Optimizations Observed
The implementation benefits from several implicit optimizations provided by the standard library. Storing values in a std::vector ensures contiguous allocation, which improves cache performance during both the reversal and the equality comparison. The use of std::reverse operates in linear time with minimal overhead, directly swapping elements in place without auxiliary storage. The equality operator for vectors is also highly optimized; it first checks size equality before proceeding to element-wise comparison, allowing early exit when a mismatch is detected. By copying the original vector only once and reusing the copy for reversal, the code avoids repeated traversals of the linked list, consolidating all necessary work into a single pass over the list followed by linear-time operations on the vectors.
ELI5 - Simplified Explanation
Imagine you have a long train made of several colorful blocks connected in a line. Each block has a special number painted on it. This code is like a helper who wants to see if the train looks exactly the same when you read it from the front to the back or from the back to the front.
First, the helper walks along the train from the very first block all the way to the end. Every time the helper passes a block, they write the number on that block into a notebook. Once the helper reaches the end, the notebook has a list of all the numbers in the order they appear on the train.
Next, the helper makes a copy of that list in the notebook. Then, the helper uses magic to flip that copy around so the last number is now first and the first number is now last.
Finally, the helper looks at the original list and the flipped copy side by side. If every number in the first list matches the number in the same spot in the second list, it means the train is like a mirror image of itself. That is what a palindrome is.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||||
| WalkCCC | C++ | Python | Java | ||||||||||
| leetcode.ca | C++ | Python | Java | C# | JS | Go | TS | ||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | AdelDaniel | Dart | |||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++ | ||||||||||||
| bujosa | Rust | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| Dijkstra-Edu | Java | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| fsq | Python | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| MacJim | C++ | ||||||||||||
| muhammadfarhankt | Go | ||||||||||||
| pruthvikp | Python | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, TypeScript | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| AdelDaniel | Dart | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| bujosa | Rust | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| Dijkstra-Edu | Java | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| fsq | Python | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| MacJim | C++ | ||||||||||||
| muhammadfarhankt | Go | ||||||||||||
| pruthvikp | Python | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 206: Reverse Linked List
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality