Java 2ms with comments, beats 100% submissions, O(N) time, O(1) space
\nclass Solution {\n    public int minimumDistance(String word) {\n        int[] keys = new int[word.length()];\n        for (int i = 0; i < word.length(); i++)
```\nclass Solution {\n    public int minimumDistance(String word) {\n        int[] keys = new int[word.length()];\n        for (int i = 0; i < word.length(); i++) keys[i] = word.charAt(i) - \'A\';\n\n        // precompute costs between all keys\n        // key 26 - is a \'finger off the keyboard\' key, cost[26][*] = 0\n        // we can only go from \'finger off\' to some other key not vice versa\n        int[][] cost = new int[27][26];\n        for (int i = 0; i < 26; i++) {\n            for (int j = i; j < 26; j++) {\n                cost[i][j] = Math.abs(i/6 - j/6) + Math.abs(i%6 - j%6);\n                cost[j][i] = cost[i][j];\n            }\n        }\n        \n        // dp[j] represents minimum dististance from current char/key till the end of the word\n        // with one finger (leading) always being at prev key and the other\n        // finger at an unknown key j prior to prev key - we try all posibile keys for j\n        int[] dp = new int[27];\n        \n        for (int i = keys.length - 1; i > 0; i--) {\n            // below var enables memory optimisation - reuse of the same 0->26 dp slots from previous iterations\n            int dp_for_key_at_i_minus_1 = dp[keys[i - 1]];\n            int cost_i_minus_1_to_i = cost[keys[i - 1]][keys[i]];\n            for (int j = 0; j < 27; j++) {\n                // lagging finger at j, leading finger at i - 1\n                // either of the two can move hence two options below\n                dp[j] = Math.min(\n                    // lagging finger moves, i.e. current leading becomes lagging, paying cost from lagging to i\n                    dp_for_key_at_i_minus_1 + cost[j][keys[i]], \n                    // leading finger moves, i.e. lagging remains lagging, paying cost from leading to i\n                    dp[j] + cost_i_minus_1_to_i);\n            }\n        }\n        \n        return dp[26];\n    }\n}\n```
[]