LeetCode 2828 - Check if a String Is an Acronym of Words

This problem asks us to determine whether a given string s is exactly the acronym formed from an array of words. An acronym is created by taking the first character from each word in the words array and concatenating those characters in the same order as the words appear.

LeetCode Problem 2828

Difficulty: 🟢 Easy
Topics: Array, String

Solution

LeetCode 2828 - Check if a String Is an Acronym of Words

Problem Understanding

This problem asks us to determine whether a given string s is exactly the acronym formed from an array of words.

An acronym is created by taking the first character from each word in the words array and concatenating those characters in the same order as the words appear. After building this acronym, we compare it with the given string s.

For example, if:

words = ["alice", "bob", "charlie"]

the acronym is:

"a" + "b" + "c" = "abc"

Since "abc" matches s, the answer would be true.

The input consists of:

  • words, an array of lowercase English strings.
  • s, a lowercase English string.

The expected output is a boolean value:

  • true if s is exactly equal to the acronym formed from words.
  • false otherwise.

The constraints are very small:

  • At most 100 words.
  • Each word has length at most 10.
  • The target string has length at most 100.

These constraints tell us that efficiency is not a major concern. Even straightforward string construction is easily fast enough.

Several edge cases are worth considering:

  • The length of s may differ from the number of words. In that case, it cannot be a valid acronym.
  • Multiple words may begin with the same letter.
  • There may be only one word in the array.
  • Every word is guaranteed to contain at least one character, so accessing the first character is always safe.

Approaches

Brute Force Approach

A straightforward solution is to generate the entire acronym explicitly.

We iterate through every word in words, extract its first character, append it to a temporary string, and then compare the resulting string with s.

This approach is correct because the problem definition directly states that an acronym is formed by concatenating the first character of every word in order. By constructing exactly that string and comparing it with s, we directly verify whether s is the required acronym.

Although this approach is already fast enough for the given constraints, it creates an additional string containing the full acronym.

Optimal Approach

A small optimization is to avoid constructing the acronym when it is unnecessary.

First, we check whether the number of words equals the length of s. If not, the answer is immediately false, because every word contributes exactly one character to the acronym.

Then we compare each character of s with the first character of the corresponding word. If any mismatch is found, we return false immediately. If all positions match, we return true.

This approach performs the verification directly and can terminate early when a mismatch occurs.

Approach Comparison

Approach Time Complexity Space Complexity Notes
Brute Force O(n) O(n) Build the complete acronym string and compare
Optimal O(n) O(1) Compare characters directly without constructing the acronym

Here, n represents the number of words.

Algorithm Walkthrough

  1. Check whether len(words) equals len(s).

Every word contributes exactly one character to the acronym. Therefore, the acronym length must equal the number of words. If the lengths differ, return false immediately. 2. Iterate through all indices from 0 to len(words) - 1.

Each position in the acronym corresponds to exactly one word. 3. For each index i, compare:

  • words[i][0], the first character of the current word.
  • s[i], the corresponding character in the target string.
  1. If the characters differ, return false.

A single mismatch means the acronym formed from words cannot equal s. 5. If all comparisons succeed, return true.

Every position matches, so s is exactly the acronym formed from the words.

Why it works

The acronym definition requires that the character at position i of the acronym be the first character of words[i]. The algorithm checks this condition for every position. If any position violates the condition, the strings cannot be equal. If every position satisfies the condition and the lengths match, then s must be exactly the acronym formed from words.

Python Solution

from typing import List

class Solution:
    def isAcronym(self, words: List[str], s: str) -> bool:
        if len(words) != len(s):
            return False

        for i in range(len(words)):
            if words[i][0] != s[i]:
                return False

        return True

The implementation begins with a length check. Since every word contributes one character, mismatched lengths immediately eliminate the possibility of a valid acronym.

Next, the code iterates through each word and compares its first character against the corresponding character in s. If any comparison fails, the function returns False immediately.

If the loop finishes without finding a mismatch, every required character matches and the function returns True.

Go Solution

func isAcronym(words []string, s string) bool {
	if len(words) != len(s) {
		return false
	}

	for i := 0; i < len(words); i++ {
		if words[i][0] != s[i] {
			return false
		}
	}

	return true
}

The Go implementation follows the same logic as the Python version. The length check is performed first, followed by a character-by-character comparison.

Since all characters are lowercase English letters, indexing strings by byte is safe here because each character occupies exactly one byte. No special Unicode handling is required.

Worked Examples

Example 1

