Advertisement
Home Data Structure Arrays Check if an Array is a Palindrome

Check if an Array is a Palindrome

0
Advertisement

Title: Check if an Array is a Palindrome

A palindrome reads the same forwards and backwards, and the idea applies just as well to an array of numbers as it does to a word like madam. In this guide, you’ll learn how to check whether an int array is a palindrome in Java using an efficient two-pointer approach, walk through a full trace of the algorithm, and see the edge cases and interview follow-ups that come up around this classic problem.

Understanding the Problem

An array is a palindrome when the element at index i from the start equals the element at index i from the end, for every valid i. For example, [1, 2, 3, 2, 1] is a palindrome, but [1, 2, 3, 4] is not because the first and last elements already disagree.

This problem shows up constantly in interviews because it tests whether you can reason about array indices from both ends at once, rather than just scanning left to right. The same mirrored-comparison idea also underlies palindrome checks on strings, linked lists, and even numbers.

Approach: Two-Pointer Comparison

The most efficient way to check a palindrome is to compare elements from both ends and move inward, stopping the moment a mismatch is found. This avoids building a reversed copy of the array and needs no extra memory.

  1. Initialize a pointer left at index 0 and a pointer right at index numbers.length - 1.
  2. While left is less than right, compare numbers[left] with numbers[right].
  3. If the two values are not equal, the array is not a palindrome; return false immediately.
  4. If the two values are equal, increment left and decrement right to move both pointers one step inward.
  5. Repeat the comparison until left meets or crosses right.
  6. If the loop finishes without finding a mismatch, the array is a palindrome; return true.

Java Program

Java
public class ArrayPalindromeChecker {

    public static boolean isPalindrome(int[] numbers) {
        if (numbers == null) {
            throw new IllegalArgumentException("Input array must not be null");
        }

        int left = 0;
        int right = numbers.length - 1;

        while (left < right) {
            if (numbers[left] != numbers[right]) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }

    public static void main(String[] args) {
        int[] sample = {1, 2, 3, 2, 1};
        System.out.println("Array: " + java.util.Arrays.toString(sample));
        System.out.println("Is palindrome? " + isPalindrome(sample));
    }
}

Explanation of the Program

The isPalindrome method takes an int[] array and returns a boolean. Here is what each part of the logic is doing.

  • numbers == null is checked first so the method fails fast with a clear exception instead of throwing a confusing NullPointerException later.
  • left starts at the first index and right starts at the last index, so they represent the two ends of the array that need to mirror each other.
  • The while (left < right) condition stops the loop once the pointers meet or cross, which means every pair has already been checked.
  • Inside the loop, numbers[left] != numbers[right] is the only branch that can end the search early, returning false the instant symmetry breaks.
  • When a pair matches, left++ and right-- shrink the window being checked, moving one step closer to the center on each iteration.

Step-by-Step Trace

Let’s trace isPalindrome on the array [5, 2, 9, 4, 7, 9, 2, 5], which is not a palindrome because the middle pair, 4 and 7, does not match.

Iterationnumbers[left]numbers[right]Equal?Action
155yesleft++, right–
222yesleft++, right–
399yesleft++, right–
447noreturn false

At the end of each successful iteration, every pair checked so far mirrors correctly around the array’s center, and the loop exits the instant a pair breaks that symmetry, which is exactly what happens at iteration 4.

Examples

Let’s look at a few concrete examples to see the method in practice, including the edge case of an array with only one element.

Example 1: Odd-Length Palindrome

An odd-length array has a middle element that pairs with itself, which the left < right condition naturally skips.

Java
int[] numbers = {1, 2, 3, 2, 1};
System.out.println(isPalindrome(numbers));
// Output: true

Example 2: Even-Length Non-Palindrome

An even-length array has no middle element, so every position must find a matching mirror on the opposite side.

Java
int[] numbers = {10, 20, 30, 40};
System.out.println(isPalindrome(numbers));
// Output: false

Example 3: Single-Element Array

With only one element, left and right start at the same index, so the loop body never runs and the array is trivially a palindrome.

Java
int[] numbers = {7};
System.out.println(isPalindrome(numbers));
// Output: true

Common Mistakes to Avoid

These are the mistakes learners most often make when implementing this exact check.

  • Returning true inside the match branch – exits as soon as one mirrored pair happens to match, instead of continuing to check the rest. For [1, 2, 3, 2, 9] this would wrongly report a palindrome after the first comparison. Only return false inside the loop, and return true after it finishes.
  • Comparing a reversed copy with == – building a reversed array and comparing it to the original with == checks object references, not contents, so it always prints false even for identical values. Use Arrays.equals(arr1, arr2) or compare elements directly instead.
  • Forgetting to update both pointers – leaving out left++ or right-- causes an infinite loop because the same pair keeps getting compared forever. Update both pointers together on every matching iteration.
  • Using left <= right as the loop condition – redundantly re-compares the middle element of an odd-length array against itself, which still happens to work but obscures the invariant and wastes a comparison. Use left < right so the loop stops exactly when every pair has been checked.
  • Skipping the null check – calling numbers.length on a null reference throws a NullPointerException before any comparison happens. Validate the array for null first and decide what that case should mean for the caller.

Edge Cases to Test

Before calling this solved, make sure it behaves correctly on each of these inputs.

  • Empty array
  • Single-element array
  • Even-length array
  • Odd-length array
  • All identical elements
  • One mismatched pair near the center
  • Null array reference
  • Negative numbers or Integer.MIN_VALUE / Integer.MAX_VALUE present

Additional Considerations

The two-pointer approach runs in O(n) time, since each element is visited at most once, and uses O(1) extra space, since only the two index variables are needed.

A simpler but less efficient alternative builds a reversed copy of the array and compares it to the original with Arrays.equals. That approach is also O(n) in time but needs O(n) extra space for the copy, so the two-pointer version is the better default once memory matters.

Interview Follow-up Questions

These are the natural follow-ups an interviewer might ask once you’ve shown the basic solution.

  • What if the array holds objects instead of primitives? – compare with .equals() rather than ==, since == on objects checks reference identity, not value equality.
  • What if you must solve it recursively? – recurse on the subarray between left + 1 and right - 1, with the base case being left >= right, mirroring the iterative two-pointer logic one call per pair.
  • What if the array is too large to fit in memory and arrives as a stream from disk? – read a prefix buffer from the front and a suffix buffer from the back of the file independently, comparing them without ever materializing the whole array in memory.
  • What if you need the minimum number of changes to make the array a palindrome? – count the mismatched mirrored pairs; that count is exactly the minimum number of single-element changes required.

Conclusion

Checking whether an array is a palindrome comes down to comparing mirrored pairs from both ends and stopping at the first mismatch, which gives an O(n) time, O(1) space solution. Try adapting isPalindrome to work on a char[] or a List<Integer> to see how the same two-pointer idea transfers to other data types.

You can learn more Array-based problems and patterns like this one in the Arrays category on DailyJavaConcept.