mediumStringsPattern: Mixed

Consecutive Nucleotide Count Solution

Problem Statement

Given a string of nucleotide bases consisting of characters 'A', 'C', 'G', and 'T', write a function to count the number of substrings where no two consecutive characters are the same.

Examples

Example 1:
Input:{"sequence":"ACGT"}
Output:4
Explanation: The substrings with no two consecutive characters representing the same nucleotide base are: A, C, G, T
Example 2:
Input:{"sequence":"AAAA"}
Output:4
Explanation: The substrings with no two consecutive characters representing the same nucleotide base are: A (at each position)
Example 3:
Input:{"sequence":"ATCGATCG"}
Output:16
Explanation: Counting all substrings with no consecutive repeats

Constraints

  • 1 <= length of DNA sequence <= 1000
  • DNA sequence only contains the characters 'A', 'C', 'G', 'T'
Time: O(n²) Space: O(1)
A more efficient approach uses a sliding window to generate substrings and checks for alternating nucleotide bases. This approach still has a time complexity of O(n²) in the worst case but with a lower constant factor, making it more efficient in practice.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.