This project implements the "Two Pointers" algorithm to verify if a character array is a palindrome. It avoids creating additional memory structures by comparing elements from the start and end of the array, progressively moving toward the center.
Manually verify a palindrome by iterating from edges to the center.
Requirements:
- No secondary array (Space complexity: $O(1)$).
- Use two pointer variables:
left(start) andright(end). - Compare values at these pointers within a
whileloop. - If values match: increment
left, decrementright. - If values mismatch: set
isPalindrometofalseandbreak. - Handle both even and odd length arrays correctly.
- Two-Pointer Strategy: An optimized approach that validates symmetry without array reversal.
- Short-Circuit Termination: Utilizing the
breakstatement for immediate execution halt upon detecting a mismatch.
-
The "Meeting Point": For an array of size
$n$ , the pointers will either cross (even length) or meet at the exact center index (odd length). -
Index Safety: The loop terminates naturally when the
rightpointer becomes smaller than theleftpointer, preventing anyArrayIndexOutOfBoundsException.
Array to check: [a, b, c, b, a]
Is it a palindrome? true
Project Structure:
src/com/yurii/pavlenko/
└── EdgeToCenterPalindrome.java # Main Entry Point & Logic
Code
package com.yurii.pavlenko;
import java.util.Arrays;
public class EdgeToCenterPalindrome {
public static void main(String[] args) {
char[] original = {'a', 'b', 'c', 'b', 'a'};
int left = 0;
int right = original.length - 1;
boolean isPalindrome = true;
while (left <= right) {
if (original[left] == original[right]) {
left++;
right--;
} else {
isPalindrome = false;
break;
}
}
System.out.println("Array to check: " + Arrays.toString(original));
System.out.println("Is it a palindrome? " + isPalindrome);
}
}This project is licensed under the MIT License.
Copyright (c) 2026 Yurii Pavlenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
License: MIT