Created
February 12, 2026 21:15
-
-
Save tatsuyax25/8cfdc4c8c0a3314140daf2127585f4f2 to your computer and use it in GitHub Desktop.
You are given a string s consisting of lowercase English letters. A substring of s is called balanced if all distinct characters in the substring appear the same number of times. Return the length of the longest balanced substring of s.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {string} s | |
| * @return {number} | |
| */ | |
| var longestBalanced = function(s) { | |
| const n = s.length; | |
| let maxLen = 0; | |
| // Try every possible starting index i | |
| for (let i = 0; i < n; i++) { | |
| // Frequency array for 'a' to 'z' | |
| const freq = Array(26).fill(0); | |
| // Expand the substring from i to j | |
| for (let j = i; j < n; j++) { | |
| const idx = s.charCodeAt(j) - 97; // map 'a'..'z' to 0..25 | |
| freq[idx]++; | |
| // Check if substring s[i..j] is balanced | |
| if (isBalanced(freq)) { | |
| const len = j - i + 1; | |
| maxLen = Math.max(maxLen, len); | |
| } | |
| } | |
| } | |
| return maxLen; | |
| }; | |
| // Helper: returns true if all non-zero frequencies are equal | |
| function isBalanced(freq) { | |
| let target = 0; | |
| for (let count of freq) { | |
| if (count === 0) continue; | |
| if (target === 0) { | |
| // First non-zero frequency becomes the target | |
| target = count; | |
| } else if (count !== target) { | |
| // Mismatch → not balanced | |
| return false; | |
| } | |
| } | |
| return true; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment