Greedy | Two pointer
\n# Approach\nTrack last occurence of each word2 character to know whether it is possible to change a particular character as it can be done only once.\n\n# Com
\n# Approach\nTrack last occurence of each word2 character to know whether it is possible to change a particular character as it can be done only once.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n+m)\n\n- Space complexity:\nO(2*m)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n    vector<int> validSequence(string word1, string word2) {\n        int n=word1.length();\n        int m=word2.length();\n\n        vector<int> lastocc(m,-1);\n        int i=n-1,j=m-1;\n        while(i>=0 && j>=0){\n            if(word1[i]==word2[j]){\n                lastocc[j]=i;\n                j--;\n                i--;\n            }else{\n                i--;\n            }\n        }\n\n        vector<int> ans;\n        int changed=0;\n\n        j=0;\n        for(i=0;i<n;i++){\n            if(word1[i]==word2[j]){\n                ans.push_back(i);\n                j++;\n            }else if(!changed){\n                if((j<m-1 && lastocc[j+1]>=i+1) || (j==m-1)){\n                    changed++;\n                    ans.push_back(i);\n                    j++;\n                }\n            }\n            if(j>=m)break;\n        }\n        if(ans.size()!=m)return {};\n        return ans;\n    }\n};\n```
['C++']