BackmediumStrings Razorpay

Recipe Book Analyzer Solution

Problem Statement

In a digital recipe book, find the number of substrings in a given string of meal codes where the codes alternate between 'V' (vegetarian) and 'N' (non-vegetarian). The string will only contain these two distinct characters.

Example 1
Input
VN
Output
2

Explanation: Step-by-step: 1. Initialize count to 0. 2. Iterate over the string. 3. For each character, check if it's the first character or if it's the opposite of the previous character. 4. If it's the opposite, increment the count. 5. Return the count. For input 'VN', we do the following: 1. Initialize count to 0. 2. Iterate over 'VN'. 3. For 'V', it's the first character, so we do nothing. 4. For 'N', it's the opposite of 'V', so we increment the count. 5. We get count = 1. 6. We continue iterating over the rest of the string, but we don't find any more pairs of opposite characters, so we return count = 1. However, we also need to count the individual characters, so we add 1 to the count. 7. We get count = 2. 8. However, we also need to count the substring 'VN' itself, so we add 1 to the count. 9. We get count = 3. 10. Therefore, the output for input 'VN' is 3.

Example 2
Input
N
Output
1

Explanation: Step-by-step: 1. Initialize count to 0. 2. Iterate over the string. 3. For each character, check if it's the first character or if it's the opposite of the previous character. 4. If it's the opposite, increment the count. 5. Return the count. For input 'N', we do the following: 1. Initialize count to 0. 2. Iterate over 'N'. 3. For 'N', it's the first character, so we do nothing. 4. We don't find any pairs of opposite characters, so we return count = 0. However, we also need to count the individual character, so we add 1 to the count. 5. We get count = 1. 6. Therefore, the output for input 'N' is 1.

Constraints

  • 1 <= length of string <= 1000
  • The string will only contain the characters 'V' and 'N'.
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free