Skip to the code
cf.
+25 XP

#620 Shortest Period of a Signal

medium

A monitoring dashboard encodes a sensor's recent readings as a string of letters and wants to know how often the pattern repeats, even if the last cycle is cut short.

A period of signal is a number p with 1 <= p <= signal.length such that signal[i] === signal[i + p] for every i where both exist. Write shortestPeriod(signal) that returns the smallest period.

For example abcabca has period 3: it is abc repeated, with the last copy cut short.

Example 1

Input: signal = "abcabca"
Output: 3

Every letter equals the one 3 places later.

Example 2

Input: signal = "abcd"
Output: 4

Nothing repeats, so only the full length works.

Constraints

  • 1 <= signal.length <= 10^5
  • signal 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).