Iterative Solution | Easy to Understand | Java Solution | Step by Step Explanation
\n\n# Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \nO(N * (string length)!)\n\n- Space complexity:\n Add your space complexity her
\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(N * (string length)!)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(N)$$ for answer\n\n# Code\n```\nclass Solution {\n    //method to count possible moving direction \n    public int findDir(String s,int i,int j,int n,int cnt){\n        for(int k = 0;k < s.length();k ++) {\n            char c = s.charAt(k);\n            //All condition about the possible direction if yes count it or stop it\n            if(c == \'L\'){\n                if(j - 1 >= 0) {\n                    j = j - 1;\n                    cnt++;\n                }else break;\n            }else if(c == \'R\') {\n                if(j + 1 < n) {\n                    j = j + 1;\n                    cnt++;\n                }else break;\n            }else if(c == \'D\') {\n                if(i + 1 < n) {\n                    i = i + 1;\n                    cnt++;\n                }else break;\n            }else{\n                if(i - 1 >= 0) {\n                    i = i - 1;\n                    cnt++;\n                }else break;    \n            }\n\n        }\n        return cnt;\n    }\n    public int[] executeInstructions(int n, int[] startPos, String s) {\n        int[][] grid = new int[n][n];\n        int i = startPos[0];\n        int j = startPos[1];\n        int[]  ans = new int[s.length()];\n        for(int k = 0;k < s.length();k ++) {\n//we need to find from current to end possible direction \n//by sending substring of the current to end for reducing time complexity\n            int countPossible = findDir(s.substring(k,s.length()),i,j,n,0);\n            ans[k] = countPossible;\n        }\n        return ans;\n    }\n}\n```
['Java']