Algorithm
You build an array with the counts of letters in the newspaper. Then you iterate over the letters of the ransom note, and short circuit when a letter is missing (count goes below zero).
Can this be done the other way around? That is, build an array of counts from the note, then iterate over the newspaper and short circuit when the letter is completed. Yes that would work too, but using a map of counts instead of an array, deleting letters that were completed, and an empty map marking the ransom note competed.
So which way is better? Consider these questions:
- Which tends to be bigger: the ransom note or the newspaper?
- What if the newspaper contains billions of letters?
- What if you receive the available letters (of the newspaper) as a (possibly infinite) stream of characters?
Naming
The name validateSomething
sounds like it might throw an exception is invalid, or mutate state (return void). More common prefixes for boolean methods are "is", "has" and "can". In this example, instead of validateLetterCreation
, I would recommend canCreateRansomNote
.
The name charArray
is misleading. A reader might think it's an array of characters. When it's actually counts of letters, so I would call it just like that: countsOfLetters
.