Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if all elements of the array are palindrome or not in Python
A palindrome array is an array that reads the same forwards and backwards. In Python, we can check if an array is a palindrome by comparing elements from both ends moving towards the center.
So, if the input is like nums = [10, 12, 15, 12, 10], then the output will be True because the array reads the same from left to right and right to left.
Algorithm
To solve this, we will follow these steps ?
- Get the size of the array
- Use a flag variable to track palindrome status
- Compare elements from start and end moving towards center
- If any pair doesn't match, it's not a palindrome
- Return the result
Using While Loop
Here's the step-by-step implementation using a while loop ?
def solve(nums):
n = len(nums)
is_palindrome = 0
i = 0
while i <= n // 2 and n != 0:
if nums[i] != nums[n - i - 1]:
is_palindrome = 1
break
i += 1
if is_palindrome == 1:
return False
else:
return True
nums = [10, 12, 15, 12, 10]
print(solve(nums))
True
Using Simple Comparison
A more Pythonic approach is to compare the array with its reverse ?
def is_palindrome_simple(nums):
return nums == nums[::-1]
# Test with palindrome array
nums1 = [10, 12, 15, 12, 10]
print(f"Array {nums1} is palindrome: {is_palindrome_simple(nums1)}")
# Test with non-palindrome array
nums2 = [1, 2, 3, 4, 5]
print(f"Array {nums2} is palindrome: {is_palindrome_simple(nums2)}")
Array [10, 12, 15, 12, 10] is palindrome: True Array [1, 2, 3, 4, 5] is palindrome: False
Using Two Pointers
An efficient approach using two pointers from both ends ?
def is_palindrome_two_pointers(nums):
left, right = 0, len(nums) - 1
while left < right:
if nums[left] != nums[right]:
return False
left += 1
right -= 1
return True
# Test examples
test_arrays = [
[10, 12, 15, 12, 10],
[1, 2, 2, 1],
[5],
[1, 2, 3],
[]
]
for arr in test_arrays:
result = is_palindrome_two_pointers(arr)
print(f"Array {arr} is palindrome: {result}")
Array [10, 12, 15, 12, 10] is palindrome: True Array [1, 2, 2, 1] is palindrome: True Array [5] is palindrome: True Array [1, 2, 3] is palindrome: False Array [] is palindrome: True
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| While Loop | O(n) | O(1) | Medium |
| Array Slicing | O(n) | O(n) | High |
| Two Pointers | O(n) | O(1) | High |
Conclusion
Use the two-pointer approach for optimal space efficiency, or array slicing for the most readable code. All methods effectively determine if an array is a palindrome by comparing elements symmetrically.
