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? To complete the task of making the ransom note, which one must be inevitably finite, and which one may be infinite, 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?
- How would you make a ransom note in real life? Cut out letter by letter from a newspaper and build neat little stacks, ready for the ransom note? Probably not ;-)
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
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:
One example case with a sample newspaper and a sample ransom note executed in a main method is far from enough to verify the correctness of such program. Consider looking into a proper unit testing framework, such as JUnit.