Saturday, 3 January 2026

Check if a String is Palindrome (Java)

Check if a String is Palindrome (Java)

In this post, we will learn how to check whether a given string is a palindrome using Java. We will solve the problem using two different techniques and handle multiple input strings.


What is a Palindrome?

A string is called a palindrome if it reads the same forward and backward.

Examples:

ABCBA  → Palindrome
MADAM  → Palindrome
HELLO  → Not a Palindrome

Approaches Used

  • Naive Approach: Reverse the string and compare
  • Efficient Approach: Two Pointer Technique

Java Code Implementation


public class StringPalindrome {

    public static void main(String[] args) {

        String[] inputs = {"ABCBA", "MADAM", "HELLO", "LEVEL"};

        for (String str : inputs) {
            System.out.println("String: " + str);
            System.out.println("Naive Check: " + isPalindromeNaive(str));
            System.out.println("Efficient Check: " + isPalindromeEfficient(str));
            System.out.println();
        }
    }

    // Naive approach using reverse
    private static boolean isPalindromeNaive(String str) {
        StringBuilder reverse = new StringBuilder(str);
        reverse.reverse();
        return str.equals(reverse.toString());
    }

    // Efficient approach using two pointers
    private static boolean isPalindromeEfficient(String str) {

        int left = 0;
        int right = str.length() - 1;

        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}


Explanation

1. Naive Approach (Reverse String)

  • Reverse the given string
  • Compare it with the original string
  • If both are equal, the string is a palindrome

Technique Used: String Reversal


2. Efficient Approach (Two Pointer Technique)

  • Initialize two pointers: one at the start and one at the end
  • Compare characters at both pointers
  • Move pointers inward until they cross
  • If all characters match, it is a palindrome

Technique Used: Two Pointer Technique


Sample Output

String: ABCBA
Naive Check: true
Efficient Check: true

String: MADAM
Naive Check: true
Efficient Check: true

String: HELLO
Naive Check: false
Efficient Check: false

Time & Space Complexity

Approach Time Complexity Space Complexity
Naive O(n) O(n)
Efficient O(n) O(1)

Interview Tip

In interviews, the Two Pointer Technique is preferred because it uses constant extra space and is more efficient.


Category: Strings
Difficulty: Easy
Technique: Two Pointers

No comments:

Post a Comment