Skip to content

Commit cde6047

Browse files
committed
#1941: Check if All Characters Have Equal Number of Occurrences; solution & tests
1 parent 0447095 commit cde6047

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* 1941
3+
* Check if All Characters Have Equal Number of Occurrences
4+
**
5+
* Given a string s,
6+
* return true if s is a good string,
7+
* or false otherwise.
8+
*
9+
* A string s is good
10+
* if all the characters that appear in s
11+
* have the same number of occurrences
12+
* (i.e., the same frequency).
13+
*
14+
* Example 1:
15+
* Input: s = "abacbc"
16+
* Output: true
17+
* Explanation:
18+
* The characters that appear in s are 'a', 'b', and 'c'.
19+
* All characters occur 2 times in s.
20+
*
21+
* Example 2:
22+
* Input: s = "aaabb"
23+
* Output: false
24+
* Explanation:
25+
* The characters that appear in s are 'a' and 'b'.
26+
* 'a' occurs 3 times while 'b' occurs 2 times,
27+
* which is not the same number of times.
28+
*
29+
* Constraints:
30+
* • 1 <= s.length <= 1000
31+
* • s consists of lowercase English letters.
32+
*
33+
* Hint 1:
34+
* Build a dictionary containing the frequency of each character appearing in s
35+
*
36+
* Hint 2:
37+
* Check if all values in the dictionary are the same.
38+
**
39+
* https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/
40+
***/
41+
42+
namespace Problems;
43+
44+
public class CheckIfAllCharactersHaveEqualNumberOfOccurrences
45+
{
46+
public bool AreOccurrencesEqual( string s )
47+
{
48+
int[] freqMap = new int[26];
49+
50+
foreach ( char c in s )
51+
{
52+
freqMap[c - 'a']++;
53+
}
54+
55+
int firstElementFrequency = freqMap[s[0] - 'a'];
56+
57+
foreach ( int freq in freqMap )
58+
{
59+
if ( freq != 0 && freq != firstElementFrequency )
60+
{
61+
return false;
62+
}
63+
}
64+
65+
return true;
66+
}
67+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
using NUnit.Framework;
2+
3+
using Problems;
4+
5+
public class CheckIfAllCharactersHaveEqualNumberOfOccurrencesTests
6+
{
7+
[TestCase( "abacbc", ExpectedResult = true )]
8+
[TestCase( "aaabb", ExpectedResult = false )]
9+
[TestCase( "vvvvvvvvvvvvvvvvvvv", ExpectedResult = true )]
10+
public bool AreOccurrencesEqualTest( string s ) =>
11+
new CheckIfAllCharactersHaveEqualNumberOfOccurrences().AreOccurrencesEqual( s );
12+
}

0 commit comments

Comments
 (0)