Check if a String Is an Acronym of Words solution and explanation
9 more videos on this problem
Leetcode | 2828. Check if a String is an Acronym of Words | Easy | Java SolutionDeveloper Docs · 3:39 · 813 views
Leetcode 2828 Check if a String Is an Acronym of Words HindiThinkCode · 4:06 · 472 views
Leetcode Weekly contest 359 - Easy- Check if a String Is an Acronym of WordsPrakhar Agrawal · 1:56 · 455 views
✅ LeetCode 2828 – Acronym Checker Explained | C++ & JavaScript Solution (Step-by-Step)AtomicDevv · 3:03 · 382 views
2828. Check if a String Is an Acronym of Words (Leetcode Easy)Programming Live with Larry · 2:38 · 287 views
LeetCode 2828 : Check if a String Is an Acronym of Words || EASY || C++ || JAVA || Detailed SolutionCodeGPT · 8:45 · 254 views
Leetcode 2828 Check if a String Is an Acronym of WordsTech Diet · 2:50 · 216 views
LeetCode 2828. Check if a String Is an Acronym of Words | Java Solution | EasyMichael Herman · 4:34 · 173 views
Leetcode 2828 :Check if a String Is an Acronym of Words (Easy) | StringBuilder vs String PerformanceTechieGanesh · 4:48 · 114 views
Leetcode 2828 Check if a String Is anAcronym of Words (Java) - Beats 100%TheAnalyticGuy · 4:02 · 103 views
The problem
Given an array of strings words and a string s, determine if s is an acronym of words.
The string s is considered an acronym of words if it can be formed by concatenating the first character of each string in words in order. For example, "ab" can be formed from ["apple", "banana"], but it can't be formed from ["bear", "aardvark"].
Return true if s is an acronym of words, and false otherwise.
Example 1:
Input: words = ["alice","bob","charlie"], s = "abc" Output: true Explanation: The first character in the words "alice", "bob", and "charlie" are 'a', 'b', and 'c', respectively. Hence, s = "abc" is the acronym.
Example 2:
Input: words = ["an","apple"], s = "a" Output: false Explanation: The first character in the words "an" and "apple" are 'a' and 'a', respectively. The acronym formed by concatenating these characters is "aa". Hence, s = "a" is not the acronym.
Example 3:
Input: words = ["never","gonna","give","up","on","you"], s = "ngguoy" Output: true Explanation: By concatenating the first character of the words in the array, we get the string "ngguoy". Hence, s = "ngguoy" is the acronym.
Constraints:
1 <= words.length <= 1001 <= words[i].length <= 101 <= s.length <= 100words[i]andsconsist of lowercase English letters.
Approach overview
Problem Overview: You receive an array of words and a string s. The task is to determine whether s equals the acronym formed by taking the first character of every word in the array, in order.
Approach 1: Iterative String Concatenation (O(n) time, O(n) space)
Build the acronym explicitly. Iterate through the array of words and append the first character of each word to a temporary string. After the loop, compare the generated acronym with s. If both strings are identical, return true; otherwise return false. This approach is straightforward and easy to reason about because you recreate the expected acronym before comparing it.
The main cost comes from constructing the new string, which requires O(n) time for n words and O(n) extra space to store the acronym. This approach is useful when clarity is more important than strict memory efficiency.
Approach 2: Index-Based Character Matching (O(n) time, O(1) space)
A more space-efficient approach compares characters directly without building a new string. First check if s.length() equals the number of words. If the lengths differ, the acronym cannot match. Then iterate through the word list and compare the first character of each word with the corresponding character in s.
If any comparison fails, return false immediately. If the loop completes successfully, the acronym matches and you return true. This method relies on simple index access in a string and sequential traversal of the array.
The algorithm runs in O(n) time because each word is inspected once. Space complexity is O(1) since no additional data structures are created. The early length check also prevents unnecessary comparisons.
Recommended for interviews: Index-Based Character Matching is typically expected. It demonstrates awareness of unnecessary allocations and keeps the solution clean and efficient. Showing the concatenation approach first proves you understand the problem transformation, but the index-based method shows stronger attention to space optimization and early validation checks.
Approach 1: Iterative String Concatenation
This approach involves iterating over each word, extracting the first character, and concatenating these characters to form a new string. Finally, compare this concatenated string with the string s. If they are equal, s is an acronym; otherwise, it is not.
def is_acronym(words, s):
acronym = ''.join(word[0] for word in words)
return acronym == s
words = ["alice", "bob", "charlie"]
s = "abc"
print(is_acronym(words, s))import java.util.*;
class Solution {
public boolean isAcronym(List<String> words, String s) {
StringBuilder acronym = new StringBuilder();
for (String word : words) {
acronym.append(word.charAt(0));
}
return acronym.toString().equals(s);
}
public static void main(String[] args) {
Solution sol = new Solution();
List<String> words = Arrays.asList("alice", "bob", "charlie");
String s = "abc";
System.out.println(sol.isAcronym(words, s));
}
}#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool isAcronym(vector<string>& words, string s) {
string acronym = "";
for (auto &word : words) {
acronym += word[0];
}
return acronym == s;
}
int main() {
vector<string> words = {"alice", "bob", "charlie"};
string s = "abc";
cout << (isAcronym(words, s) ? "true" : "false") << endl;
return 0;
}function isAcronym(words, s) {
const acronym = words.map(word => word[0]).join('');
return acronym === s;
}
const words = ["alice", "bob", "charlie"];
const s = "abc";
console.log(isAcronym(words, s));#include <stdbool.h>
#include <string.h>
#include <stdio.h>
bool isAcronym(char** words, int wordsSize, char* s) {
char acronym[101] = "";
for (int i = 0; i < wordsSize; ++i) {
strncat(acronym, &words[i][0], 1);
}
return strcmp(acronym, s) == 0;
}
int main() {
char* words[] = {"alice", "bob", "charlie"};
char* s = "abc";
printf("%s\n", isAcronym(words, 3, s) ? "true": "false");
return 0;
}using System;
using System.Collections.Generic;
public class Solution {
public bool IsAcronym(List<string> words, string s) {
string acronym = "";
foreach (string word in words) {
acronym += word[0];
}
return acronym == s;
}
public static void Main(string[] args) {
Solution sol = new Solution();
List<string> words = new List<string> {"alice", "bob", "charlie"};
string s = "abc";
Console.WriteLine(sol.IsAcronym(words, s));
}
}This Python code uses a generator expression within the join() method to form the acronym, which is compared to s.
Time Complexity: O(n), where n is the length of `words`.
Space Complexity: O(1), aside from input storage.
Approach 2: Index-Based Character Matching
For this approach, directly compare the i-th character in s with the first character of the i-th word in words. This eliminates the need for an additional string construction, thus potentially speeding up the execution by doing the comparison simultaneously during the iteration.
def is_acronym(words, s):
if len(s) != len(words):
return False
return all(s[i] == words[i][0] for i in range(len(s)))
words = ["alice", "bob", "charlie"]
s = "abc"
print(is_acronym(words, s))import java.util.*;
class Solution {
public boolean isAcronym(List<String> words, String s) {
if (s.length() != words.size()) return false;
for (int i = 0; i < words.size(); i++) {
if (s.charAt(i) != words.get(i).charAt(0)) return false;
}
return true;
}
public static void main(String[] args) {
Solution sol = new Solution();
List<String> words = Arrays.asList("alice", "bob", "charlie");
String s = "abc";
System.out.println(sol.isAcronym(words, s));
}
}#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool isAcronym(vector<string>& words, string s) {
if (s.length() != words.size()) return false;
for (size_t i = 0; i < words.size(); ++i) {
if (s[i] != words[i][0])
return false;
}
return true;
}
int main() {
vector<string> words = {"alice", "bob", "charlie"};
string s = "abc";
cout << (isAcronym(words, s) ? "true" : "false") << endl;
return 0;
}function isAcronym(words, s) {
if (s.length !== words.length) return false;
for (let i = 0; i < words.length; i++) {
if (s[i] !== words[i][0]) return false;
}
return true;
}
const words = ["alice", "bob", "charlie"];
const s = "abc";
console.log(isAcronym(words, s));#include <stdbool.h>
#include <string.h>
#include <stdio.h>
bool isAcronym(char** words, int wordsSize, char* s) {
int len_s = strlen(s);
if (len_s != wordsSize) return false;
for (int i = 0; i < wordsSize; ++i) {
if (s[i] != words[i][0])
return false;
}
return true;
}
int main() {
char* words[] = {"alice", "bob", "charlie"};
char* s = "abc";
printf("%s\n", isAcronym(words, 3, s) ? "true": "false");
return 0;
}using System;
using System.Collections.Generic;
public class Solution {
public bool IsAcronym(List<string> words, string s) {
if (s.Length != words.Count) return false;
for (int i = 0; i < words.Count; i++) {
if (s[i] != words[i][0]) return false;
}
return true;
}
public static void Main(string[] args) {
Solution sol = new Solution();
List<string> words = new List<string> {"alice", "bob", "charlie"};
string s = "abc";
Console.WriteLine(sol.IsAcronym(words, s));
}
}In this Python code, the first check is made to ensure that the lengths of `s` and `words` are equal. Then it uses a generator inside the all function to validate each formation of `s` from `words`.
Time Complexity: O(n), where n is the length of `s` (or words since they must be the same).
Space Complexity: O(1).
Approach 3: Simulation
We can iterate over each string in the array words, concatenate their first letters to form a new string t, and then check if t is equal to s.
The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the array words.
function isAcronym(words: string[], s: string): boolean {
return words.map(w => w[0]).join('') === s;
}func isAcronym(words []string, s string) bool {
t := []byte{}
for _, w := range words {
t = append(t, w[0])
}
return string(t) == s
}impl Solution {
pub fn is_acronym(words: Vec<String>, s: String) -> bool {
words
.iter()
.map(|w| w.chars().next().unwrap_or_default())
.collect::<String>()
== s
}
}Approach 4: Simulation (Space Optimization)
First, we check if the number of strings in words is equal to the length of s. If not, s is definitely not an acronym of the first letters of words, and we directly return false.
Then, we iterate over each character in s, checking if it is equal to the first letter of the corresponding string in words. If not, s is definitely not an acronym of the first letters of words, and we directly return false.
After the iteration, if we haven't returned false, then s is an acronym of the first letters of words, and we return true.
The time complexity is O(n), where n is the length of the array words. The space complexity is O(1).
function isAcronym(words: string[], s: string): boolean {
if (words.length !== s.length) {
return false;
}
for (let i = 0; i < words.length; i++) {
if (words[i][0] !== s[i]) {
return false;
}
}
return true;
}func isAcronym(words []string, s string) bool {
if len(words) != len(s) {
return false
}
for i := range s {
if words[i][0] != s[i] {
return false
}
}
return true
}impl Solution {
pub fn is_acronym(words: Vec<String>, s: String) -> bool {
if words.len() != s.len() {
return false;
}
for (i, w) in words.iter().enumerate() {
if w.chars().next().unwrap_or_default() != s.chars().nth(i).unwrap_or_default() {
return false;
}
}
true
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Iterative String Concatenation | Time Complexity: O(n), where n is the length of `words`. |
| Index-Based Character Matching | Time Complexity: O(n), where n is the length of `s` (or |
| Simulation | – |
| Simulation (Space Optimization) | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Iterative String Concatenation | O(n) | O(n) | When readability and explicit acronym construction help understanding |
| Index-Based Character Matching | O(n) | O(1) | General case and interview settings where constant space is preferred |
Frequently asked questions
Is Check if a String Is an Acronym of Words easy or hard?
Check if a String Is an Acronym of Words is classified as an Easy problem. It focuses on straightforward string and array operations, making it a common introductory exercise for practicing indexing and iteration.
Check if a String Is an Acronym of Words Python/Java solution
In Python or Java, iterate through the list of words and compare each word's first character with the corresponding character in the string. Return false immediately on mismatch. This implementation runs in O(n) time and uses constant extra space.
How to solve Check if a String Is an Acronym of Words in O(n)?
Start by verifying that the length of the acronym string equals the number of words. Then iterate through the array and compare the first character of each word with the character at the same index in the string. If all comparisons match, the string is a valid acronym.
What is the best approach for Check if a String Is an Acronym of Words?
The most efficient approach is index-based character matching. Compare the first character of each word with the corresponding character in the target string while iterating through the array. This avoids building a new string and runs in O(n) time with O(1) extra space.
Is Check if a String Is an Acronym of Words asked at Google/Amazon/Meta?
Problems like this appear in coding interviews at large tech companies as warm-up or screening questions. They test basic string manipulation, array traversal, and attention to edge cases rather than complex algorithms.
What data structure is used in Check if a String Is an Acronym of Words?
The solution primarily uses an array (or list) of strings and a single string for comparison. No advanced data structures are required, making it a basic exercise in array traversal and string indexing.
What is the time complexity of Check if a String Is an Acronym of Words?
The time complexity is O(n), where n is the number of words in the array. Each word is visited once to check its first character against the corresponding position in the acronym string.
