00:00

Problem Statement

Input/Output Examples

Visual Explanation

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.

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.

Complexity Analysis

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 is O(n × m).
  • Add the length shortcut. If the note is longer than the magazine, it can never fit, so return false before 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.