<|instruction|>
Solve the below problem. The solution should start with an abridged problem statement. Then key observations. Then full solution based on the observations. Then C++ and Python implementations with comments.

538. Emoticons
Time limit per test: 1 second(s)
Memory limit: 262144 kilobytes
input: standard
output: standard



A berland national nanochat Bertalk should always stay up-to-date. That's why emoticons highlighting was decided to be introduced. As making emoticons to be highlighted is not exactly the kind of task one performs everyday but this task had to be done as soon as possible, the following simple rule was decided to be introduced: a round opening or closing bracket  be considered part of an emoticon if:
this is an opening bracket and there exists the nearest bracket following to the right. The nearest round bracket to the right should be a closing bracket and there shouldn't be anything between the brackets but spaces and Latin letters,
or else it can be a closing bracket and there exists the nearest round bracket following to the left. The nearest round bracket to the left should be an opening bracket. Besides, there shouldn't be anything between the brackets but spaces and Latin letters.


If a bracket doesn't satisfy the conditions, it is considered a part of an emoticon. For example, let's consider the string "Hi:) (it is me) I have bad news:-((". In the string only the brackets that outline "it is me" aren't emoticons. Note that an opening bracket immediatelly followed by a closing bracket, i.e. "()", are not parts of emoticons by definition.

Your task is to print the number of brackets that are parts of emoticons in the given string.

Input
The input data consist of a single non-empty string. The length of the string does not exceed 105 characters. The string consists of lowercase and uppercase Latin letters, spaces, round brackets and punctuation marks: "-", ":", ",", ";". The string does not begin with and does not end with a space.

Output
Print a single number — the required number of brackets that are part of emoticons.

