Tutorialcountingstring
Count a Character
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Given a string s and a single character c, return how many times c appears in s. Both are lowercase
English letters; c has the single-character type char.
Examples
| s | c | result |
|---|---|---|
"banana" | "a" | 3 |
"apple" | "z" | 0 |
"ccc" | "c" | 3 |
Example 1 — a appears 3 times in banana.
Example 2 — z never appears.
Example 3 — Every character is c.
This is a tutorial problem: there are no performance tests, just return the correct value.
Function signature
solution(s: string, c: char) → int
Constraints
- length of
s scontains only lowercase English letters.cis one lowercase English letter.
Expected complexity
- Time
- O(N)
- Space
- O(1)
Examples
| s | c | Expected |
|---|---|---|
"banana" | "a" | 3 |
"apple" | "z" | 0 |
"ccc" | "c" | 3 |
Hint
Hint
Go through the characters one by one and count those equal to c. In Java, s.charAt(i) gives the i-th
character, and chars compare with ==.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1000 ms | derived |
| Kotlin 2.4 (JVM) | 1200 ms | estimated |
| C# 14 (.NET 10) | 1200 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 100 | 11 | verdict only |