HackerRank 'The Love Letter Mystery' Solution

by Srikant Padala on April 5, 2016, 6:12 am


  • Take two pointers, one a left(say i) of the middle and one on the right. The left pointer moves towards 0 and right(say j) towards n.
  • Find the absolute difference between the a[i] and a[j].
  • Return the total sum.

The Love Letter Mystery Problem Statement


#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int llMystery(string &str) {
    int s = str.size(), count=0;
    int i=s/2-1,j;
    if(s%2) j = i+2;
    else j = s/2;
    for(; i >= 0 && j < s; i--, j++) {
        count += abs(str[j] - str[i]);
    return count;
int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int T;
    cin >> T;
    string str;
    while(T--) {
        cin >> str;
        cout << llMystery(str) << endl;
    return 0;

Coming Soon.