22 * @link Problem definition [[docs/hackerrank/interview_preparation_kit/dictionaries_and_hashmaps/sherlock_and_anagrams.md]]
33 */
44
5- function factorial ( n : number ) : number {
6- if ( n == 0 ) {
7- return 1 ;
8- }
9- return n * factorial ( n - 1 ) ;
5+ import { logger as console } from '../../../logger' ;
6+
7+ function extraLongFactorials ( n : number ) : bigint {
8+ const rs = [ ... Array ( n ) ] . reduce ( ( a , b , i ) => a * BigInt ( i + 1 ) , 1n ) ;
9+ return rs ;
1010}
1111
1212export function sherlockAndAnagrams ( s : string ) : number {
@@ -16,6 +16,9 @@ export function sherlockAndAnagrams(s: string): number {
1616 for ( let i = 0 ; i < size ; i ++ ) {
1717 for ( let j = 0 ; j < size - i ; j ++ ) {
1818 const substr = s . substring ( i , size - j ) ;
19+ console . debug (
20+ `i: ${ i } , size: ${ size } , size - j: ${ size - j } | substr: ${ substr } `
21+ ) ;
1922
2023 // Add substrings to a candidate list.
2124 // two strings are anagrams if sorted strings are the same.
@@ -32,7 +35,8 @@ export function sherlockAndAnagrams(s: string): number {
3235 }
3336 }
3437
35- let count = 0 ;
38+ let total : bigint = BigInt ( 0 ) ;
39+ let q_candidates = 0 ;
3640 // Final Anagram list
3741 for ( const word of Object . keys ( candidates ) ) {
3842 const quantity_of_anagrams = candidates [ word ] . length ;
@@ -42,15 +46,23 @@ export function sherlockAndAnagrams(s: string): number {
4246 delete candidates [ word ] ;
4347 } else {
4448 // Binomial coefficient: https://en.wikipedia.org/wiki/Binomial_coefficient
45- count += Math . floor (
46- factorial ( quantity_of_anagrams ) /
47- ( factorial ( k ) * factorial ( quantity_of_anagrams - k ) )
48- ) ;
49+ q_candidates += quantity_of_anagrams ;
50+
51+ const count =
52+ extraLongFactorials ( quantity_of_anagrams ) /
53+ ( extraLongFactorials ( k ) *
54+ extraLongFactorials ( quantity_of_anagrams - k ) ) ;
55+ total += count ;
56+
57+ console . debug ( `'Partial anagrams of ${ word } : ${ count } ` ) ;
4958 }
5059 }
51- console . debug ( `filtered candidates: ${ count } ` ) ;
60+ console . debug (
61+ `'sherlockAndAnagrams(${ s } ) Filtered # candidates: ${ q_candidates } `
62+ ) ;
63+ console . debug ( `'sherlockAndAnagrams(${ s } ) # anagrams: ${ total } ` ) ;
5264
53- return count ;
65+ return Number ( total ) ;
5466}
5567
5668export default { sherlockAndAnagrams } ;
0 commit comments