Sort the characters in the string: "abcabcb" -> "aabbbcc"
Group characters: "aabbbcc" -> [ "aa", "bbb", "cc" ]
Map outer list to length: [ "aa", "bbb", "cc" ] -> [ 2, 3, 2 ]
Sort and group again: [ 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.
constlast=arr=>arr[arr.length-1]constappendToLast=(arr,x)=>{constlastElement=last(arr)lastElement.push(x)returnarr}constgroup=(prev,x)=>prev.length===0?[[x]]:last(prev)[0]===x?appendToLast(prev,x):[...prev,[x]]// Everything above this line is because Javascript doesn't have group built in.constlength=arr=>arr.lengthconstisAlmostLucky=groupedFreqs=>groupedFreqs.length===2&&groupedFreqs[1].length===1&&groupedFreqs[1][0]===groupedFreqs[0][0]+1constisLucky=str=>{constgroupedFreqs=str.split('').sort().reduce(group,[]).map(length).sort().reduce(group,[])returngroupedFreqs.length===1||isAlmostLucky(groupedFreqs)}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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.