Count Substring Occurrences
Medium About 15 min Free, no account needed
Count overlapping occurrences by comparing characters, not slicing strings.
The brief
Count how many times needle occurs in text, overlapping occurrences
count ("aa" occurs twice in "aaa"). The needle is never empty.
Slicing text.Substring(i, needle.Length) for every position allocates a
string per character of the text. The hidden test is a 100 KB text under a
32 KB allocation budget. Match each candidate position without allocating a
new string, zero allocations.
Starter code
using System;
public class Solution
{
// TODO: return the number of overlapping occurrences of needle in text.
public int CountOccurrences(string text, string needle)
{
throw new NotImplementedException();
}
}How it is graded
Visible examples help you iterate. Hidden tests then cover edge cases and larger inputs, and every test reports server-measured time and allocated bytes.
What it practices
- String processing
- Parse, scan and match text character by character with correct edge cases.
- Allocation-free code
- Avoid per-item strings and copies with spans, indexes and arithmetic in hot loops.
Related katas
- Hex Checksum Medium Free Sum the bytes of a hex string with nibble arithmetic, not substrings.
- Most Common Word Length Medium Free Which word length appears most often? Count lengths, not words.
- Count Words Easy Free Count words by spotting boundaries, not by splitting.
- Parse and Sum Integers Easy Free Sum space-separated integers (negatives included) allocation-free.