Skip to content

234: Palindrome Linked List #56

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions LeetCode/linked_list_is_palidrome.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# 234. Palindrome Linked List
from typing import Optional, List


# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next


class Solution:
def reverse_linked_list(self, head: Optional[ListNode]):
pass

def isPalindrome(self, head: Optional[ListNode]) -> bool:
pass

def is_palindrome_str(self, head: Optional[ListNode]) -> bool:
current = head
temp_str = ""
while current is not None:
temp_str += str(current.val)
current = current.next
return temp_str == temp_str[::-1]

def insert_from_list(
self, head: Optional[ListNode], values: List[int]
) -> Optional[ListNode]:
if not values:
return None

head.val = values[0]
current = head
for value in values[1:]:
current.next = ListNode(value)
current = current.next

return head

def print_linked_list(self, head: Optional[ListNode]):
current = head
while current is not None:
print(current.val, end=" => " if current.next else " \n")
current = current.next


values = [1, 2, 2, 1]
head = ListNode() # Initialize an empty node to serve as the head
head = Solution().insert_from_list(head=head, values=values)
Solution().print_linked_list(head=head)
print(Solution().is_palindrome_str(head=head))
# Expected Output: 1 -> 2 -> 2 -> 1
21 changes: 21 additions & 0 deletions recap/palindrome.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Python3 program to check if a number is Palindrome

# Function to check Palindrome
def check_palindrome(n):
reverse = 0
# Copy of the original number so that the original
# number remains unchanged while finding the reverse
temp = n
while temp != 0:
reverse = reverse * 10 + temp % 10
temp = temp // 10
# If reverse is equal to the original number, the
# number is palindrome
return reverse == n

# Sample Input
n = -121
if check_palindrome(n):
print("Yes")
else:
print("No")
13 changes: 13 additions & 0 deletions tests/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from typing import List
from LeetCode.is_palindrome_linked_list import ListNode

# Helper function to convert list to linked list (for easy setup in test cases)
def list_to_linked_list(arr: List[int]):
if not arr:
return None
head = ListNode(arr[0])
current = head
for value in arr[1:]:
current.next = ListNode(value)
current = current.next
return head
43 changes: 40 additions & 3 deletions tests/test_leetcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ def test_chalk_replacer(chalk, k, expected):
assert solution.chalkReplacer(chalk, k) == expected


@pytest.mark.parametrize("string_val, repeat, expected", [("leetcode", 2, 6), ("iiii", 1, 36)])
@pytest.mark.parametrize(
"string_val, repeat, expected", [("leetcode", 2, 6), ("iiii", 1, 36)]
)
def test_sum_of_digit_1945(string_val, repeat, expected):
from LeetCode.sum_of_string_digit_1945 import Solution

Expand Down Expand Up @@ -79,10 +81,18 @@ def test_length_of_longest_substring(s: str, expected: int):
@pytest.mark.parametrize(
"s1, s2, expected",
[
("this apple is sweet", "this apple is sour", ["sweet", "sour"]), # uncommon words are "sweet" and "sour"
(
"this apple is sweet",
"this apple is sour",
["sweet", "sour"],
), # uncommon words are "sweet" and "sour"
("apple apple", "banana", ["banana"]), # "banana" is the only uncommon word
("apple", "apple", []), # no uncommon words, both sentences have "apple"
("the quick", "brown fox", ["the", "quick", "brown", "fox"]), # all words are uncommon
(
"the quick",
"brown fox",
["the", "quick", "brown", "fox"],
), # all words are uncommon
("", "fox", ["fox"]), # one sentence is empty, uncommon is "fox"
("hello world", "", ["hello", "world"]), # second sentence is empty
("a b c", "a b", ["c"]), # "c" is the only uncommon word
Expand All @@ -93,3 +103,30 @@ def test_uncommon_from_sentences(s1: str, s2: str, expected: List[str]):

solution = Solution()
assert sorted(solution.uncommonFromSentences(s1, s2)) == sorted(expected)


def test_is_palindrome(self):
from LeetCode.is_palindrome_linked_list import Solution
from .helpers import list_to_linked_list

solution = Solution()

# Test case 1: Palindrome [1, 2, 2, 1] -> True
l1 = list_to_linked_list([1, 2, 2, 1])
assert solution.isPalindrome(l1) == True, "Test case 1 failed"

# Test case 2: Not a palindrome [1, 2] -> False
l1 = list_to_linked_list([1, 2])
assert solution.isPalindrome(l1) == False, "Test case 2 failed"

# Test case 3: Single element [1] -> True
l1 = list_to_linked_list([1])
assert solution.isPalindrome(l1) == True, "Test case 3 failed"

# Test case 4: Empty list -> True (Assume empty list as a palindrome)
l1 = list_to_linked_list([])
assert solution.isPalindrome(l1) == True, "Test case 4 failed"

# Test case 5: Palindrome [1, 0, 1] -> True
l1 = list_to_linked_list([1, 0, 1])
assert solution.isPalindrome(l1) == True, "Test case 5 failed"
Loading