PROBLEM LINK:
DIFFICULTY:
CAKEWALK
PREREQUISITES:
Basics of looping, conditional statements in any language.
PROBLEM:
Given a string $s$, find whether exactly two different letters alternate in it or not. e.g. if $s$ = "ABABAB", then the answer will be yes or if $s$ = "ABC", then the answer would be no, if $s$ = "AA" answer would be no because the alternating characters should be different as stated in the problem.
EXPLANATION:
Given a string, first check the starting two characters, if they are the same (character is in consecutive position instead of alternating) then clearly the answer is NO. Otherwise we just have to check whether the first two characters (i.e. $s[0]$ and $s[1]$) are occurring in even and odd positions respectively or not.
Pseudo Code
if(S[0]==S[1]) return false; for(i=0; i+2 < N; i++) if(S[i]!= S[i+2]) return false; return true;
The above code first checks the first two character and if they are different then check the whole string whether it follows the alternating character condition. The time complexity of the algorithm is $\mathcal{O}(|s|)$ as we are iterating over all the characters of string s only once.
AUTHOR'S AND TESTER'S SOLUTIONS:
Author's solution can be found here.
Tester's solution can be found here.