Solving the 'Amazing Subarrays' Problem in Java

Table of contents
Problem:
Count substrings starting with a vowel in a given string, modulo 10003.
Solution:
public class Solution {
public int solve(String A) {
int count = 0;
char vowels[] = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
char input[] = A.toCharArray();
for (int i = 0; i < A.length(); i++) {
for (char vowel : vowels) {
if (input[i] == vowel) {
count += (A.length() - i);
break;
}
}
}
return count % 10003;
}
}
Explanation:
Initializing Variables:
int count = 0;
initializes the counter for substrings.char vowels[] = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
is the list of vowel characters.
Converting String to Character Array:
char input[] = A.toCharArray();
converts the input string to a character array for easy traversal.
Counting Substrings Starting with a Vowel:
The outer loop
for (int i = 0; i < A.length(); i++)
traverses each character in the input string.The inner loop
for (char vowel : vowels)
checks if the current character is a vowel.If the character is a vowel,
count += (A.length() - i);
adds the number of substrings starting from this vowel to the end of the string.
Returning the Result Modulo 10003:
return count % 10003;
ensures the result is within the specified modulo range.
Lessons Learned:
Fixing ArrayIndexOutOfBounds Error:
- Using
i < A.length()
instead ofi <= A.length()
prevents the loop from accessing an out-of-bounds index.
- Using
Adjusting Count Logic:
- Changing the count logic to
count += (A.length() - i);
ensures correct counting of all substrings starting from each vowel.
- Changing the count logic to
Subscribe to my newsletter
Read articles from Sarthak Kulkarni directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
