Palindrome Linked List
Easy linked-list · two-pointers
Description
Constraints
0 <= n <= 100000
Examples
Input: list = [1,2,2,1]
Output: true
Hints (1)
- Find the middle, reverse the second half and compare.
Solutions
Two pointers inward. · Time O(n) · Space O(1)
func isPalindromeList(list []int) bool {
for i, j := 0, len(list)-1; i < j; i, j = i+1, j-1 {
if list[i] != list[j] {
return false
}
}
return true
}
Two pointers inward. · Time O(n) · Space O(1)
function isPalindromeList(list) {
let i = 0, j = list.length - 1;
while (i < j) { if (list[i++] !== list[j--]) return false; }
return true;
}
Compare with the reverse. · Time O(n) · Space O(n)
function isPalindromeList($list) {
return $list === array_reverse($list);
}
Compare with the reverse. · Time O(n) · Space O(n)
def isPalindromeList(list):
return list == list[::-1]
Two pointers inward. · Time O(n) · Space O(1)
function isPalindromeList(list: number[]): boolean {
let i = 0, j = list.length - 1;
while (i < j) { if (list[i++] !== list[j--]) return false; }
return true;
}
Create a free account to submit solutions, track progress and save problems.
Create account