PPractick

DSA interview question

Pattern 7: Star Pyramid

Easy · Algorithms · Topics: pattern building

The problem

The pyramid is the first pattern where each row needs two segments: leading spaces to centre it, then the stars. Row 1 has one star in the middle, and each row below adds a star on each side. It's the pattern that teaches you to derive two formulas per row, one for the spaces (n − i) and one for the stars (2i − 1). Almost every later symmetric pattern (diamonds, hills, crowns) is built on this one.

Example for n = 3:

  *
 ***
*****

Function signature

vector<string> starPyramid(int n);  // row i: n - i spaces, then 2i - 1 stars

Test cases

Input nOutput rowsExplanation
1"*"One star, no spaces
2" *", "***"Row 1 has one leading space
3" *", " ***", "*****"Stars grow by two, spaces shrink by one
4" *", " ***", " *****", "*******"Last row has 2n − 1 stars

(Confirm: rows have leading spaces for centring but no trailing spaces; some judges also print trailing spaces to make each row 2n − 1 wide.)

How interviewers phrase it

Clarifying questions to ask

  1. Is N the height (number of rows)?
  2. Should rows include trailing spaces?
  3. Print or return?

Follow-ups to expect

  1. "How did you get 2i − 1 stars?"
  2. "And n − i spaces?"
  3. "How wide is the last row?"
  4. "How do you invert it?"
  5. "What's the complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in