![]() |
VOOZH | about |
You are given a DNA sequence: a string S consisting of characters A, C, G, and T. Your task is to find the longest repetition in the sequence. This is a maximum-length substring containing only one type of character.
Examples:
Input: S = "ATTCGGGA"
Output: 3
Explanation: The longest repetition in the sequence is "GGG" which has a length of 3.Input: S = "AATTGGCCCC"
Output: 4
Explanation: The longest repetition in the sequence is "CCCC" which has a length of 4.
Approach: To solve the problem, follow the below idea:
The problem can be solved by maintaining the running count of contiguous characters. Iterate over the string and if the current character is same as the previous character, then we can increment the count by 1 otherwise we can reset the count to 1. Also maintain another variable to store the maximum value of count in any iteration.
Step-by-step algorithm:
Below is the implementation of the algorithm:
4
Time Complexity: O(N), where N is the length of input string S.
Auxiliary Space: O(1)