educative.io

Heads-up: should contain also test cases where the letter to the be dropped is on the left side

It seems like all test cases have a right most extra letter to drop.
Test cases should contain also a left mot extra letter.

E.g.
“madamz” → right most extra letter
“zmadam”-> left most extra letter

A solution that I found is to run the algorithm twice and check if one of the two iteration produces a true value.

public class ValidPalindromeII {

        public static boolean isPalindrome(String s) {

            return isPalindrome(s, ValidPalindromeII.Skippable.LEFT) || isPalindrome(s, ValidPalindromeII.Skippable.RIGHT);
        }


        private static boolean isPalindrome(String s, Skippable sk) {

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

            while (left <= right) {
                while (s.charAt(left) != s.charAt(right) && left <= right) {
                    counter++;
                    if(counter > 1) {
                        return false;
                    }
                    if(sk == ValidPalindromeII.Skippable.LEFT) {
                        left++;
                    } else {
                        right--;
                    }
                }

                left++;
                right--;

            }

            return true;
        }

        enum Skippable {
            LEFT,
            RIGHT
        }
}

Anyways, I wouldn’t include this exercise in 2 pointer category.
It’s way simpler to use a hash map where when the string contains an even number of letters, the hash map size at the end should be 0, if odd it should be 1 instead.


Course: Grokking Coding Interview Patterns in Java - Learn Interactively
Lesson: https://www.educative.io/courses/grokking-coding-interview-patterns-java/qAWVrz2GkjG

Hi @Davide_Pugliese !
Thanks for your suggestion. We’ll look into this.
Happy Learning :blush:

Hello @Davide_Pugliese,

I hope you’re doing well!

Thank you for sharing your suggestion. In the code test widget, hidden cases cater to all possible test cases. Thank you for sharing the code with us. I looked into the code and found it is working fine and passing all the test cases. Great job!

As always, we appreciate our valued users reaching out to us. Therefore, please write to us if you have any further queries, concerns, or suggestions in general.

We hope you enjoy your experience with us at Educative! Happy learning!