The Love-Letter Mystery – HackerRank Solution

In this post, we will solve The Love-Letter Mystery HackerRank Solution. This problem (The Love-Letter Mystery) is a part of HackerRank Problem Solving series.

Solution – The Love-Letter Mystery – HackerRank Solution

C++

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        string str;
        cin >> str;
        int len = (int)str.size(), ans = 0;
        for (int i = 0, j = len - 1; i < j; i++, j--)
            ans += abs((int)str[i] - (int)str[j]);
        cout << ans << endl;
    }
    return 0;
}

Python

#!/bin/python3

import sys

def theLoveLetterMystery(s):
    string = list(s)
    res = 0
    first = []
    second = []
    
    if len(string) % 2 == 1:
        first = list(map(lambda x: ord(x), string[:len(string)//2]))
        first = first[::-1]
        second = list(map(lambda x: ord(x), string[len(string)//2 + 1:]))
    else:
        first = list(map(lambda x: ord(x), string[:len(string)//2 - 1]))
        first = first[::-1]
        second = list(map(lambda x: ord(x), string[len(string)//2 + 1:]))
        res = abs(ord(string[len(string)//2 - 1]) - ord(string[len(string)//2]))
        
    for ind in range(len(first)):
        if first[ind] != second[ind]:
            res += abs(first[ind] - second[ind])
            first[ind] = min(first[ind], second[ind])
            second[ind] = first[ind]
            
    return res
        
        

q = int(input().strip())
for a0 in range(q):
    s = input().strip()
    result = theLoveLetterMystery(s)
    print(result)

Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    static int theLoveLetterMystery(String s){
        int counter = 0;
        int i = 0;
        int j = s.length() - 1;

        while (i <= j) {
            if (s.charAt(i) != s.charAt(j)) {
                counter += Math.abs(((int) s.charAt(i)) - ((int) s.charAt(j)));
            }
            i++; j--;
        }

        return counter;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int q = in.nextInt();
        for(int a0 = 0; a0 < q; a0++){
            String s = in.next();
            int result = theLoveLetterMystery(s);
            System.out.println(result);
        }
    }
}

Note: This problem (The Love-Letter Mystery) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *