Check if a String Is an Acronym of Words - Problem
You're tasked with creating an acronym validator! Given an array of strings words and a string s, determine if s forms a valid acronym of the words.
An acronym is formed by taking the first character of each word in the given order. For example:
"NASA"could be formed from["National", "Aeronautics", "Space", "Administration"]"FBI"could be formed from["Federal", "Bureau", "Investigation"]
Important: The order matters! "ab" can be formed from ["apple", "banana"], but cannot be formed from ["banana", "apple"].
Return true if s is a valid acronym of words, and false otherwise.
Input & Output
example_1.py โ Basic Valid Acronym
$
Input:
words = ["alice", "bob", "charlie"], s = "abc"
โบ
Output:
true
๐ก Note:
Taking the first character of each word: 'a' from "alice", 'b' from "bob", 'c' from "charlie" gives us "abc", which matches the input string s.
example_2.py โ Invalid Acronym
$
Input:
words = ["an", "apple"], s = "a"
โบ
Output:
false
๐ก Note:
The first characters would be 'a' from "an" and 'a' from "apple", giving us "aa". Since "aa" โ "a", this is not a valid acronym.
example_3.py โ Length Mismatch
$
Input:
words = ["never", "gonna", "give", "up"], s = "nggu"
โบ
Output:
true
๐ก Note:
Taking first characters: 'n' from "never", 'g' from "gonna", 'g' from "give", 'u' from "up" gives us "nggu", which exactly matches the input string.
Visualization
Tap to expand
Understanding the Visualization
1
Input Validation
Check if the number of words matches the length of target acronym
2
Character Extraction
Take the first character from each word in sequence
3
Direct Comparison
Compare extracted characters with target string positions
4
Result
Return true if all characters match, false otherwise
Key Takeaway
๐ฏ Key Insight: The most efficient approach compares characters directly without building intermediate strings, achieving O(1) space complexity while maintaining O(n) time complexity.
Time & Space Complexity
Time Complexity
O(n)
We iterate through the words array once, checking each character. In worst case, we check all n characters
โ Linear Growth
Space Complexity
O(1)
We only use a constant amount of extra space for variables, no additional data structures
โ Linear Space
Constraints
- 1 โค words.length โค 100
- 1 โค words[i].length โค 10
- 1 โค s.length โค 100
- words[i] and s consist of lowercase English letters
- Order matters - acronym must be formed in the exact sequence given
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code