Palindrome Index (Hackerrank)
Here we have another Hackerrank question on String manipulation, this one involving the classic Palindrome index.
Question-
Approach - Pretty simple, we just need to check values one by one, iterating a loop from index 0 being compared to index n, where n is the last value in the index, narrowing it down to inner values one by one.
The point where the elements do not stay equal is the point where element needs to be removed in order to make the string into a palindrome
The steps are -
- initialise i = 0; j= string.length()-1 //last value in the string
- Run a loop from i to middle of the string, i increments while j decrements, bringing us a section to focus on within the string
- Run an if condition which checks whether character at i is equal to j or not
- If it is not equal, we check if the element after character at i is equal to j or not
- If yes, we check whether the element before j is equal to character at i and character after i is subsequently equal to element at 2 places before character at j,
- In short we define whether the values ahead and after the character with fault match the palindrome or not, if they do-> we return index j as point of failure
- Else we return i as point of failure, further if last character is equal to the first character, we return index j,
- For all other cases we return -1
Code-