Advertisement

Valid Palindrome - LeetCode 125 Solution

Valid Palindrome - Complete Solution Guide

Valid Palindrome is LeetCode problem 125, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s , return true if it is a palindrome , or false otherwise . Example 1: Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome. Example 2: Input: s = "race a car" Output: false Explanation: "raceacar"

Detailed Explanation

The "Valid Palindrome" problem isn't just a straightforward check for reading the same forwards and backwards; it introduces a crucial pre-processing step that's central to its definition. Before we even begin comparing characters, we must first clean up the input string `s`. This involves two specific transformations: eliminating any characters that aren't letters or numbers (like spaces, punctuation, or symbols), and then converting all remaining letters to lowercase. Only after this meticulous sanitization process can we actually determine if the resulting sequence is a palindrome.

Solution Approach

The provided solution elegantly breaks down the problem into two distinct and manageable phases. The first phase focuses entirely on normalization: it iterates through the original input string `s`, character by character. For each character, it first checks if it's alphanumeric using `ch.isalnum()`. If it passes this test, the character is then converted to lowercase with `ch.lower()` and appended to a `new_string`. This `new_string` becomes the definitive, cleaned-up representation that perfectly aligns with the problem's criteria for a palindrome check.

Step-by-Step Algorithm

  1. Step 1: Create a new string containing only the alphanumeric characters from the input string, converting all characters to lowercase.
  2. Step 2: Initialize two pointers, `left` and `right`, to the start and end of the new string, respectively.
  3. Step 3: Iterate while `left` is less than `right`. In each iteration, compare the characters at `left` and `right`.
  4. Step 4: If the characters are different, return `false`. Otherwise, increment `left` and decrement `right`.
  5. Step 5: If the loop completes without finding a mismatch, return `true`.

Key Insights

  • **Decoupling Normalization and Comparison:** The solution brilliantly separates the concerns of string preparation (filtering non-alphanumeric characters and lowercasing) from the actual palindrome verification. This makes the code modular, easier to understand, and less prone to errors, as each step addresses a single, well-defined part of the problem.
  • **Efficient Two-Pointer Symmetry Check:** Once the `new_string` is constructed, the classic two-pointer technique is employed. By using one pointer starting at the beginning (`l`) and another at the end (`r`), we can efficiently compare characters symmetrically inwards. This avoids the need to explicitly reverse the string (which would involve creating another full string copy) and allows for an in-place comparison, halting immediately upon the first mismatch.
  • **Leveraging Python's Expressive Built-ins:** Python's built-in string methods like `isalnum()` and `lower()`, combined with a generator expression and `''.join(...)`, provide an exceptionally concise and readable way to perform the string normalization. This approach expresses the intent of filtering and transforming characters very clearly without requiring verbose manual character-by-character loops for the initial cleanup.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(n)

Topics

This problem involves: Two Pointers, String.

Companies

Asked at: Accenture, American Express, Axon, Bank of America, Cadence, Capgemini, Cisco, EPAM Systems, Infosys, Intel, RBC, SAP, ServiceNow, Shopee, Spotify, TikTok, Tinkoff, Toast, Turing, Uber, VK, Visa, Wayfair, Wipro, Yahoo, Yandex, Zenefits.