Check Whether Available Letters Can Form a Note

Quick Overview

Practice deciding whether one lowercase string supplies enough letter occurrences to form another. Preserve multiplicities while allowing rearrangement and unused letters.

Check Whether Available Letters Can Form a Note

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

# Check Whether Available Letters Can Form a Note Given lowercase strings `ransomNote` and `magazine`, return whether the note can be formed using letters from the magazine. Each occurrence of a letter in `magazine` may be used at most once. ### Function `bool canConstruct(string ransomNote, string magazine)` ### Example 1 ```text Input: ransomNote = "cab", magazine = "bcaac" Output: true ``` The magazine has at least one occurrence of each required letter. ### Example 2 ```text Input: ransomNote = "ccc", magazine = "acbc" Output: false ``` Only two copies of `c` are available. ### Constraints - `1 <= ransomNote.length,magazine.length <= 100000`. - Both strings contain only lowercase English letters. ### Clarifications Letters may be rearranged; the note need not appear as a subsequence or substring. Repeated letters require separate available occurrences. Unused magazine letters are allowed. ### What a Strong Answer Covers - Letter availability and repeated occurrences. - Why letter order does not affect the answer. - Correctness and time/storage bounds for long strings.

Overview: Practice deciding whether one lowercase string supplies enough letter occurrences to form another. Preserve multiplicities while allowing rearrangement and unused letters.

Google logo
Google
easySoftware EngineerOtherCoding & Algorithms
0
0

Check Whether Available Letters Can Form a Note

Given lowercase strings ransomNote and magazine, return whether the note can be formed using letters from the magazine. Each occurrence of a letter in magazine may be used at most once.

Function

bool canConstruct(string ransomNote, string magazine)

Example 1

Input: ransomNote = "cab", magazine = "bcaac"
Output: true

The magazine has at least one occurrence of each required letter.

Example 2

Input: ransomNote = "ccc", magazine = "acbc"
Output: false

Only two copies of c are available.

Constraints

  • 1 <= ransomNote.length,magazine.length <= 100000 .
  • Both strings contain only lowercase English letters.

Clarifications

Letters may be rearranged; the note need not appear as a subsequence or substring. Repeated letters require separate available occurrences. Unused magazine letters are allowed.

What a Strong Answer Covers Guidance

  • Letter availability and repeated occurrences.
  • Why letter order does not affect the answer.
  • Correctness and time/storage bounds for long strings.