Java - Simple recursion with memoization.
Intuition\nSometimes, just try to simulate the question using recursion.\n\n# Approach\nWe can either use first finger or second figer, so try both in recursion
# Intuition\nSometimes, just try to simulate the question using recursion.\n\n# Approach\nWe can either use first finger or second figer, so try both in recursion, and accomodate for first time press (distance will be 0).\n\nJust recursive solution will give tle, we need to memoize it but the challenge is state variable. When ever state variables are complex, try HashMap instead of arry with string as key. This approach can give memory limit exceed sometimes and it can work sometimes. This approach works in this case.\n\n# Code\n```\nclass Solution {\n    Map<String, Integer> memo;\n    public int minimumDistance(String word) {\n        memo = new HashMap<>();\n        return solve(word, 0, new int[]{-1,-1}, new int[]{-1,-1});\n    }\n\n    public int solve(String word, int index, int finger1[], int finger2[]) {\n        if(index == word.length())\n            return 0;\n\n        String key = index + "," + finger1[0] + "," + finger1[1] + "," + finger2[0] + "," + finger2[1];\n\n        if(memo.containsKey(key)) return memo.get(key);\n\n        int cur[] = new int[]{(word.charAt(index) - \'A\') / 6, (word.charAt(index) - \'A\') % 6};\n\n        int f1 = solve(word, index+1, cur, finger2);\n\n        int f2 = solve(word, index+1, finger1, cur);\n\n        int val = Math.min(f1 + (finger1[0] == -1 ? 0 : distance(finger1, cur)), f2 + (finger2[0] == -1 ? 0 : distance(finger2, cur)));\n\n        memo.put(key, val);\n\n        return val;\n    }\n\n    public int distance(int a[], int b[]) {\n        return Math.abs(a[0]- b[0]) + Math.abs(a[1] - b[1]);\n    }\n}\n```
['Memoization', 'Java']