Similar Problems
Similar Problems not available
Count Prefixes Of A Given String - Leetcode Solution
Companies:
LeetCode: Count Prefixes Of A Given String Leetcode Solution
Difficulty: Easy
Problem Statement:
Given a string s, return an array where each element i is the length of the longest prefix of the string that ends with i.
Example 1:
Input: s = "abcda" Output: [1, 2, 3, 4, 1]
Explanation: The longest prefix ending at the first character is "a" which has length 1. The longest prefix ending at the second character is "ab" which has length 2. The longest prefix ending at the third character is "abc" which has length 3. The longest prefix ending at the fourth character is "abcd" which has length 4. The longest prefix ending at the fifth character is "a" which has length 1.
Example 2:
Input: s = "aaaaa" Output: [1, 2, 3, 4, 5]
Explanation: The longest prefix ending at any character is the string itself.
Approach:
We can solve this problem by using a simple dynamic programming approach. We can create an array dp of length n, where n is the length of the input string s. The value of dp[i] would represent the length of the longest prefix of the string that ends with the character at index i.
To calculate the value of dp[i], we can check if the character at index i is equal to the character at index dp[i-1] (the end of the longest prefix ending at the previous character). If they are equal, then the length of the longest prefix ending at the current position can be calculated as dp[i-1] + 1. Otherwise, the length of the longest prefix ending at the current position would be 1.
Finally, we can return the dp array as the result.
Solution:
class Solution: def countPrefixes(self, s: str) -> List[int]: n = len(s)
dp = [0] * n
dp[0] = 1
for i in range(1, n):
if s[i] == s[dp[i-1]]:
dp[i] = dp[i-1] + 1
else:
dp[i] = 1
return dp
Time Complexity:
The time complexity of the above algorithm is O(n), where n is the length of the input string s. This is because we are iterating through the input string once and performing constant time operations for each character.
Space Complexity:
The space complexity of the above algorithm is O(n), where n is the length of the input string s. This is because we are creating an additional array of size n for storing the values of dp.
Count Prefixes Of A Given String Solution Code
1