Easy explanation | O(N) time O(1) space
Approach:\nstr - BACBC  Ans: 25\nSubstrings with no of unique characters\nB  1\nBA 2\nBAC 3\nBACB 2\nBACBC 1\n\nA 1\nAC 2\nACB 3\nACBC 2\n\nC 1\nCB 2\nCBC 1\n\n
**Approach:**\n**str - BACBC  Ans: 25**\nSubstrings with no of unique characters\nB  1\nBA 2\nBAC 3\nBACB 2\nBACBC 1\n\nA 1\nAC 2\nACB 3\nACBC 2\n\nC 1\nCB 2\nCBC 1\n\nB 1\nBC 2\n\nC 1\n\n**Contribution of each character**\nB A C B C\n3 8  6 6 2  -> 25\n\n* If we get to know contribution of each character then we can add them to get answer\n* prev is no of characters before curr character not equal to curr \n* next is no of characters after curr character not equal to curr\n\nB \nprev -> 0 + 1\nnext -> 2 + 1 \ncontribution: 1 * 3 = 3\n\nA\nprev -> 1 + 1 \nnext -> 3 + 1\ncontribution: 2 * 4 = 8\n\nC\nprev -> 2 + 1 \nnext -> 1 + 1\ncontribution: 3 * 2 = 6\n\nB\nprev -> 2 + 1 \nnext -> 1 + 1\ncontribution: 3 * 2 = 6\n\nC\nprev -> 1 + 1 \nnext -> 0 + 1\ncontribution: 2 * 1 = 2\n\n**Code Explanation:**\n* last2Index vector stores last 2 index of each character, it is initialzed with -1\n* **if last2Index[0] == -1** for curr character then it\'s coming for the first time then simply set last2Index[0] for curr char to i\n* **else** add prev * next where *prev = (i - last2Index[chi][0])* and next = *(last2Index[chi][0] - last2Index[chi][1])* and update *last2Index[1] = last2Index[0*] and *last2Index[0] = i*\n* At the end add character than are not added yet to ans (in first for loop 1st occurence of character are included)\n\n\n**Code:**\n```\nclass Solution {\npublic:\n    int uniqueLetterString(string s) {\n        vector<vector<int>> last2Index(26, vector<int>(2, -1));\n        int ans = 0;\n        for(int i = 0; i < s.length(); i++) {\n            int chi = s[i] - \'A\';\n            if(last2Index[chi][0] == -1) {\n                last2Index[chi][0] = i;\n            } else {\n                ans += (i - last2Index[chi][0]) * (last2Index[chi][0] - last2Index[chi][1]);\n                last2Index[chi][1] = last2Index[chi][0];\n                last2Index[chi][0] = i;\n            }\n        }\n        \n        int i = s.length();\n        for(int chi = 0; chi < 26; chi++) {\n            if(last2Index[chi][0] != -1) {\n                ans += (i - last2Index[chi][0]) * (last2Index[chi][0] - last2Index[chi][1]);\n            }\n        }\n        return ans;\n    }\n};\n```\n\n**Time Complexity:** O(N)\n**Space Complexity:** O(1)
['C']