This is another whiteboard exercise I was presented with in a real life interview. I had come across this several times in blogs and interview books but I still had to struggle when put on the spot. Solving this while sitting down at home is always going to be ten times easier than trying to think out loud in a roomful of strangers.

I started by misunderstanding the question and then over-thinking it; I was thinking mathematically because instead of being given a number of "rows" as a function parameter, it was presented as the "height". For this particular problem I quickly realized that I had to think in terms of a grid and allow for the spaces to the left of the X's - this was the crux of it. Otherwise I would have ended up with something like this:

X
XX
XXX
XXXX

The best advice I can give anyone in these types of situations is to get into a relaxed state. Think it out loud by asking yourself questions out loud and what it is you are going to actually try to do. Interviewers will then be tuned into your thinking and more able to offer hints as you move through it. Rationalize it in your own mind as you go along.

Here's a working example:

public static void CreateTriangle(int height)
{
    // Number of rows
    for (int i = 1; i <= height; i++)
    {
        // Print spaces
        for (int j =1; j <= (height - i); j++)
        {
            Console.Write(" ");
        }

        // Print X's
        for (int k = 1; k < (i * 2); k++)
        {
            Console.Write("X");
        }
        Console.WriteLine();
    }

    Console.ReadLine();
}

 



Comments (2) -

Heidi
Heidi United States
1/14/2018 3:34:16 PM #

Test. Hi cutie. <3

Ankit
Ankit United States
5/2/2018 10:22:54 AM #

Hello, thanks for sharing this information

Pingbacks and trackbacks (1)+