◻️234. Palindrome Linked List (easy)
Given the head of a singly linked list, return true if it is a
palindrome or false otherwise.
Example 1:

Input: head = [1,2,2,1]
Output: trueExample 2:

Input: head = [1,2]
Output: falseSolutions
Normal - Linked List 2 Pointers
Runtime 7 ms Memory 7.45 MB
class Solution {
public:
bool isHappy(int n) {
int slow=n, fast=n;
slow = square_fn(slow);
fast = square_fn(square_fn(fast));
cout << "slow: " << slow << " fast: " << fast << endl;
while(slow != fast){
slow = square_fn(slow);
fast = square_fn(square_fn(fast));
cout << "slow: " << slow << " fast: " << fast << endl;
if(slow == fast){
if(slow == 1) return(true);
else return(false);
}
}
return(true);
}
private:
int square_fn(int n){
int sum = 0;
while(n != 0){
sum += pow(n%10, 2);
n = n/10;
}
return sum;
}
};Optimised - HashSet
Runtime 5 ms Memory 8.22 MB
T.C -> O(1) | S.C -> O(1)
Last updated