Christmas Tree with N Tiers
Updated
Problem statement
Draw a Christmas tree with n tiers out of text, and return its rows from top to bottom as an array of strings. The tree follows these rules:
- The tree is
2n + 1characters wide, and every row is centred on the middle column, which is columnnwhen columns are numbered from0. - Tier
k, fork = 1, 2, ..., nfrom the top, hask + 1rows with1, 3, 5, ..., 2k + 1stars. Rowjof a tier, counting from0, isn - jspaces followed by2j + 1copies of'*'. - Below the last tier is the trunk: one row of
nspaces followed by'|'. - No row has spaces after its last character.
Printing the tree would output these strings one per line; here they are returned instead.
Function
christmasTree(n: int) → String[]Examples
Example 1
n = 1return = [" *","***"," |"]- The tree is 3 columns wide. The single tier has 2 rows with 1 and 3 stars.
- The trunk
|sits in the middle column, after 1 space.
Example 2
n = 2return = [" *"," ***"," *"," ***","*****"," |"]- The tree is 5 columns wide, so the middle column has 2 spaces before it.
- Tier 1 has 2 rows (1 and 3 stars), tier 2 has 3 rows (1, 3 and 5 stars), then the trunk.
Example 3
n = 3return = [" *"," ***"," *"," ***"," *****"," *"," ***"," *****","*******"," |"]- The tree is 7 columns wide. Tiers 1, 2 and 3 have 2, 3 and 4 rows, so there are 9 star rows plus the trunk.
- No row has spaces after its last character.
Constraints
1 <= n <= 20
More Verily Onsite Interview questions
Similar questions at other companies
- Bounded Word Guess SolverAtlassian · ONSITE INTERVIEWAtlassian interview questions
- Document Edit EventsClickUp · ONSITE INTERVIEW
- Predict Runtime Method DispatchAMD · ONSITE INTERVIEWAMD interview questions
- Basic String Compression with Length GuardNew Relic · PHONE SCREEN · ONSITE INTERVIEW
- Print Sentences as TableAirbnb · PHONE SCREEN · ONSITE INTERVIEWAirbnb interview questions
- Retry with an Attempt LimitOracle · ONSITE INTERVIEWOracle interview questions
- Extract Error Log ContextFlexTrade · ONSITE INTERVIEWFlexTrade interview questions
- Run-Length Encode Consecutive Letter RunsMorgan Stanley · ONSITE INTERVIEWMorgan Stanley interview questions
- String Pattern ReplacementGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- IPv4 Forward IteratorOpenAI · PHONE SCREEN · ONSITE INTERVIEWOpenAI interview questions