Palindrome Check with a Deque
Problem
Print true if the array reads the same from the left and from the right, else false. Use a double-ended queue: look at its two ends and remove them together.
Constraints
- 1 <= n <= 10^5
Examples
Input
5 1 2 3 2 1
Output
true
Solutions
A deque lets us remove from both ends in O(1). Each round checks one matching pair. After n / 2 rounds the answer is clear.
/*
* Problem : Palindrome array.
* Input : n, then n integers.
* Output : true or false.
* Approach: Deque.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static boolean solve(int[] a) {
// Step 1: Put all numbers in a deque. Compare and remove the front and the back until at most one number is left.
java.util.ArrayDeque<Integer> deque = new java.util.ArrayDeque<Integer>();
for (int value : a) {
deque.addLast(value);
}
while (deque.size() > 1) {
if (!deque.pollFirst().equals(deque.pollLast())) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(solve(a));
}
}
Hints (2)
- What is left when n is odd?
- Why compare after removing both ends?