VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-repetitions/

⇱ CSES Solutions - Repetitions - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Repetitions

Last Updated : 16 Mar, 2024

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:

  • Maintain a variable count to store the running count of the contiguous character.
  • Iterate over the string, if the current character is same as the previous character, increment count by 1.
  • Otherwise reset count to 1.
  • Also keep checking for the maximum value of count and store it in ans.
  • After iterating over the entire string, return ans as the final result.

Below is the implementation of the algorithm:


Output
4

Time Complexity: O(N), where N is the length of input string S.
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: