Java String Program · S09
Ransom Note Problem in Java
Can you cut the letters of a note out of a magazine, using each letter only once? This classic counting problem shows how a small array can replace a map.
Problem Statement
You are given two strings, note and magazine. Return true if every letter of note can be taken from magazine, where each letter of the magazine can be used only once.
Both strings contain only lowercase English letters. An empty note can always be built.
Input/Output Examples
note = "sit", magazine = "tissue"OutputtrueExplanation: the magazine has at least one s, one i and one t.note = "moon", magazine = "monday"OutputfalseExplanation: the note needs two o's, but the magazine has only one.note = "", magazine = "abc"OutputtrueExplanation: no letters are needed.Visual Explanation
- Step 1counts from "tissue"e:1i:1s:2t:1u:1count the magazine
- Step 2after si:1s:1t:1use s s:2 → s:1
- Step 3after ii:0s:1t:1use i i:1 → i:0
- Step 4after ti:0s:1t:0use t t:1 → t:0
- Doneno count went below 0true
note = "sit" against magazine = "tissue": count the magazine letters, then use one letter per note character (amber). Only the letters the note needs are shown after step 1.The counts array is a stock of available letters. Every note character takes one from the stock; if any count would drop below zero, that letter has run out and the answer is false.
Approaches
Both approaches count the magazine letters first. They differ only in the data structure used for the counts.
Approach 1: int[26] Counting Array (Recommended)
Idea: count the magazine letters in an array indexed by c - 'a', then subtract one for each note letter.
- If the note is longer than the magazine, return
falseimmediately. - For each magazine letter, increase
counts[c - 'a']. - For each note letter, decrease its count; if it becomes negative, return
false. - If every note letter is covered, return
true.
Time: O(n + m) · Space: O(1). The array always has 26 slots, whatever the input size.
Approach 2: HashMap Counting
Idea: same idea, but store the counts in a HashMap so that any character, including uppercase letters and digits, is supported.
- Count the magazine characters with
merge(c, 1, Integer::sum). - For each note character, read its count with
getOrDefault(c, 0). - If the count is
0, returnfalse; otherwise, store the count minus one.
Time: O(n + m) · Space: O(k).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: int[26] Counting Array (Recommended)
c - 'a' turns 'a' into index 0 and 'z' into 25. The early length check skips all work when the note cannot possibly fit.
public class RansomNoteArray {
// Assumes lowercase English letters; counts[c - 'a'] tracks the letters still available
static boolean canConstruct(String note, String magazine) {
if (note.length() > magazine.length()) {
return false;
}
int[] counts = new int[26];
for (char c : magazine.toCharArray()) {
counts[c - 'a']++;
}
for (char c : note.toCharArray()) {
if (--counts[c - 'a'] < 0) {
return false; // this letter has run out
}
}
return true;
}
public static void main(String[] args) {
String[][] pairs = {{"sit", "tissue"}, {"moon", "monday"}, {"", "abc"}};
for (String[] p : pairs) {
System.out.println("note=\"" + p[0] + "\", magazine=\"" + p[1] + "\" -> " + canConstruct(p[0], p[1]));
}
}
}
note="sit", magazine="tissue" -> true note="moon", magazine="monday" -> false note="", magazine="abc" -> true
Time complexity: O(n + m) · Space complexity: O(1).
Approach 2: HashMap Counting
Use this version when the input is not limited to a to z. Here k is the number of distinct characters in the magazine.
import java.util.HashMap;
import java.util.Map;
public class RansomNoteMap {
// Works for any characters, not only a to z
static boolean canConstruct(String note, String magazine) {
Map<Character, Integer> counts = new HashMap<>();
for (char c : magazine.toCharArray()) {
counts.merge(c, 1, Integer::sum);
}
for (char c : note.toCharArray()) {
int left = counts.getOrDefault(c, 0);
if (left == 0) {
return false;
}
counts.put(c, left - 1);
}
return true;
}
public static void main(String[] args) {
String[][] pairs = {{"sit", "tissue"}, {"moon", "monday"}, {"", "abc"}};
for (String[] p : pairs) {
System.out.println("note=\"" + p[0] + "\", magazine=\"" + p[1] + "\" -> " + canConstruct(p[0], p[1]));
}
}
}
note="sit", magazine="tissue" -> true note="moon", magazine="monday" -> false note="", magazine="abc" -> true
Time complexity: O(n + m) · Space complexity: O(k).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| int[26] Counting Array | O(n + m) | O(1) |
| HashMap Counting | O(n + m) | O(k) |
Here n is the length of the note and m is the length of the magazine. Each character is processed once. The array has a fixed size of 26, so its space is O(1).
Interview Tips and Recommended Approach
- Confirm the alphabet. The
int[26]trick is valid only for lowercase English letters; ask before using it. - Do not search and delete in the magazine string. Calling
indexOf()and rebuilding the string for every note letter isO(n × m). - Add the length shortcut. If the note is longer than the magazine, it can never fit, so return
falsebefore counting. - Explain why counting works. The order of letters does not matter, only how many of each are available.
Recommended Approach: int[26] Counting Array
Why: it runs in linear time with a fixed 26-element array, which is faster and lighter than a map. The same counting pattern solves anagram checks and many other frequency questions.