A Python utility that identifies the index of a character whose removal converts a string into a palindrome.
https://github.com/davidbmar/Palindrome-Index · public · shipped
A command-line script that solves the 'Palindrome Index' algorithmic problem. It accepts a series of lowercase strings and determines if they are already palindromes or if removing a single specific character makes them one. It returns the zero-based index of the removable character, or -1 if the string is already a palindrome.
python palindromeIndex.py
flowchart TD
A[Start] --> B[Read Input Integer T]
B --> C{Loop T times}
C -->|Next String S| D[Check isPalindrome(S)]
D -->|True| E[Print -1]
D -->|False| F[Find Mismatch Index i]
F --> G[Test Remove S[i]]
G -->|Is Palindrome| H[Print i]
G -->|Not Palindrome| I[Test Remove S[len-1-i]]
I -->|Is Palindrome| J[Print len-1-i]
E --> K{More Cases?}
H --> K
J --> K
K -->|Yes| C
K -->|No| L[End]
The solution is implemented in a single Python file (`palindromeIndex.py`). It uses a two-pointer approach implicitly by comparing the string with its reverse. When a mismatch is found at index `i`, it tests two hypotheses: removing the character at `i` from the original string, or removing the corresponding character from the end (index `len(s)-1-i`). It validates these hypotheses by checking if the resulting substrings are palindromes.
sequenceDiagram
participant User
participant Main as palindromeIndex.py
participant Logic as palindromeIndex()
participant Helper as isPalindrome()
User->>Main: Provide Input (T, Strings)
loop For each string S
Main->>Logic: palindromeIndex(S)
Logic->>Helper: isPalindrome(S)
alt S is Palindrome
Helper-->>Logic: True (1)
Logic-->>Main: Return -1
else S is Not Palindrome
Helper-->>Logic: False (0)
Logic->>Logic: Find first mismatch i
Logic->>Helper: isPalindrome(S without i)
alt Substring is Palindrome
Helper-->>Logic: True
Logic-->>Main: Return i
else Substring is Not Palindrome
Helper-->>Logic: False
Logic->>Helper: isPalindrome(S without mirror i)
Helper-->>Logic: True
Logic-->>Main: Return mirror index
end
end
Main->>User: Print Result
end
This code serves as a reference implementation for string manipulation algorithms, specifically for interview preparation involving palindromes and greedy approaches. It demonstrates basic string slicing, reversal, and iterative comparison logic in Python 2/3 compatible syntax.
✓ all on main — nothing unmerged.