878899. Inverted Right AngleTriangle

Basic

Inverted Right Angle Triangle

Summary

The problem involves generating an inverted right-angle triangle where each row has a specific number of stars. The number of stars in each row increases by one, and the remaining spaces are filled with underscores. For example, if the input is 5, the output would be:

_____
*** 
__* 
_* 
*

Detailed Explanation

To solve this problem, we can use a simple loop to generate the triangle. We start from the last row (the smallest number of stars) and move upwards.

Here's the step-by-step breakdown:

  1. Start with an empty string result that will store the final output.
  2. Loop through each row from the smallest to the largest, using a variable i to represent the current row.
  3. For each row, calculate the number of stars and underscores needed based on the value of i.
  4. Append the required number of stars and underscores to the result string.
  5. Move on to the next row by incrementing i.

Time complexity: O(n), where n is the input number.

Space complexity: O(1), as we only use a constant amount of space to store the result.

Optimized Solutions

Java

View on GeeksforGeeks
public class Main {
    public static void main(String[] args) {
        int n = 5; // input number
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                if (j == i) {
                    sb.append("*");
                } else {
                    sb.append("_");
                }
            }
            sb.append("\n");
        }
        System.out.println(sb.toString());
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.