Print Multiple Lines

Solve this Problem
Easy5 min
Topics
Companies
Given a name, an age and a city, return a three-line introduction card: "Name: …", "Age: …" and "City: …", one entry per line. On screen, "multiple lines" usually means several print calls, or one print with line breaks inside it. Both ideas appear here. The first solution builds a single string with \nEscape Sequence \nA backslash followed by n, typed as two characters but stored as one newline character that starts a new line when printed. line breaks and then cuts it apart; the second simply builds each line separately. Returning the lines as a list lets every line be checked on its own.

Test Case 1:

Input:name = "Asha", age = 19, city = "Pune"
Output:["Name: Asha", "Age: 19", "City: Pune"]
Explanation:One entry per line, in the order name, age, city.

Test Case 2:

Input:name = "Kiran", age = 7, city = "New Delhi"
Output:["Name: Kiran", "Age: 7", "City: New Delhi"]
Explanation:A single-digit age and a two-word city are handled the same way.

Constraints

  • ◆1 ≤ name.length, city.length ≤ 30
  • ◆1 ≤ age ≤ 120
  • ◆name and city contain letters and spaces only

Try the Dry Run

Approach & Solutions

Single String with Newline EscapesGood

Build the whole card as one string, putting the escape sequence \n wherever a new line should start. \n is a single character that means "line break". Then split that string on \n to get the separate lines. This mirrors how one print call can print several lines at once.

TimeO(n)
SpaceO(n)
class Solution { public String[] introductionCard(String name, int age, String city) { String text = "Name: " + name + "\nAge: " + age + "\nCity: " + city; String[] lines = text.split("\n"); return lines; } }
One Entry per LineOptimal

Skip the newline characters entirely and build each line as its own entry, in order: the name line, the age line, the city line. Each line is constructed exactly once, and there is no splitting step that could go wrong.

TimeO(n)
SpaceO(n)
class Solution { public String[] introductionCard(String name, int age, String city) { String[] lines = new String[3]; lines[0] = "Name: " + name; lines[1] = "Age: " + age; lines[2] = "City: " + city; return lines; } }

Related Problems