Typing Distance | HackerRank  solution


mostly asked the question in software developer intern role at hackerrank


Language C++ : 


map<char, pair<int, int>> keyboardLayout = {

    {'A', {0, 0}}, {'B', {1, 1}}, {'C', {2, 1}}, {'D', {3, 0}}, {'E', {4, 0}},

    {'F', {5, 0}}, {'G', {6, 0}}, {'H', {7, 1}}, {'I', {8, 1}},

    {'J', {9, 1}}, {'K', {10, 1}}, {'L', {11, 1}}, {'M', {12, 0}}, {'N', {11, 0}},

    {'O', {9, 0}}, {'P', {10, 0}}, {'Q', {3, 1}}, {'R', {4, 1}}, {'S', {5, 1}},

    {'T', {6, 1}}, {'U', {7, 0}}, {'V', {8, 0}}, {'W', {4, 2}}, {'X', {5, 2}},

    {'Y', {6, 2}}, {'Z', {7, 2}}

};


int getDistance(string word) {

    int totalDistance = 0;

    int currentRow = 0;

    int currentCol = 0;


    for (char c : word) {

        pair<int, int> keyPosition = keyboardLayout[c];

        int newRow = keyPosition.first;

        int newCol = keyPosition.second;


        totalDistance += abs(newRow - currentRow) + abs(newCol - currentCol);

        currentRow = newRow;

        currentCol = newCol;

    }


    return totalDistance;

};



Hackerrank software engineer intern Online Coding Test | solution

thanks.

1 comment: