The Love-Letter Mystery

Sort by

recency

|

985 Discussions

|

  • + 0 comments

    Here is a python solution in O(n) time and O(1) space:

    def theLoveLetterMystery(s):
        letters = "abcdefghijklmnopqrstuvwxyz"
        
        i = 0
        j = len(s) - 1
        
        change_count = 0
        
        while i < j:
            if s[i] == s[j]:
                i += 1
                j -= 1
            else:
                idx_i = letters.index(s[i])
                idx_j = letters.index(s[j])
                temp_count = abs(idx_j - idx_i)
                
                change_count += temp_count
                i += 1
                j -= 1
            
        return change_count
    
  • + 0 comments

    C++

    int theLoveLetterMystery(string s)
    {
        int count{0};
        for (int i = s.length() - 1; i >= s.length() / 2; i--)
            count += abs(s[i] - s[s.length() - 1 - i]);
            
        return count;
    }
    
  • + 0 comments

    Java:

    public static int theLoveLetterMystery(String s) {
        int left = 0;
        int right = s.length() - 1;
        int retVal = 0;
        while (left < right) {
            if (s.charAt(left) != s.charAt(right)) {
                retVal += Math.abs((int) s.charAt(right) - (int) s.charAt(left));
            }
            ++left;
            --right;
        }
        return retVal;
    }
    
  • + 0 comments

    Here is my c++ solution to the problem, explanation here : https://youtu.be/gIUqS2xO6lg

    int theLoveLetterMystery(string s) {
        int ans = 0 , start = 0, end = s.size() - 1;
        while(start < end){
            ans += abs(s[start] - s[end]);
            start++; end--;
        }
        return ans;
    }
    
  • + 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;
        }