The Love-Letter Mystery

  • + 0 comments

    My Java solution:

    public static int theLoveLetterMystery(String s) {
            //goal: find min operations req to convert string s into a palindrome
            //o(n) time, o(1) space
            if(s.length() == 1) return 0; //len of 1 is always palindromic
            
            int minOperations = 0;
            int left = 0, right = s.length() - 1;
            //use a left pointer at the start and a right pointer at the end to process both ends of str
            while(left < right){
                char leftChar = s.charAt(left);
                char rightChar = s.charAt(right);
                //if char at left is < right, reduce right
                if(leftChar < rightChar){
                    minOperations += rightChar - leftChar;
                }
                //if char at left is > right, reduce left
                else if(leftChar > rightChar){
                    minOperations += leftChar - rightChar;
                }
                left++;
                right--;            
            }
            return minOperations;
        }