Golang O(N) time and O(1) space
Consider only one letter (e.g. \'A\')\n\nplain\n"xAxxAxx..." (x for other letters)\n[xA]xxAxx...\nx[A]xxAxx...\n[xAx]xAxx...\nx[Ax]xAxx...\n[xAxx]Axx...\nx[Axx]
Consider only one letter (e.g. \'A\')\n\n```plain\n"xAxxAxx..." (x for other letters)\n[xA]xxAxx...\nx[A]xxAxx...\n[xAx]xAxx...\nx[Ax]xAxx...\n[xAxx]Axx...\nx[Axx]Axx...\n```\nAbove are all substrings that contain the first A uniquely: If there are `p` non \'A\' letters before it,\nand `q` non \'A\' letters after it, then there will be `(p + 1)*(q + 1)`  \n(e.g. 6 here) substrings that contain *this* \'A\' uniquely. And all other substrings either not contain\n*this* \'A\' or contain other \'A\' as well (then not uniquely)\n\nThen the solution will be the sum of all the count of these substrings for each letter for each occurrence.\n\n```golang\nfunc uniqueLetterString(s string) int {\n    r := 0\n    last2 := [26]int{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}\n    last1 := [26]int{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}\n    for i := 0; i < len(s); i++ {\n        a := int(s[i] - \'A\')\n        i2, i1 := last2[a], last1[a]\n        r += (i1 - i2)*(i - i1)\n        last2[a], last1[a] = i1, i\n    }\n    \n    i := len(s)\n    for a := 0; a < 26; a++ {\n        if last1[a] < 0 {\n            continue\n        }\n        i2, i1 := last2[a], last1[a]\n        r += (i1 - i2)*(i - i1)\n    }\n    return r\n}\n```\n\nSo one pass with constant space (to remember last two occurences for each letter) is enough.
[]