DEV Community

Debesh P.
Debesh P.

Posted on

383. Ransom Note | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/ransom-note/


Detailed Step-by-Step Explanation

Solution 1: https://leetcode.com/problems/ransom-note/solutions/7481880/most-optimal-solution-beats-200-using-ha-d54j
Solution 2: https://leetcode.com/problems/ransom-note/solutions/7481780/smartest-approach-most-optimal-solution-u8bed


leetcode 383


Solution 1

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {

        Map<Character, Integer> map = new HashMap<>();

        for (char c : magazine.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }

        for (char c : ransomNote.toCharArray()) {
            if (!map.containsKey(c) || map.get(c) == 0) {
                return false;
            }
            map.put(c, map.get(c) - 1);
        }

        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Solution 2

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {

        int[] charCount = new int[26];

        for (char c : magazine.toCharArray()) {
            charCount[c - 'a']++;
        }

        for (char ch : ransomNote.toCharArray()) {
            if (charCount[ch - 'a'] == 0) {
                return false;
            }
            charCount[ch - 'a']--;
        }

        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)