Funcia
Tutorialcountingstring

Count a Character

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
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

scresult
"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

  • 1≤1 \le length of s ≤1,000\le 1{,}000
  • s contains only lowercase English letters.
  • c is one lowercase English letter.

Expected complexity

Time
O(N)
Space
O(1)

Examples

scExpected
"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

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251000 msderived
Kotlin 2.4 (JVM)1200 msestimated
C# 14 (.NET 10)1200 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness10011verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.