Skip to content
Katabench
Try free

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.

The allocation budget

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

C#
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.

C# coding challenges →

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