Skip to content

Commit 1119445

Browse files
committed
add solution for ransom note
1 parent df1bc4b commit 1119445

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { describe, it, expect } from 'bun:test'
2+
import { canConstruct } from './ransom-note';
3+
4+
describe('canConstruct', () => {
5+
it('should return true when ransomNote can be constructed from magazine', () => {
6+
expect(canConstruct('a', 'a')).toBe(true);
7+
expect(canConstruct('aa', 'aab')).toBe(true);
8+
expect(canConstruct('abc', 'cba')).toBe(true);
9+
});
10+
11+
it('should return false when ransomNote cannot be constructed from magazine', () => {
12+
expect(canConstruct('aa', 'ab')).toBe(false);
13+
expect(canConstruct('aaa', 'aa')).toBe(false);
14+
expect(canConstruct('abcd', 'abc')).toBe(false);
15+
});
16+
17+
it('should return true for empty ransomNote', () => {
18+
expect(canConstruct('', 'anystring')).toBe(true);
19+
});
20+
21+
it('should return false for empty magazine when ransomNote is not empty', () => {
22+
expect(canConstruct('a', '')).toBe(false);
23+
});
24+
25+
it('should return true when both ransomNote and magazine are empty', () => {
26+
expect(canConstruct('', '')).toBe(true);
27+
});
28+
29+
it('should handle large inputs', () => {
30+
const ransomNote = 'a'.repeat(1000);
31+
const magazine = 'a'.repeat(1000);
32+
expect(canConstruct(ransomNote, magazine)).toBe(true);
33+
34+
const magazineWithExtra = 'a'.repeat(1001);
35+
expect(canConstruct(ransomNote, magazineWithExtra)).toBe(true);
36+
37+
const insufficientMagazine = 'a'.repeat(999);
38+
expect(canConstruct(ransomNote, insufficientMagazine)).toBe(false);
39+
});
40+
});
+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
2+
3+
export function canConstruct(ransomNote: string, magazine: string): boolean {
4+
if (magazine == '' && ransomNote == '') return true
5+
6+
const dictLetters: Record<string, number> = {}
7+
8+
for (let i = 0; i < magazine.length; i++) {
9+
if (dictLetters[magazine[i]]) {
10+
dictLetters[magazine[i]] += 1
11+
} else {
12+
dictLetters[magazine[i]] = 1
13+
}
14+
}
15+
16+
for (let i = 0; i < ransomNote.length; i++) {
17+
if (dictLetters[ransomNote[i]]) {
18+
if (dictLetters[ransomNote[i]] > 1) {
19+
dictLetters[ransomNote[i]] -= 1
20+
} else {
21+
delete dictLetters[ransomNote[i]]
22+
}
23+
} else {
24+
return false
25+
}
26+
}
27+
return true // Độ phức tạp
28+
29+
30+
};

0 commit comments

Comments
 (0)