• + 0 comments

    Java solution using a 1D array matrix

    class Result {
      public static final int NUM_LETTERS = 26;
      /*
       * Complete the 'alternate' function below.
       *
       * The function is expected to return an INTEGER.
       * The function accepts STRING s as parameter.
       */
    
      public static int alternate(String s) {
        // Edge case: if length <= 1, no alternations are possible
        if (s.length() <= 1) {
          System.out.println(0);
          return 0;
        }
        // Flattened array to represent the upper triangular portion of the matrix
        int[] count = new int[(NUM_LETTERS * (NUM_LETTERS - 1)) / 2];
        char[] lastSeen = new char[(NUM_LETTERS * (NUM_LETTERS - 1)) / 2];
        // Helper function to calculate the index in the flattened array
    
        // Process the string
        for (char c : s.toCharArray()) {
          int charIndex = c - 'a';
    
          // Update all pairs involving this character
          for (int i = 0; i < NUM_LETTERS; i++) {
            if (i == charIndex)
              continue;
    
            int index =
                charIndex < i ? getIndex(charIndex, i) : getIndex(i, charIndex);
    
            if (count[index] != -1) { // Only process if valid
              if (lastSeen[index] == c) {
                count[index] = -1; // Invalidate if repeating
              } else {
                lastSeen[index] = c; // Update last seen character
                count[index]++;
              }
            }
          }
        }
    
        // Find the maximum valid count
        int max = 0;
        for (int c : count) {
          max = Math.max(max, c);
        }
        return max;
      }
      private static int getIndex(int i, int j) {
        return i * NUM_LETTERS + j - ((i + 1) * (i + 2)) / 2;
      }
    }