1. Naive Slicing from Length N-1 Downward
Intuition
Iterate candidate prefix length k from n - 1 down to 1. Compare the prefix s[0...k-1] with the suffix s[n-k...n-1]. The first k that matches is the longest proper prefix suffix, so return k. If no match found, return 0.
When to apply: Basic baseline comparison.
Algorithm
- Loop
kfromn - 1down to 1: - If
s.substr(0, k) == s.substr(n - k, k): - Return
k. - Return 0.
Naive Slicing from Length N-1 Downward
2 of 2 questions left todayObservation: A proper prefix or suffix cannot equal the entire string
Observation: A proper prefix or suffix cannot equal the entire string. Maximum possible candidate length is N - 1 = 5.
Decision: Slice prefix s[0..4] = 'ababa' and suffix s[1..5] = 'babab'. Characters mismatch at index 0 (a vs b).
Invariant: Proper prefix and suffix exclude the full string of length N.
#include <iostream>#include <string> class Solution {public: int lps(std::string s) { int n = s.size(); for (int len = n - 1; len >= 1; --len) { if (s.substr(0, len) == s.substr(n - len, len)) { return len; } } return 0; }}; int main() { Solution sol; std::cout << sol.lps("abab") << std::endl; // 2 std::cout << sol.lps("aaaa") << std::endl; // 3 std::cout << sol.lps("abc") << std::endl; // 0 return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Tests up to N candidate lengths, each string comparison taking up to O(N) operations. - Space complexity:
O(1) auxiliary
Why Brute Force Doesn't Scale:
Linear 2N amortized step count replaces the quadratic N2 brute force.
Preallocates a single contiguous integer array of size N.