Skip to content

Commit 4592943

Browse files
authored
Merge pull request #1921 from Hemav009/382
added 383
2 parents dc67989 + accb9f5 commit 4592943

File tree

1 file changed

+133
-0
lines changed

1 file changed

+133
-0
lines changed
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
---
2+
id: ransome-note
3+
title: Ransom Note
4+
sidebar_label: 0383-Ransom Note
5+
tags:
6+
- Leet code
7+
description: "Solution to leetocde 383"
8+
---
9+
10+
### Problem Description
11+
12+
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.
13+
14+
Each letter in magazine can only be used once in ransomNote.
15+
16+
### Examples
17+
18+
Example 1:
19+
20+
```
21+
Input: ransomNote = "a", magazine = "b"
22+
Output: false
23+
```
24+
25+
Example 2:
26+
27+
```
28+
Input: ransomNote = "aa", magazine = "ab"
29+
Output: false
30+
```
31+
32+
Example 3:
33+
34+
```
35+
Input: ransomNote = "aa", magazine = "aab"
36+
Output: true
37+
```
38+
39+
### Constraints:
40+
41+
- $1 <= ransomNote.length, magazine.length <= 10^5$
42+
- ransomNote and magazine consist of lowercase English letters.
43+
Alright, here's the breakdown of the code you provided, along with implementations in various languages:
44+
45+
### Algorithm:
46+
47+
1. **Initialize a frequency table:** The code creates an array `alpha` of size 26. This array will store the frequency of each letter in the magazine (`a` maps to index 0, `b` to index 1, and so on).
48+
2. **Iterate through ransom note:** For each character `c` in the ransom note:
49+
- Calculate the index `idx` using `ord(c) - ord('a')`. This converts the character `c` to its corresponding numerical position (e.g., 'a' becomes 0, 'b' becomes 1).
50+
- Use `magazine.find(c, alpha[idx])` to find the first occurrence of `c` in the magazine starting from index `alpha[idx]`. This improves efficiency by avoiding redundant searches in the magazine.
51+
- If `i` (the result of `find`) is -1, it means the character `c` is not found in the magazine. In this case, the function returns `False` as the ransom note cannot be formed.
52+
- Update `alpha[idx]` with `i + 1` to track the last position where `c` was found in the magazine. This helps avoid revisiting the same characters in the magazine unnecessarily.
53+
3. **Return True:** After iterating through the entire ransom note, if no characters were missing, the function returns `True`, indicating that the ransom note can be constructed from the magazine.
54+
55+
**Code Implementations:**
56+
57+
**Python:**
58+
59+
```python
60+
from collections import Counter
61+
62+
class Solution:
63+
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
64+
magazine_counter = Counter(magazine)
65+
ransom_counter = Counter(ransomNote)
66+
for char, count in ransom_counter.items():
67+
if char not in magazine_counter or magazine_counter[char] < count:
68+
return False
69+
return True
70+
```
71+
72+
**C++:**
73+
74+
```c++
75+
#include <unordered_map>
76+
77+
class Solution {
78+
public:
79+
bool canConstruct(std::string ransomNote, std::string magazine) {
80+
std::unordered_map<char, int> magazine_counter;
81+
for (char c : magazine) {
82+
magazine_counter[c]++;
83+
}
84+
for (char c : ransomNote) {
85+
if (magazine_counter.find(c) == magazine_counter.end() || magazine_counter[c] == 0) {
86+
return false;
87+
}
88+
magazine_counter[c]--;
89+
}
90+
return true;
91+
}
92+
};
93+
```
94+
95+
**Java:**
96+
97+
```java
98+
import java.util.HashMap;
99+
100+
class Solution {
101+
public boolean canConstruct(String ransomNote, String magazine) {
102+
HashMap<Character, Integer> magazine_counter = new HashMap<>();
103+
for (char c : magazine.toCharArray()) {
104+
magazine_counter.put(c, magazine_counter.getOrDefault(c, 0) + 1);
105+
}
106+
for (char c : ransomNote.toCharArray()) {
107+
if (!magazine_counter.containsKey(c) || magazine_counter.get(c) == 0) {
108+
return false;
109+
}
110+
magazine_counter.put(c, magazine_counter.get(c) - 1);
111+
}
112+
return true;
113+
}
114+
}
115+
```
116+
117+
**JavaScript:**
118+
119+
```javascript
120+
function canConstruct(ransomNote, magazine) {
121+
const magazine_counter = {};
122+
for (const char of magazine) {
123+
magazine_counter[char] = (magazine_counter[char] || 0) + 1;
124+
}
125+
for (const char of ransomNote) {
126+
if (!(char in magazine_counter) || magazine_counter[char] === 0) {
127+
return false;
128+
}
129+
magazine_counter[char]--;
130+
}
131+
return true;
132+
}
133+
```

0 commit comments

Comments
 (0)