C++ 3D DP solution | Top Down DP | Well commented to better understand
\nclass Solution {\npublic:\n    map<int,pair<int,int>> m;  //Store postions of each character\n    int dp[300][30][30];        \n    int sum(string &s, int spo
```\nclass Solution {\npublic:\n    map<int,pair<int,int>> m;  //Store postions of each character\n    int dp[300][30][30];        \n    int sum(string &s, int spos, int i, int j)\n    {\n        // spos: position of current character we want to type\n\t\t// i: current postion of 1st finger\n\t\t// j: current postion of 2nd finger\n\t\t\n\t\t//  If we reached end of word\n\t\tif(spos==s.length())   \n            return 0;\n\t\t\n\t\t//  If we already calculated answer before\n        if(dp[spos][i][j]!=-1)   \n            return dp[spos][i][j];\n\t\t\t\n        int x=s[spos]-\'A\';    //  Current character \n\t\t\n\t\t//   Option 1: move 1st finger to current character\n        int d1=abs(m[x].first-m[i].first)+abs(m[x].second-m[i].second);  \n\t\t\n\t\t//   Option 2: move 2nd finger to current character\n        int d2=abs(m[x].first-m[j].first)+abs(m[x].second-m[j].second);  \n\t\t\n\t\t//  Take minimum of two options, store in dp table and return\n        return dp[spos][i][j]=min(d1+sum(s,spos+1,x,j),d2+sum(s,spos+1,i,x));  \n    }\n    int minimumDistance(string word)\n    {\n        //   Storing coordinates of each character\n\t\tfor(int i=0;i<26;i++)\n            m[i]={i/6,i%6}; \n\t\t\n\t\t//   DP table initialization\n        memset(dp,-1,sizeof(dp));\n\t\t\n        //   Initialize answer\n\t\tint curr=1e9;\n\t\t\n\t\t//   It is always optimal to have first hand on first character and loop for all possible positions of 2nd hand and take the minimum of those possible postions\n        for(int i=0;i<26;i++)\n            curr=min(curr,sum(word,0,word[0]-\'A\',i));   \n        return curr;   \n    }\n};\n```
[]