Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/main/java/com/thealgorithms/strings/RansomNote.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.thealgorithms.strings;

/**
* Determines if a ransom note can be constructed using letters from a magazine.
* Each letter in the magazine can only be used once.
*
* <p>Example: ransomNote = "aa", magazine = "aab" -> true
*
* <p>Time complexity: O(n), Space complexity: O(1) (fixed 26-char alphabet)
*
* @see <a href="https://leetcode.com/problems/ransom-note/">LeetCode #383</a>
*/
public final class RansomNote {
private RansomNote() {
}

public static boolean canConstruct(String ransomNote, String magazine) {
int[] count = new int[26];
for (char c : magazine.toCharArray()) {
count[c - 'a']++;
}
for (char c : ransomNote.toCharArray()) {
if (--count[c - 'a'] < 0) {
return false;
}
}
return true;
}
}
34 changes: 34 additions & 0 deletions src/test/java/com/thealgorithms/strings/RansomNoteTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.thealgorithms.strings;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;

public class RansomNoteTest {

@Test
public void testCanConstruct() {
assertTrue(RansomNote.canConstruct("aa", "aab"));
}

@Test
public void testCannotConstruct() {
assertFalse(RansomNote.canConstruct("aa", "ab"));
}

@Test
public void testEmptyRansomNote() {
assertTrue(RansomNote.canConstruct("", "abc"));
}

@Test
public void testEmptyMagazine() {
assertFalse(RansomNote.canConstruct("a", ""));
}

@Test
public void testExactMatch() {
assertTrue(RansomNote.canConstruct("abc", "abc"));
}
}
Loading