Last Updated: June 7, 2026
Return how many positions in s hold exactly the character c. The return value is a number, not a position or a boolean, so even a string with zero matches produces a valid answer of 0.
The comparison is case sensitive. A and a are stored as different codes, so only an exact match increases the count. If the string is empty, or the character never appears, the answer is 0.
A few cases test the logic. An empty string has nothing to scan, so the loop runs zero times and the count stays at 0. A string where every character matches gives a count equal to its length. A character that never appears, such as z in "abc", leaves the counter at 0. The same scan handles all three.
0 <= s.length <= 1000 → The string can be empty, so the code must run cleanly when there is nothing to read. The upper bound is small, so a single linear pass is fast enough.A and a are counted separately.Counting requires looking at every character at least once, since any skipped character might be the one being counted. This is where counting differs from searching: a search can stop on its first hit, but a count has to continue, because a later position can still add to the total.
Keep a running counter that starts at zero. Visit each character in order, and every time the current character equals c, add one to the counter. At the end of the string, the counter holds the total number of matches. That counter is the only state needed, so this uses constant extra memory regardless of string length.
0.c, increase the counter by one.Take s = "banana" and c = 'a'. Index 0 is b, which does not match, so the count stays at 0. Index 1 is a, the first match, so the count becomes 1. Index 2 is n, no match. Index 3 is a, so the count becomes 2. Index 4 is n, no match. Index 5 is a, so the count becomes 3. The scan has reached the end, so the answer is 3.
The scan never stops early. After the first match at index 1, it keeps going to catch the matches at indices 3 and 5.