2
2
* @link Problem definition [[docs/hackerrank/interview_preparation_kit/dictionaries_and_hashmaps/sherlock_and_anagrams.md]]
3
3
*/
4
4
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 ;
10
10
}
11
11
12
12
export function sherlockAndAnagrams ( s : string ) : number {
@@ -16,6 +16,9 @@ export function sherlockAndAnagrams(s: string): number {
16
16
for ( let i = 0 ; i < size ; i ++ ) {
17
17
for ( let j = 0 ; j < size - i ; j ++ ) {
18
18
const substr = s . substring ( i , size - j ) ;
19
+ console . debug (
20
+ `i: ${ i } , size: ${ size } , size - j: ${ size - j } | substr: ${ substr } `
21
+ ) ;
19
22
20
23
// Add substrings to a candidate list.
21
24
// two strings are anagrams if sorted strings are the same.
@@ -32,7 +35,8 @@ export function sherlockAndAnagrams(s: string): number {
32
35
}
33
36
}
34
37
35
- let count = 0 ;
38
+ let total : bigint = BigInt ( 0 ) ;
39
+ let q_candidates = 0 ;
36
40
// Final Anagram list
37
41
for ( const word of Object . keys ( candidates ) ) {
38
42
const quantity_of_anagrams = candidates [ word ] . length ;
@@ -42,15 +46,23 @@ export function sherlockAndAnagrams(s: string): number {
42
46
delete candidates [ word ] ;
43
47
} else {
44
48
// 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 } ` ) ;
49
58
}
50
59
}
51
- console . debug ( `filtered candidates: ${ count } ` ) ;
60
+ console . debug (
61
+ `'sherlockAndAnagrams(${ s } ) Filtered # candidates: ${ q_candidates } `
62
+ ) ;
63
+ console . debug ( `'sherlockAndAnagrams(${ s } ) # anagrams: ${ total } ` ) ;
52
64
53
- return count ;
65
+ return Number ( total ) ;
54
66
}
55
67
56
68
export default { sherlockAndAnagrams } ;
0 commit comments