-
Notifications
You must be signed in to change notification settings - Fork 577
Expand file tree
/
Copy pathLongest_balanced_substring.c
More file actions
87 lines (80 loc) · 1.92 KB
/
Longest_balanced_substring.c
File metadata and controls
87 lines (80 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
* =====================================================================================
*
* Program: Longest Balanced Substring
*
* Problem Statement:
* Given a lowercase English string s, find the length of the longest substring
* where all distinct characters appear the same number of times.
*
* Approach:
* - For each substring (i, j), use a frequency map (array of size 26)
* to count occurrences of each character.
* - Check if the substring is "balanced" by verifying if all non-zero
* frequencies are equal.
* - Track the maximum balanced substring length.
*
* Time Complexity: O(n^2 * 26)
* Space Complexity: O(26)
*
* Example Run (Input/Output):
*
* Input:
* Enter string: abbac
*
* Output:
* Longest balanced substring length: 4
*
* Explanation:
* "abba" is the longest balanced substring since 'a' and 'b'
* both appear exactly 2 times.
*
* =====================================================================================
*/
#include <stdio.h>
#include <string.h>
#include <limits.h>
int isBalanced(int freq[26])
{
int mini = INT_MAX, maxi = 0;
for (int i = 0; i < 26; i++)
{
if (freq[i] > 0)
{
if (freq[i] < mini)
mini = freq[i];
if (freq[i] > maxi)
maxi = freq[i];
}
}
return mini == maxi;
}
int longestBalanced(char *s)
{
int n = strlen(s);
int ans = 0;
for (int i = 0; i < n; i++)
{
int freq[26] = {0};
for (int j = i; j < n; j++)
{
freq[s[j] - 'a']++;
if (isBalanced(freq))
{
int len = j - i + 1;
if (len > ans)
ans = len;
}
}
}
return ans;
}
int main(void)
{
char s[1005];
printf("Enter string: ");
scanf("%s", s);
int result = longestBalanced(s);
printf("Longest balanced substring length: %d\n", result);
return 0;
}