#2828
Check if a String Is an Acronym of Words
EasyArrayStringArrayString
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution is similar to the brute-force approach but uses a more efficient way to construct the acronym and perform the comparison in a single pass. This reduces unnecessary string concatenation operations.
⚙️
Algorithm
3 steps- 1Step 1: Check if the length of words is equal to the length of s. If not, return false.
- 2Step 2: Loop through each word in the words array and check if the first character matches the corresponding character in s.
- 3Step 3: If all characters match, return true; otherwise, return false.
solution.py7 lines
1def isAcronym(words, s):
2 if len(words) != len(s):
3 return False
4 for i in range(len(words)):
5 if words[i][0] != s[i]:
6 return False
7 return Trueℹ
Complexity note: The time complexity remains O(n) because we still loop through each word once, but the space complexity is reduced to O(1) as we do not create any additional strings.
- 1The acronym is formed by the first characters of each word.
- 2Length mismatch between words and s immediately indicates false.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.