Problem:
Score : 200 points

Problem Statement

You are given a string S of length N.
Among its subsequences, count the ones such that all characters are different, modulo 10^9+7. Two subsequences are considered different if their characters come from different positions in the string, even if they are the same as strings.

Here, a subsequence of a string is a concatenation of one or more characters from the string without changing the order.

Constraints

1 \leq N \leq 100000

S consists of lowercase English letters.

|S|=N

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of the subsequences such that all characters are different, modulo 10^9+7.

Sample Input 1

4
abcd

Sample Output 1

15

Since all characters in S itself are different, all its subsequences satisfy the condition.

Sample Input 2

3
baa

Sample Output 2

5

The answer is five: b, two occurrences of a, two occurrences of ba. Note that we do not count baa, since it contains two as.

Sample Input 3

5
abcab

Sample Output 3

17

Solution in C++14 (GCC 5.4.1) (judge verdict: Time Limit Exceeded)

#include <bits/stdc++.h>

using namespace std;

static constexpr int64_t mod = INT64_C(1000000007);

using cache_t = std::unordered_map<std::string, int64_t>;

static cache_t allowEmptyCache{};
static cache_t disallowEmptyCache{};

int64_t solve(bool allowEmpty, const std::string& s) {
  int const n = s.length();
  if (!n) {
    return allowEmpty;
  }
  if (n == 1) {
    return allowEmpty + 1;
  }
  cache_t& cache = allowEmpty ? allowEmptyCache : disallowEmptyCache;
  auto it = cache.find(s);
  if (it != cache.end()) {
    return it->second;
  }
  int64_t ret = solve(allowEmpty, s.substr(1));
  char const c = s.front();
  std::string nextS{};
  nextS.reserve(s.length() + 1);
  for (int i = 1; i < n; i++) {
    if (s[i] == c) {
      continue;
    }
    nextS.push_back(s[i]);
  }
  if (nextS.empty()) {
    ret += 1;
  } else {
    ret += solve(true, nextS);
  }
  ret = ret % mod;
  cache[s] = ret;
  return ret;
}

int main() {
  std::cin.tie(nullptr);
  std::ios::sync_with_stdio(false);
  int n;
  std::cin >> n;
  std::string s;
  s.resize(n);
  for (auto& c : s) {
    std::cin >> c;
  }
  std::cout << solve(false, s) << std::endl;
  return 0;
}