Check if a String Is an Acronym of Words - 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.

Input & Output

Example 1 — Basic Valid Acronym
$ Input: words = ["alice","bob","charlie"], s = "abc"
Output: true
💡 Note: Taking first letters: 'a' from "alice", 'b' from "bob", 'c' from "charlie" gives "abc" which matches s
Example 2 — Invalid Acronym
$ Input: words = ["an","apple"], s = "a"
Output: false
💡 Note: First letters are 'a' and 'a', forming "aa", but s = "a" has different length
Example 3 — Single Character Match
$ Input: words = ["never"], s = "n"
Output: true
💡 Note: Single word "never" has first letter 'n' which matches s = "n"

Constraints

  • 1 ≤ words.length ≤ 100
  • 1 ≤ words[i].length ≤ 10
  • 1 ≤ s.length ≤ 100
  • words[i] and s consist of lowercase English letters

Visualization

Tap to expand
Check if String Is an Acronym of Words INPUT words array: a lice [0] b ob [1] c harlie [2] Target string s: "abc" words=["alice","bob","charlie"] s = "abc" ALGORITHM STEPS 1 Initialize Result Create empty string: result="" 2 Loop Through Words For each word in words[] 3 Extract First Char Append word[0] to result 4 Compare Strings Return result == s Building Process: "alice"[0] --> "a" "bob"[0] --> "ab" "charlie"[0] --> "abc" result = "abc" FINAL RESULT String Comparison: Built: "abc" == Target: "abc" true Strings match! s IS an acronym of words Output: true Key Insight: The acronym is formed by concatenating the FIRST character of each word in ORDER. Time complexity O(n) where n is the number of words. Simply iterate through words, build the result string, then compare with s. TutorialsPoint - Check if a String Is an Acronym of Words | String Building Approach
Asked in
Google 25 Amazon 20 Microsoft 15
28.1K Views
Medium Frequency
~8 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen