Problem 234

Abstract / Summary

Determine if a linked list reads the same forwards and backwards.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};
16 lines | 303 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 58% (4+ million submissions).

Typical patterns to solve this problem:
  • Linked List
  • Recursion
  • Stack
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.22 | σ = 1.23

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
61 links | 45 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'LeetCode Palindrome Linked List Solution Explained - Java'
Nick White 10 mins
LeetCode Palindrome Linked List Solution Explained - Java
YouTube video 'Palindrome Linked List (LeetCode 234) | Full solution with trick | Study Algorithms'
Nikhil Lohia 15 mins
Palindrome Linked List (LeetCode 234) | Full solution with trick | Study Algorithms
YouTube video 'Is a Linked List Palindrome | Solution'
Pepcoding 14 mins
Is a Linked List Palindrome | Solution
YouTube video 'LeetCode 234: Palindrome Linked List - Interview Prep Ep 63'
Fisher Coder 8 mins
LeetCode 234: Palindrome Linked List - Interview Prep Ep 63
YouTube video 'Palindrome Linked List | 4 Approaches | Leetcode 234| codestorywithMIK'
codestorywithMIK 45 mins
Palindrome Linked List | 4 Approaches | Leetcode 234| codestorywithMIK
YouTube video 'Palindrome Linked List | Linked List'
Pepcoding 26 mins
Palindrome Linked List | Linked List
YouTube video 'Palindrome Linked List | Live Coding with Explanation | Leetcode - 234'
Algorithms Made Easy 11 mins
Palindrome Linked List | Live Coding with Explanation | Leetcode - 234
YouTube video 'Check if Linked List is Palindrome | Programming Interview'
Knowledge Center 12 mins
Check if Linked List is Palindrome | Programming Interview
YouTube video 'Palindrome Linked List - LeetCode 234 - Coding Interview Questions'
One Code Man 10 mins
Palindrome Linked List - LeetCode 234 - Coding Interview Questions
YouTube video '234. Palindrome Linked List || Java || Leetcode || Hindi'
Coding Sphere 7 mins
234. Palindrome Linked List || Java || Leetcode || Hindi
YouTube video 'Palindrome Linked List | LeetCode 234 | C++, Java, Python'
Knowledge Center 24 mins
Palindrome Linked List | LeetCode 234 | C++, Java, Python
YouTube video 'Palindrome Linked List | Leetcode 234 | Linked List'
Ayushi Sharma 11 mins
Palindrome Linked List | Leetcode 234 | Linked List
YouTube video 'Leetcode | 234. Palindrome Linked List | Easy | Java Solution'
Developer Docs 6 mins
Leetcode | 234. Palindrome Linked List | Easy | Java Solution
YouTube video '[Java] Leetcode 234. Palindrome Linked List [Fast & Slow Pointers #4]'
Eric Programming 10 mins
[Java] Leetcode 234. Palindrome Linked List [Fast & Slow Pointers #4]
YouTube video '234. Palindrome Linked List | leetcode daily challenge | DSA | Shashwat Tiwari Hindi'
ShashCode 15 mins
234. Palindrome Linked List | leetcode daily challenge | DSA | Shashwat Tiwari Hindi
YouTube video 'LeetCode 234: Palindrome Linked List'
Engineering Digest 14 mins
LeetCode 234: Palindrome Linked List
YouTube video 'Palindrome Linked List #leetcode #linkedlist'
Deepti Talesra 13 mins
Palindrome Linked List #leetcode #linkedlist
YouTube video 'Palindrome Linked List - LeetCode 234 - JavaScript'
AlgoJS 6 mins
Palindrome Linked List - LeetCode 234 - JavaScript
YouTube video 'Palindrome Linked List | (Leetcode 234) | Meta interview question'
The Hustling Engineer 14 mins
Palindrome Linked List | (Leetcode 234) | Meta interview question
YouTube video 'Palindrome Linked List Explained in Telugu | Leetcode 234 | Python DSA Tutorial | srkcodes'
Srk Codes 10 mins
Palindrome Linked List Explained in Telugu | Leetcode 234 | Python DSA Tutorial | srkcodes
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

18 easy 43 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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