easyString ProblemsJava

Check Whether a Sentence Is a Palindrome Ignoring Spaces and Case

Return whether a sentence is a palindrome when spaces, punctuation and case are ignored.

Quick Answer

Use two pointers from both ends. Skip any character that is not a letter or digit, and lowercase the rest before comparing. If a mismatch appears, it is not a palindrome; if the pointers cross cleanly, it is. This checks the sentence in O(n) time and O(1) extra space.

Problem Statement

Given a sentence, determine whether it is a palindrome when you ignore spaces, punctuation, and letter case. Only letters and digits are compared, and uppercase and lowercase are treated as equal.

For example, "Was it a car or a cat I saw" is a palindrome once spaces and case are ignored, while "Hello World" is not.

Input: A string sentence.

Output: A boolean: true if it is a palindrome under the given rules, false otherwise.

Examples

Example 1
Input:  "Was it a car or a cat I saw"
Output: true

Ignoring spaces and case gives wasitacaroracatisaw, which reads the same both ways.

Example 2
Input:  "Hello World"
Output: false

The alphanumeric sequence helloworld is not the same reversed.

Constraints

  • 0 <= sentence.length() <= 10^6
  • Ignore non-alphanumeric characters; compare case-insensitively

Think Before You Code

Reveal the questions to ask yourself first
  • How do you decide whether a character should be compared or skipped?
  • How can you compare letters without letting case cause a false mismatch?
  • Can you skip unwanted characters while comparing, or must you clean the string first?

Hints

Open them one at a time — try after each before revealing the next.

Hint 1
Only letters and digits matter; `Character.isLetterOrDigit` tells you which characters to keep.
Hint 2
Lowercase each kept character with `Character.toLowerCase` before comparing the two ends.
Hint 3
Advance the `left` pointer past skippable characters and pull `right` back the same way, then compare.

Approach

Reveal the step-by-step approach

Two pointers that skip non-alphanumeric characters as they go.

  1. Set left = 0 and right = length - 1.
  2. While left < right:
    • Move left forward while s.charAt(left) is not a letter or digit.
    • Move right backward while s.charAt(right) is not a letter or digit.
    • If left < right, compare the lowercased characters; if they differ, return false. Then step both pointers inward.
  3. If the scan finishes with no mismatch, return true.

Skipping inline avoids allocating a cleaned copy of the string.

Dry Run

Walk through the example step by step

Checking "Hello World" (only letters count, lowercased):

left | right | s[left] | s[right] | compare (lower)   | result
-----+-------+---------+----------+-------------------+-------
0    | 10    | H       | d        | 'h' vs 'd'        | mismatch -> false

The first compared pair already differs, so the answer is false.

Solution

Reveal the full Java solution
public class SentencePalindrome {
    public static boolean isPalindrome(String s) {
        int left = 0;
        int right = s.length() - 1;
        while (left < right) {
            while (left < right && !Character.isLetterOrDigit(s.charAt(left))) {
                left++;
            }
            while (left < right && !Character.isLetterOrDigit(s.charAt(right))) {
                right--;
            }
            if (left < right) {
                char a = Character.toLowerCase(s.charAt(left));
                char b = Character.toLowerCase(s.charAt(right));
                if (a != b) {
                    return false;
                }
                left++;
                right--;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isPalindrome("Was it a car or a cat I saw")); // true
        System.out.println(isPalindrome("Hello World"));                  // false
    }
}

The inner while loops move the pointers past any character that should not take part in the comparison, so only letters and digits are ever matched. Folding each character to lowercase before comparing makes the check case-insensitive. Because each pointer only moves inward, every character is visited at most once, keeping it O(n) time and O(1) extra space.

Time: O(n)Space: O(1)

Common Mistakes

  • Forgetting to re-check `left < right` inside the skip loops, which can read past the pointers.
  • Comparing without lowercasing, so 'A' and 'a' are wrongly treated as different.

Edge Cases to Test

  • A string of only spaces or punctuation is a palindrome (no letters to compare).
  • An empty string is a palindrome.
  • Mixed case like "RaceCar" is a palindrome once folded to lowercase.

Interview Follow-Ups

  • How would you also treat accented letters as their base letters?
  • How would you first build a cleaned string and then reuse the simple palindrome check?
  • How would you handle Unicode code points beyond the basic multilingual plane?

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Explore the Java Full Stack program →
Chat with us