Print Your Name

Solve this Problem
Easy5 min
Topics
Companies
Given a person's name, return the sentence "My name is <name>.". This is the classic first program, with one twist: instead of printing straight to the screen, the function hands its text back so it can be checked automatically. A program that prints would end with a print call such as System.out.println(result) — everything before that line is identical. The concatenationConcatenationJoining strings end to end to make one longer string, usually written with the + operator. version joins the pieces by hand; the formatted stringFormatted StringA text template with placeholders (%s, {name}) that the language fills in with values. version writes the sentence once and drops the name into a placeholder.

Test Case 1:

Input:name = "Asha"
Output:"My name is Asha."
Explanation:The fixed words, then the name, then a full stop.

Test Case 2:

Input:name = "Ravi Kumar"
Output:"My name is Ravi Kumar."
Explanation:A space inside the name is just another character — it is copied across unchanged.

Constraints

  • ◆1 ≤ name.length ≤ 50
  • ◆name contains letters and spaces only

Try the Dry Run

Approach & Solutions

String ConcatenationGood

Glue three pieces together in order: the fixed text "My name is ", the name that was passed in, and a closing ".". Most languages use the + operator to join strings. C has no string +, so it reserves enough memory and copies the pieces in one by one with strcpy and strcat.

TimeO(n)
SpaceO(n)
class Solution { public String introduce(String name) { String result = "My name is " + name + "."; return result; } }
Formatted StringOptimal

Write the whole sentence once as a template with a placeholder where the name belongs, and let the language fill it in: %s with String.format or sprintf, {name} in a Python f-string, ${name} in a JavaScript template literal. C++ streams the pieces into an ostringstream. The sentence stays readable as one piece of text.

TimeO(n)
SpaceO(n)
class Solution { public String introduce(String name) { return String.format("My name is %s.", name); } }

Related Problems