Coding problem · Easy · Basics
Make an Acronym
Easy Algorithms & data structures
Given a phrase of words separated by single spaces, return its acronym: the first letter of each word, upper-cased.
"portable network graphics" becomes "PNG".
Example 1
Input: phrase = "portable network graphics" Output: "PNG"
Example 2
Input: phrase = "as soon as possible" Output: "ASAP"
Hints
Hint 1
Split the phrase into words and take the first character of each.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(n) · Space O(n)
Map each word to its first letter, join them, and upper-case the result.
Reference solution
function acronym(phrase) {
return phrase.split(' ').map((w) => w[0]).join('').toUpperCase();
}
function acronym(phrase: string): string {
return phrase.split(' ').map((w) => w[0]).join('').toUpperCase();
}
def acronym(phrase: str) -> str:
return ''.join(w[0] for w in phrase.split(' ')).upper()
<?php
function acronym(string $phrase): string
{
return strtoupper(implode('', array_map(fn ($w) => $w[0], explode(' ', $phrase))));
}
class Solution {
public String acronym(String phrase) {
StringBuilder sb = new StringBuilder();
for (String w : phrase.split(" ")) sb.append(w.charAt(0));
return sb.toString().toUpperCase();
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy