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 ) {
6
- if ( n === 0 ) {
7
- return 1 ;
8
- }
9
- return n * factorial ( n - 1 ) ;
5
+ import { logger as console } from '../../../logger.js' ;
6
+
7
+ function extraLongFactorials ( n ) {
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 ) {
@@ -16,6 +16,9 @@ export function sherlockAndAnagrams(s) {
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) {
32
35
}
33
36
}
34
37
35
- let count = 0 ;
38
+ let total = BigInt ( 0 ) ;
39
+ let qCandidates = 0 ;
36
40
// Final Anagram list
37
41
for ( const word of Object . keys ( candidates ) ) {
38
42
const quantityOfAnagrams = candidates [ word ] . length ;
@@ -42,15 +46,22 @@ export function sherlockAndAnagrams(s) {
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 ( quantityOfAnagrams ) /
47
- ( factorial ( k ) * factorial ( quantityOfAnagrams - k ) )
48
- ) ;
49
+ qCandidates += quantityOfAnagrams ;
50
+
51
+ const count =
52
+ extraLongFactorials ( quantityOfAnagrams ) /
53
+ ( extraLongFactorials ( k ) * extraLongFactorials ( quantityOfAnagrams - k ) ) ;
54
+ total += count ;
55
+
56
+ console . debug ( `'Partial anagrams of ${ word } : ${ count } ` ) ;
49
57
}
50
58
}
51
- console . debug ( `filtered candidates: ${ count } ` ) ;
59
+ console . debug (
60
+ `'sherlockAndAnagrams(${ s } ) Filtered # candidates: ${ qCandidates } `
61
+ ) ;
62
+ console . debug ( `'sherlockAndAnagrams(${ s } ) # anagrams: ${ total } ` ) ;
52
63
53
- return count ;
64
+ return Number ( total ) ;
54
65
}
55
66
56
67
export default { sherlockAndAnagrams } ;
0 commit comments