Last Updated: 14 Oct, 2025

Max Substring Occurrences

Moderate
Asked in company
GridRay

Problem statement

You are given an array of strings, arr, containing N strings, and a non-empty target substring, target. Your task is to find and return the string from the array that contains the highest number of occurrences of the target substring.


There are two important rules to consider:


1) Overlapping Occurrences: The occurrences of target within a string are allowed to overlap. For example, if target is "aba", the string "ababa" contains two occurrences of the target: one starting at index 0 and another starting at index 2.


2) Tie-breaking: If two or more strings have the same maximum number of occurrences, you must return the one that appears first in the input array.


Input Format:
The first line contains a single integer N, the number of strings in the array.

The second line contains the target substring.

The next N lines each contain one string from the arr array.


Output Format:
Print a single line containing the string from the array that has the maximum number of occurrences of the target, according to the rules.


Note:
A simple approach using a split() function on the target string may not work correctly due to the overlapping rule. A more robust method is to iteratively search for the substring from the position immediately after the last found match.