Skip to content

1624. Largest Substring Between Two Equal Characters 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int maxLengthBetweenEqualCharacters(string s) {
    int ans = -1;
    vector<int> lastSeen(26, -1);

    for (int i = 0; i < s.length(); ++i) {
      const int c = s[i] - 'a';
      if (lastSeen[c] == -1)
        lastSeen[c] = i;
      else
        ans = max(ans, i - lastSeen[c] - 1);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int maxLengthBetweenEqualCharacters(String s) {
    int ans = -1;
    int[] lastSeen = new int[26];
    Arrays.fill(lastSeen, -1);

    for (int i = 0; i < s.length(); ++i) {
      final int c = s.charAt(i) - 'a';
      if (lastSeen[c] == -1)
        lastSeen[c] = i;
      else
        ans = Math.max(ans, i - lastSeen[c] - 1);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def maxLengthBetweenEqualCharacters(self, s: str) -> int:
    ans = -1
    lastSeen = {}

    for i, c in enumerate(s):
      if c not in lastSeen:
        lastSeen[c] = i
      else:
        ans = max(ans, i - lastSeen[c] - 1)

    return ans