Consecutive Nucleotide Count — Problem Statement & Solution Guide
Problem Description
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
Input
ATCG
Output
4
Explanation: Step-by-step: Given the input string 'ATCG', we can form substrings like 'A', 'C', 'G', 'T', 'AC', 'GT'. However, we should not count 'AT' and 'CG' as they have consecutive characters. Therefore, the correct count is 4.
Input
AA
Output
1
Explanation: Step-by-step: Given the input string 'AA', we can form a single substring 'A'. Therefore, the correct count is 1.
Constraints
- 1 <= length of DNA sequence <= 1000
- DNA sequence only contains the characters 'A', 'C', 'G', 'T'
Optimal Approach & Strategy
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.
Brute Force Approach
The brute-force approach involves checking all possible substrings of the DNA sequence, which has a time complexity of O(n²) due to the nested loop structure. This approach is inefficient for large sequences. It checks every substring, resulting in unnecessary comparisons.
Verified Code Solutions
function countSubstrings(sequence) {
let count = 0;
for (let i = 0; i < sequence.length; i++) {
let prev = sequence[i - 1] || null;
for (let j = i + 1; j < sequence.length; j++) {
let substring = sequence.slice(i, j);
if (substring.length === new Set(substring).size && substring[0] !== substring[1]) {
count++;
}
}
}
return count;
}public int consecutiveNucleotideCount(String s) {
int count = 0;
for (int i = 0; i < s.length() - 1; i++) {
if (s.charAt(i) != s.charAt(i + 1)) {
count++;
}
}
return count + 1;
}def consecutive_nucleotide_count(s: str) -> int:
count = 0
for i in range(len(s) - 1):
if s[i] != s[i + 1]:
count += 1
return count + 1function countSubstrings(sequence) {
let count = 0;
for (let i = 0; i < sequence.length; i++) {
let prev = sequence[i - 1] || null;
for (let j = i + 1; j < sequence.length; j++) {
let substring = sequence.slice(i, j);
if (substring.length === new Set(substring).size && substring[0] !== substring[1]) {
count++;
}
}
}
return count;
}Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.