1. Divisor Substring Testing
Intuition
For each possible pattern length L from 1 to N / 2: if N % L == 0, extract sub = s.substr(0, L). Repeat sub N / L times. If the resulting string equals s, return true. If no divisor works, return false.
When to apply: Basic factor-checking approach.
Algorithm
- Loop
Lfrom 1 ton / 2: - If
n % L == 0: -
sub = s.substr(0, L) - Construct repeated string of
subrepeatedn / Ltimes. - If repeated string equals
s: return true. - Return false.
Divisor Substring Testing Trace
2 of 2 questions left todayObservation: Length $N = 4$
Observation: Length N = 4. Candidate sub-lengths must divide N and satisfy L <= N/2.
Decision: Test L = 1: sub = "a".
Invariant: Repetition count k = 4 / 1 = 4.
#include <iostream>#include <string> class Solution {public: bool repeatedSubstringPattern(std::string s) { int n = s.size(); for (int len = 1; len <= n / 2; ++len) { if (n % len == 0) { std::string sub = s.substr(0, len); std::string formed = ""; int times = n / len; for (int t = 0; t < times; ++t) { formed += sub; } if (formed == s) return true; } } return false; }}; int main() { Solution sol; std::cout << (sol.repeatedSubstringPattern("abab") ? "true" : "false") << std::endl; // true std::cout << (sol.repeatedSubstringPattern("aba") ? "true" : "false") << std::endl; // false return 0;}Time & Space Complexity
- Time complexity:
O(N * sqrt(N))— Number of divisors of N is at most O(sqrt(N)), string construction and comparison takes O(N). - Space complexity:
O(N)
Why Brute Force Doesn't Scale:
Linear LPS evaluation computes the exact periodic unit without looping over all divisors.
Preallocates a single contiguous integer array of size N.