Universal Lucky string:
Write a function(S) to find universal lucky string with following conditions-
All characters in S have the same exact frequency (i.e., occur the same number of times). For example, "aabbcc" is valid, but "baacddd" is not valid.
Deleting exactly 1 character from S will result in all its characters having the same frequency. For example, "aabbccc" and "aabbc" are valid because all their letters will have the same frequency if we remove occurrence of "c", but "aabbcccc" is not valid because we'd need to remove 2 characters.
@florin pop can you help me for this Js challenge?
Top comments (4)
Object.prototype.hasOwnProperty.call(counts, c)
is necessary in case the prototype for object has been messed with.Also, I just found out about Map, so here's a version that uses that 😁:
I know the header says "Javascript", but this is really easy in Haskell (or any language that has built-ins for sorting and grouping collections)
The algorithm is as follows:
"abcabcb" -> "aabbbcc"
"aabbbcc" -> [ "aa", "bbb", "cc" ]
[ "aa", "bbb", "cc" ] -> [ 2, 3, 2 ]
[ 2, 3, 2 ] -> [[ 2, 2 ], [ 3 ]]
If the outer array has length of 1, all characters appear with the exact same frequency and we have a lucky string.
If the outer array has a length of 2, the second element has a length of 1, and the element in the second array is one higher than any element in the first array, we have an almost lucky string.
Of course, we can just implement the same algorithm in Javascript, we just need to implement a
group
function. In this case, I have implemented it as a reducer function so that I can use it in an array method chain.