#3713Longest Balanced Substring I
Medium
→
Approach: Brute-Force Enumeration + Frequency Counting
Intuition
The goal is to indentify the longest balanced substring within string s. A substring is called balanced if all the distinct characters in the substring appears the same number of times. My approach exhaustively explores all possible substrings to track the maximum length encountered.
Specifically:
- We utilize two nested loops with iterators
iandjto traverse all possible substrings, wherei ≤ j < n. - While extending the right endpoint, we maintain a frequency table
cntto track character occurences. Since the character set is limited to lowercase English letters, a fixed-size array of length 26 is used, where the index corresponds to the character’s alphabetical order. - In each substring, we iterater throught
cntand check whether all characters in substring appears the same number of time. If condition is met, we update the our maximum length.
Implementation
| |
Complexity Analysis
- Time complexity: $O(Cn^2)$. We iterate through all possible substrings, which takes $O(n^2)$ time. In each iteration, we perform a check operation which takes $O(C)$ time.
- Space complexity: $O(C)$. We only use a constant amount of extra space to store the counts of each character.