Example(s)
sample input
sample output
Hi:) (it is me) I have bad news:-((
3

sample input
sample output
((two plus two equals four))
2

<|response|>
1. Abridged Problem Statement
You are given a string s of length up to 10^5 consisting of letters, spaces, round brackets '(', ')', and a few punctuation marks ('-', ':', ',', ';').
We say a bracket is normal (i.e., not part of an emoticon) if:
  - It is '(' and its nearest round bracket to the right is ')', and all characters strictly between them are only letters or spaces.
  - Or it is ')' and its nearest round bracket to the left is '(', with only letters or spaces in between.
All other parentheses are considered parts of emoticons.
Output the total count of emoticon parentheses in s.

2. Key Observations
- We need, for each position i, the index of the nearest '(' to the left (prev_bracket[i]) and the nearest ')' to the right (next_bracket[i]).
- We must quickly check if the substring between two brackets contains only letters/spaces. We build a prefix-sum array cnt_non_letters of characters that are neither letters, spaces, nor brackets. Then the count in [l..r] is cnt_non_letters[r] - cnt_non_letters[l-1].
- If we initially assume all parentheses are emoticons, we can later detect each "normal" bracket and subtract it from our count.

3. Full Solution Approach
a. Preprocessing in O(n):
   1. Build prev_bracket[]: left-to-right pass, record the most recent index of '(' at or before each position (only '(' is tracked since the check at ')' looks for its nearest '(').
   2. Build cnt_non_letters[]: also in that pass, prefix sum of characters that are not letters, spaces, or brackets.
   3. Build next_bracket[]: right-to-left pass, record the next index of ')' at or after each position.

b. Counting emoticons:
   1. Scan left-to-right; for each position i:
      - Count every '(' or ')' as an emoticon (ans++).
      - If s[i]=='(', let j = next_bracket[i]. If j!=-1 and prev_bracket[j]==i and get_non_letters(i, j)==0, this '(' is normal; ans--.
      - If s[i]==')', let j = prev_bracket[i]. If j!=-1 and next_bracket[j]==i and get_non_letters(j, i)==0, this ')' is normal; ans--.

c. Print ans.

Time complexity: O(n).
Memory: O(n).

4. C++ Implementation with Comments
```cpp
#include <bits/stdc++.h>

using namespace std;

template<typename T1, typename T2>
ostream& operator<<(ostream& out, const pair<T1, T2>& x) {
    return out << x.first << ' ' << x.second;
}

template<typename T1, typename T2>
istream& operator>>(istream& in, pair<T1, T2>& x) {
    return in >> x.first >> x.second;
}

template<typename T>
istream& operator>>(istream& in, vector<T>& a) {
    for(auto& x: a) {
        in >> x;
    }
    return in;
};

template<typename T>
ostream& operator<<(ostream& out, const vector<T>& a) {
    for(auto x: a) {
        out << x << ' ';
    }
    return out;
};

string s;

void read() { getline(cin, s); }

void solve() {
    // A bracket pair is a "real" pair (not part of an emoticon) when an '(' has
    // its nearest bracket to the right being a ')', that ')' has this '(' as its
    // nearest bracket to the left, and everything between them is only spaces
    // and Latin letters (and the pair is not the empty "()"). All other
    // brackets are emoticon parts, which is what we count.
    //
    // prev_bracket[i] / next_bracket[i] give, for position i, the index of the
    // nearest '(' to the left / ')' to the right (or itself if i is that
    // bracket). cnt_non_letters is a prefix sum of characters that are neither
    // letters, spaces, nor brackets, so get_non_letters(l, r) tests emptiness
    // of the inside. We start by counting every bracket, then for each matched,
    // clean pair we subtract its two brackets back out.

    int n = s.size();
    vector<int> prev_bracket(n, -1);
    vector<int> next_bracket(n, -1);
    vector<int> cnt_non_letters(n, 0);
    for(int i = 0; i < n; i++) {
        if(s[i] == '(') {
            prev_bracket[i] = i;
        } else {
            prev_bracket[i] = i ? prev_bracket[i - 1] : -1;
        }

        if(!isalpha(s[i]) && s[i] != ' ' && s[i] != '(' && s[i] != ')') {
            cnt_non_letters[i]++;
        }
        cnt_non_letters[i] += i ? cnt_non_letters[i - 1] : 0;
    }

    auto get_non_letters = [&](int l, int r) {
        return cnt_non_letters[r] - (l ? cnt_non_letters[l - 1] : 0);
    };

    for(int i = n - 1; i >= 0; i--) {
        if(s[i] == ')') {
            next_bracket[i] = i;
        } else {
            next_bracket[i] = i < n - 1 ? next_bracket[i + 1] : -1;
        }
    }

    int ans = 0;
    for(int i = 0; i < n; i++) {
        if(s[i] == '(' || s[i] == ')') {
            ans++;
        }

        if(s[i] == '(' && next_bracket[i] != -1 &&
           prev_bracket[next_bracket[i]] == i &&
           get_non_letters(i, next_bracket[i]) == 0) {
            ans--;
        }

        if(s[i] == ')' && prev_bracket[i] != -1 &&
           next_bracket[prev_bracket[i]] == i &&
           get_non_letters(prev_bracket[i], i) == 0) {
            ans--;
        }
    }

    cout << ans << '\n';
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int T = 1;
    // cin >> T;
    for(int test = 1; test <= T; test++) {
        read();
        // cout << "Case #" << test << ": ";
        solve();
    }

    return 0;
}
```

5. Python Implementation with Comments
```python
import sys

def count_emoticons(s: str) -> int:
    n = len(s)
    # nearest bracket to the left/right
    prev_b = [-1] * n
    next_b = [-1] * n
    # bad[i]: number of forbidden chars up to index i
    bad = [0] * n

    # Build prev_b[] and bad[] in one pass
    for i, ch in enumerate(s):
        # nearest bracket to the left
        if ch in '()':
            prev_b[i] = i
        elif i > 0:
            prev_b[i] = prev_b[i - 1]

        # forbidden if not letter, not space
        is_forbidden = not (ch.isalpha() or ch == ' ')
        bad[i] = (bad[i - 1] if i > 0 else 0) + (1 if is_forbidden else 0)

    # Build next_b[] in reverse
    for i in range(n - 1, -1, -1):
        if s[i] in '()':
            next_b[i] = i
        elif i + 1 < n:
            next_b[i] = next_b[i + 1]

    # helper to count forbidden chars in s[l..r]
    def count_bad(l, r):
        if l > r:
            return 0
        return bad[r] - (bad[l - 1] if l > 0 else 0)

    # start by assuming every parenthesis is an emoticon
    ans = sum(1 for ch in s if ch in '()')

    # subtract each normal bracket
    for i, ch in enumerate(s):
        if ch == '(':
            j = next_b[i]
            if (j != -1 and s[j] == ')' and prev_b[j] == i
                and count_bad(i + 1, j - 1) == 0):
                ans -= 1
        elif ch == ')':
            j = prev_b[i]
            if (j != -1 and s[j] == '(' and next_b[j] == i
                and count_bad(j + 1, i - 1) == 0):
                ans -= 1

    return ans

if __name__ == "__main__":
    s = sys.stdin.readline().rstrip('\n')
    print(count_emoticons(s))
```
