Skip to the code
cf.
+25 XP

#614 Smallest Repeating Tile

medium

A pattern editor for wallpaper backgrounds stores each pattern as a string of tile codes. To save space, it wants the smallest tile that, repeated a whole number of times, rebuilds the string exactly.

Write smallestTile(pattern) that returns the shortest string tile such that pattern equals tile repeated k times for some whole number k >= 1. If nothing shorter works, the answer is pattern itself.

Example 1

Input: pattern = "abcabcabc"
Output: "abc"

abc three times rebuilds it.

Example 2

Input: pattern = "abcab"
Output: "abcab"

ab would need a half copy at the end, which isn't allowed.

Constraints

  • 1 <= pattern.length <= 10^5
  • pattern contains lowercase letters.
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).