words = ["alice","bob","charlie"]
s = "abc"

Length check:

len(words) = 3
len(s) = 3

Proceed with comparisons.

i words[i] words[i][0] s[i] Match?
0 alice a a Yes
1 bob b b Yes
2 charlie c c Yes

All positions match.

Return true

Example 2

words = ["an","apple"]
s = "a"

Length check:

len(words) = 2
len(s) = 1

The lengths differ.

Return false

No further work is needed.

Example 3

words = ["never","gonna","give","up","on","you"]
s = "ngguoy"

Length check:

len(words) = 6
len(s) = 6

Proceed with comparisons.

i words[i] words[i][0] s[i] Match?
0 never n n Yes
1 gonna g g Yes
2 give g g Yes
3 up u u Yes
4 on o o Yes
5 you y y Yes

All comparisons succeed.

Return true

Complexity Analysis

Measure Complexity Explanation
Time O(n) We examine the first character of each word once
Space O(1) Only a few variables are used regardless of input size

The algorithm performs a single pass through the words array. Each iteration performs constant-time work, resulting in linear time complexity. No auxiliary data structures proportional to the input size are allocated, so the extra space usage remains constant.

Test Cases

from typing import List

sol = Solution()

assert sol.isAcronym(["alice", "bob", "charlie"], "abc") is True  # example 1
assert sol.isAcronym(["an", "apple"], "a") is False  # example 2, length mismatch
assert sol.isAcronym(["never", "gonna", "give", "up", "on", "you"], "ngguoy") is True  # example 3

assert sol.isAcronym(["apple"], "a") is True  # single word
assert sol.isAcronym(["apple"], "b") is False  # single word mismatch

assert sol.isAcronym(["cat", "dog"], "cd") is True  # normal valid case
assert sol.isAcronym(["cat", "dog"], "dc") is False  # wrong order

assert sol.isAcronym(["aa", "ab", "ac"], "aaa") is True  # repeated initials
assert sol.isAcronym(["aa", "ab", "ac"], "aab") is False  # repeated initials mismatch

assert sol.isAcronym(["x", "y", "z"], "xyz") is True  # single-character words
assert sol.isAcronym(["x", "y", "z"], "xy") is False  # acronym too short

assert sol.isAcronym(["hello", "world"], "hw") is True  # typical case
assert sol.isAcronym(["hello", "world"], "ha") is False  # second character mismatch

assert sol.isAcronym(["a"] * 100, "a" * 100) is True  # maximum word count style case

Test Case Summary

Test Why
["alice","bob","charlie"], "abc" Valid acronym from example
["an","apple"], "a" Length mismatch
["never","gonna","give","up","on","you"], "ngguoy" Longer valid example
["apple"], "a" Single-word success case
["apple"], "b" Single-word failure case
["cat","dog"], "cd" Standard valid acronym
["cat","dog"], "dc" Order matters
["aa","ab","ac"], "aaa" Repeated starting letters
["aa","ab","ac"], "aab" Repeated letters with mismatch
["x","y","z"], "xyz" Single-character words
["x","y","z"], "xy" Acronym shorter than required
["hello","world"], "hw" Typical positive case
["hello","world"], "ha" Character mismatch
100 words starting with 'a' Boundary-size style validation

Edge Cases

Length Mismatch Between Words and String

A common mistake is to compare only the available characters without verifying the lengths first. For example:

words = ["an", "apple"]
s = "a"

The generated acronym would be "aa", not "a". The implementation handles this immediately by checking whether len(words) == len(s) before any character comparisons.

Single Word Input

When there is only one word, the acronym consists of exactly one character. For example:

words = ["apple"]
s = "a"

The algorithm still works because the length check passes and the single comparison verifies whether the first character matches.

Repeated First Letters

Different words may begin with the same character:

words = ["ant", "apple", "arrow"]
s = "aaa"

A buggy solution might accidentally remove duplicates or perform some kind of set-based comparison. The correct implementation compares characters position by position, preserving order and multiplicity.

Mismatch in the Middle

Consider:

words = ["cat", "dog", "bird"]
s = "cxb"

The first and last characters appear correct, but the middle character does not match. The implementation detects this during iteration and immediately returns False, preventing incorrect acceptance of partially matching acronyms.

Single-Character Words

Words may themselves contain only one character:

words = ["a", "b", "c"]
s = "abc"

Since every word is guaranteed to have length at least one, accessing words[i][0] is always valid. The algorithm handles these inputs exactly the same as longer words.