08(March) Check if frequencies can be equal
08. Check if frequencies can be equal
My Approach:
Time and Auxiliary Space Complexity
Code (C++)
class Solution{
public:
int getIdx(char ch)
{
return (ch - 'a');
}
bool allSame(int freq[], int N)
{
int same;
int i;
for (i = 0; i < N; i++)
{
if (freq[i] > 0)
{
same = freq[i];
break;
}
}
for (int j = i+1; j < N; j++)
if (freq[j] > 0 && freq[j] != same)
return false;
return true;
}
bool sameFreq(string str)
{
int M = 26;
int l = str.length();
int freq[M] = {0};
for (int i = 0; i < l; i++)
freq[getIdx(str[i])]++;
if (allSame(freq, M))
return true;
for (char c = 'a'; c <= 'z'; c++)
{
int i = getIdx(c);
if (freq[i] > 0)
{
freq[i]--;
if (allSame(freq, M))
return true;
freq[i]++;
}
}
return false;
}
};Contribution and Support
📍Visitor Count
Previous07(March) Longest repeating and non-overlapping substringNext09(March) Find the N-th character
Last updated