We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Check if a String Is an Acronym of Words

Number: 2977

Difficulty: Easy

Paid? No

Companies: Uber


Problem Description

Given an array of strings named words and a string s, determine if s is an acronym of words. The string s is formed by concatenating the first character of each word in the words array in order. The task is to verify if the provided s matches this concatenation.


Key Insights

  • The solution requires extracting the first character of each string in the words array.
  • Compare the resulting concatenated string to s.
  • The order of characters must exactly match the order in the words array.
  • Edge cases include when s has a different length than the number of words.

Space and Time Complexity

Time Complexity: O(n) where n is the number of words, as we iterate over each word once. Space Complexity: O(n) for constructing the acronym string.


Solution

The solution involves iterating over the words array, extracting the first character from each word, and concatenating them to form the acronym. Then, we simply compare the resulting string with s. If they are equal, we return true; otherwise, we return false. The approach leverages simple string manipulation and iteration, making it straightforward and efficient.


Code Solutions

# Define the function to check if s is an acronym of words
def isAcronym(words, s):
    # Generate acronym by concatenating the first character of each word
    acronym = "".join(word[0] for word in words)
    # Compare generated acronym with s and return the result
    return acronym == s

# Example usage:
words = ["alice", "bob", "charlie"]
s = "abc"
print(isAcronym(words, s))  # Expected output: True
← Back to All Questions