Deque Palindrome Check
Given an array representing a deque (double-ended queue), determine whether the sequence of elements forms a palindrome — meaning it reads the same forward and backward. Return true if it is a palindrome, false otherwise.
For example, [1, 2, 2, 1] is a palindrome. [1, 2] is not. An empty deque or a single-element deque is always a palindrome. [1, 2, 3, 2, 1] is also a palindrome.
Checking a palindrome using a deque is a classic application of the double-ended queue. Because a deque allows access to both ends, you can compare the front and back elements, removing them simultaneously. If any pair mismatches, it is not a palindrome. This approach is more natural for a deque than using two pointers, because the deque itself manages the endpoints.
In array-based deque implementations, this is equivalent to the two-pointer technique: compare arr[i] with arr[j] where i starts at 0 and j at length-1, moving inward. The deque's ability to pop from both ends makes this operation intuitive and clean.
Edge cases include an empty deque (return true), a single element (return true), even-length palindromes [1, 1] (true), and near-palindromes where only the middle differs [1, 2, 3] (false).
Example Input & Output
Empty
Palindrome
Even length palindrome
Not palindrome
Single element
Algorithm Flow
Solution Approach
Use two pointers at both ends to compare elements moving inward.
Initialize i at the front (0) and j at the back (length-1). Loop while i < j, comparing elements at each position. If any pair differs, return false. If all pairs match, return true. This works for both odd and even length arrays.
Time complexity is O(n) with n being the array length, space complexity is O(1).
Best Answers
class Solution {
public boolean solution(int[] nums) {
int l=0,r=nums.length-1;while(l<r){if(nums[l]!=nums[r])return false;l++;r--;}return true;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
