Skip to the code
cf.
+25 XP

#617 Repeated Fragments of Length k

medium

A copy-paste detector looks at a file as one long string and reports every fragment of exactly k characters that appears more than once. Occurrences may overlap.

Write repeatedFragments(text, k) that returns each such fragment once, ordered by the index where it first appears. Return an empty array if there are none.

Example 1

Input: text = "abcXabcYabc", k = 3
Output: ["abc"]

abc appears three times; no other 3-character fragment repeats.

Example 2

Input: text = "aaaa", k = 2
Output: ["aa"]

aa appears at 0, 1, and 2.

Constraints

  • 0 <= text.length <= 10^5
  • 1 <= k <= 100
  • text contains printable ASCII characters.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).