Simple brute-force all solutions with a hash-map solution.
You can just iterate through all the digits between 1 and n and manually iterate through the hash-map to find the number of groups with the largest size.
code
class Solution {
public:
unordered_map<int, int> mp;
int countLargestGroup(int n) {
for (int i = 1; i <= n; ++i) {
int copy = i;
int counter = 0;
while(copy > 0) {
counter += (copy % 10);
copy /= 10;
}
++mp[counter];
}
int ans = 0, mx = 0;
for (auto &[key, value] : mp) {
if (value > mx) {
ans = 1;
mx = value;
} else if (value == mx) {
++ans;
}
}
return ans;
}
};
complexity
- Time:
O(n)- Space:
O(1)
learnings
- when summing up the digits present in an integer, it is quicker to use division and modulus operations than rely on conversion from integer to string
time taken
- less than 5 minutes?? I should really properly keep track of time