#383

Ransom Note

Easy
Hash TableStringCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a frequency count of characters in the magazine. This allows us to efficiently check if we have enough letters to construct the ransom note.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a frequency map (dictionary) to count occurrences of each character in magazine.
  2. 2Step 2: For each character in ransomNote, check if it exists in the frequency map and if the count is greater than zero.
  3. 3Step 3: Decrease the count in the frequency map for each character used.
  4. 4Step 4: If all characters are accounted for, return true; otherwise, return false.
solution.py10 lines
1# Full working Python code
2
3def canConstruct(ransomNote, magazine):
4    from collections import Counter
5    magazine_count = Counter(magazine)
6    for char in ransomNote:
7        if magazine_count[char] <= 0:
8            return False
9        magazine_count[char] -= 1
10    return True

Complexity note: The time complexity is O(n) because we traverse the magazine and ransomNote strings once each. The space complexity is O(n) for storing the frequency counts.

  • 1Using a frequency count allows us to efficiently track character availability.
  • 2The optimal solution scales better with larger inputs due to linear time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.