The trick here is to name the state correctly, then let the implementation follow. For 383. Ransom Note, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are canConstruct, count.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01/**
02Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
03
04Each letter in the magazine string can only be used once in your ransom note.
05
06Note:
07You may assume that both strings contain only lowercase letters.
08
09canConstruct("a", "b") -> false
10canConstruct("aa", "ab") -> false
11canConstruct("aa", "aab") -> true
12**/
13
14//Runtime: 32 ms, faster than 49.26% of C++ online submissions for Ransom Note.
15//Memory Usage: 10.8 MB, less than 98.90% of C++ online submissions for Ransom Note.
16class Solution {
17public:
18 bool canConstruct(string ransomNote, string magazine) {
19 vector<int> count(26);
20
21 /*
22 need to visit all chars in magazine first,
23 then to visit chars in ransomNote,
24 because we may use chars in magazine in any order
25 */
26 for(char c : magazine){
27 count[c-'a'] += 1;
28 }
29
30 for(char c : ransomNote){
31 count[c-'a'] -= 1;
32 if(count[c-'a'] < 0) return false;
33 }
34
35 return true;
36 }
37};
Cost