
Problem
Solution
Submissions
Palindrome Linked List
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a C program to determine if a singly linked list is a palindrome. A palindrome is a sequence that reads the same forward and backward. For example, "racecar" is a palindrome. For a linked list, we need to check if the sequence of values from the first node to the last node reads the same as the sequence from the last node to the first node.
Example 1
- Input: head = [1,2,2,1]
- Output: true
- Explanation:
- Step 1: The linked list contains values [1,2,2,1]
- Step 2: Reading from left to right: 1 -> 2 -> 2 -> 1
- Step 3: Reading from right to left: 1 -> 2 -> 2 -> 1
- Step 4: Both sequences are identical
- Step 5: Therefore, the linked list is a palindrome
Example 2
- Input: head = [1,2]
- Output: false
- Explanation:
- Step 1: The linked list contains values [1,2]
- Step 2: Reading from left to right: 1 -> 2
- Step 3: Reading from right to left: 2 -> 1
- Step 4: The sequences are different
- Step 5: Therefore, the linked list is not a palindrome
Constraints
- The number of nodes in the list is in the range [1, 10^5]
- 0 <= Node.val <= 9
- Time Complexity: O(n) where n is the number of nodes in the linked list
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- A naive approach would be to copy all values into an array and check if the array is a palindrome, but that would require O(n) extra space
- To achieve O(1) space complexity, consider modifying the list structure temporarily
- Find the middle of the linked list using slow and fast pointers
- Reverse the second half of the linked list
- Compare the first half with the reversed second half
- Optionally, restore the list to its original structure