Simple CPP Solution | Iterative | Effective
Intuition\nUse a helper function ans to simulate the robot\u2019s moves starting from any index i.\n# Approach\n\n- Iterate through the instructions, updating t
# Intuition\nUse a helper function ans to simulate the robot\u2019s moves starting from any index i.\n# Approach\n\n- Iterate through the instructions, updating the robot\u2019s position based on the current command (L, R, U, or D).\n- Stop if a move would place the robot outside the grid boundaries and return the count of valid moves.\n- For each index in s, store the result of ans in the answer array.\n# Complexity\n- Time complexity:\n$$O(m^2)$$, where m is the length of s. For each start index, it can take up to m moves in the worst case.\n- Space complexity:\n$$O(m)$$ for the answer vector.\n# Code\n```cpp []\nclass Solution {\npublic:\n    int ans(vector<int> startPos,  string s,\n            int start,int n) {\n        int count = 0;\n        for (int i = start; i < s.length(); i++) {\n            if (s[i] == \'L\') {\n                if (startPos[1] - 1 >= 0) {\n                    startPos[1] -= 1;\n                    count++;\n                } else\n                    return count;\n            }\n            if (s[i] == \'R\') {\n                if ((startPos[1] + 1) < (n)) {\n                    startPos[1] += 1;\n                    count++;\n                } else\n                    return count;\n            }\n            if (s[i] == \'U\') {\n                if ((startPos[0] - 1) >= 0) {\n                    startPos[0] -= 1;\n                    count++;\n                } else\n                    return count;\n            }\n            if (s[i] == \'D\') {\n                if ((startPos[0] + 1) < (n)) {\n                    startPos[0] += 1;\n                    count++;\n                } else\n                    return count;\n            }\n        }\n        return count;\n    }\n    vector<int> executeInstructions(int n, vector<int>& startPos, string s) {\n        vector<int> answer;\n        for (int i = 0; i < s.length(); i++) {\n            answer.push_back(ans(startPos, s, i,n));\n        }\n        return answer;\n    }\n};\n```
['C++']