Very simple O(N) with Prev and Next
Just save the  prev and next occurrence of the char at the current index for all indices and then with simple math just calculate the number of substrings in wh
Just save the  prev and next occurrence of the char at the current index for all indices and then with simple math just calculate the number of substrings in which the current char is unique.\n```\nint uniqueLetterString(string S) {\n        int n = S.size();\n        unordered_map<char, int> Last; //index of last occurrence of char\n        \n        vector<int> Next(n, n); //index of next occurrence of S[i]\n        vector<int> Prev(n, 0); //index of prev occurrence of S[i]\n        \n        for (int i = 0; i < n; ++i) {\n            char c = S[i];\n            if (Last.count(c)) {\n                Prev[i] = Last[c] + 1;\n                Next[Last[c]] = i;   \n            }\n            Last[c] = i;\n        }\n        \n        int res = 0;\n        for (int i = 0; i < n; ++i) {\n        // the following is the number of substrings\n        // in which the current char is unique\n            res += ((i + 1) - Prev[i]) * (Next[i] - i);\n        }\n        return res % 1000000007;\n    }\n```
[]