Practice › Hashing & Two Pointers
Ransom Note
Easy · Hashing & Two Pointers · Asked at Amazon, Microsoft, Apple, TCS, Infosys
Can the note be written using the letters of the magazine, using each letter of the magazine at most once? Print YES or NO.
Input
Two lines: note, then magazine (lowercase letters).
Output
YES or NO.
Constraints
- 1 ≤ |note|, |magazine| ≤ 10^5
Count the magazine’s letters, then take one away for each letter of the note; if a count would go below zero, the answer is NO.
Example 1
Input
a b
Output
NO
Example 2
Input
aa aab
Output
YES
Hints
- Only how many of each letter the magazine has matters.
- Count the magazine, then spend letters for the note.
Approach
Count the 26 letters of the magazine. For each letter of the note, decrease its count; if the count is already 0, that letter is missing — NO. If the whole note is processed, YES.
Complexity: O(|note| + |magazine|) time · O(26) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string note, mag;
cin >> note >> mag;
int cnt[26] = {0};
for (char c : mag) cnt[c - 'a']++;
for (char c : note)
if (cnt[c - 'a']-- == 0) {
cout << "NO\n";
return 0;
}
cout << "YES\n";
return 0;
}Python solution
import sys
from collections import Counter
note, mag = sys.stdin.read().split()[:2]
print("YES" if not (Counter(note) - Counter(mag)) else "NO")Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String note = br.readLine().trim(), mag = br.readLine().trim();
int[] cnt = new int[26];
for (char c : mag.toCharArray()) cnt[c - 'a']++;
for (char c : note.toCharArray())
if (cnt[c - 'a']-- == 0) {
System.out.println("NO");
return;
}
System.out.println("YES");
}
}