The Love-Letter Mystery

  • + 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