Solving the 'Amazing Subarrays' Problem in Java

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:

  1. 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.

  2. Converting String to Character Array:

    • char input[] = A.toCharArray(); converts the input string to a character array for easy traversal.
  3. 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.

  4. Returning the Result Modulo 10003:

    • return count % 10003; ensures the result is within the specified modulo range.

Lessons Learned:

  1. Fixing ArrayIndexOutOfBounds Error:

    • Using i < A.length() instead of i <= A.length() prevents the loop from accessing an out-of-bounds index.
  2. Adjusting Count Logic:

    • Changing the count logic to count += (A.length() - i); ensures correct counting of all substrings starting from each vowel.
0
Subscribe to my newsletter

Read articles from Sarthak Kulkarni directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sarthak Kulkarni
Sarthak Kulkarni