Learn how to print the floyd triangle in javascript.
Floyd triangle is a way to print the numbers in following pattern
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
We will implement a simple algorithm to print the triangle.
Implementation
- We will use two different loops to print the each element on different rows.
- Also we will use a extra variable to keep track of the numbers count.
let floydTriangle = (rows) => { let k = 0; for(let i = 1; i <= rows; i++){ let str = ''; for(let j = 1; j <= i; j++){ //Increment the no; k += 1; //Add the no for each row str += k + ' ' ; } //Print the numbers for each row console.log(str.trim()); } };
Input: floydTriangle(5); Output: "1" "2 3" "4 5 6" "7 8 9 10" "11 12 13 14 15"
Time complexity: O(n ^ 2).
Space complexity: O(1).
Time and Space complexity
- We are using two nested loops to print the triangle, we are printing the count of numbers for each row like n * (n - 1) * (n - 2) ..., so Time complexity is O(n ^ 2).
- We are using constant space, so Space complexity is O(1).