countOccurrences

Easy · Loops and Iterations · 3 test cases

Given a string and a character, count how many times the character appears in the string.

Examples

countOccurrences('hello', 'l') → 2
countOccurrences('programming', 'm') → 2
countOccurrences('banana', 'a') → 3

Starter code

function countOccurrences(str, char) {

}

Complexity of the optimal solution

Time O(n), space O(1). The function loops through the input string once. The execution time scales linearly with the length of the string (n). The space used for the counter is constant.

Solve countOccurrences in the browser