create account

DSA (Medium) - General - Print A Diamond Shape (Typescript, Python & Rust) by simplestack

View this thread on: hive.blogpeakd.comecency.com
· @simplestack ·
DSA (Medium) - General - Print A Diamond Shape (Typescript, Python & Rust)
<center>
![image.png](https://files.peakd.com/file/peakd-hive/simplestack/AKFAAYwC7MQupaPzNne2j8DdL1orztntzeKs4fQh3z4kp4PAoy4dbwf2w6D8kQk.png)
</center>

Given the following shape:

```
[LOG]: "     A" 
[LOG]: "    B B" 
[LOG]: "   C   C" 
[LOG]: "  D     D" 
[LOG]: " E       E" 
[LOG]: "F         F" 
[LOG]: " E       E" 
[LOG]: "  D     D" 
[LOG]: "   C   C" 
[LOG]: "    B B" 
[LOG]: "     A"
```

Print it to the console.

There were no specific params required but in this case let's do it for an arbitrary number of letters.

# Explanation

Okay, imagine you want to draw a diamond shape using letters. You give me the top half of the letters, like A, B, C. My job is to figure out the rest and print the whole diamond.
Here's the general idea in simple steps (like a recipe):

🔹Get the Full Letter List:
🔸🔸You give me the first half of the letters.
🔸🔸I take those letters and make a copy of them.
🔸🔸I reverse the copy.
🔸🔸I remove the very first letter from the reversed copy (so we don't have the middle letter twice).
🔸🔸I then stick the original letters and the modified reversed letters together. Now I have the complete list of letters for the diamond, going from top to bottom. For example, if you gave me A, B, C, I'd end up with A, B, C, B, A.

🔹Figure Out the Middle:
🔸🔸I count how many letters are in my complete list. Let's say there are 5 letters.
🔸🔸I find the middle position. In a list of 5, the middle is at index 2 (starting from 0). This helps me know how many spaces to put at the beginning of each line.

🔹Draw Each Line:
🔸🔸I go through each letter in my complete list, one by one, from the beginning to the end. For each letter, I'm going to print a line.

🔹Spaces at the Beginning:
🔸🔸For each line, I calculate how many spaces I need at the beginning to make the diamond shape. The lines at the top and bottom need more spaces, and the line in the middle needs no spaces. I use the middle position I found earlier to figure this out. The further a letter is from the middle, the more spaces it gets at the start.
🔸🔸I print those spaces.

🔹The First Letter:
🔸🔸I print the current letter from my list.

🔹Spaces in the Middle (if needed):
🔸🔸If I'm not on the very first or the very last line (because those only have one letter), I need to put spaces between the two identical letters in that row.
🔸🔸I calculate how many spaces go in the middle. The lines closer to the middle have more spaces in between.
🔸🔸I print those middle spaces.

🔹The Second Letter (if needed):
🔸🔸If I added middle spaces, I now print the same letter again to complete the row.

🔹New Line:
🔸🔸After printing the spaces and the letter(s) for the current step, I move to the next line.

```
function printDiamondPattern(firstHalfOfLetters):
  otherHalf = reverse(copy(firstHalfOfLetters))
  removeFirstElement(otherHalf)
  completeLetters = combine(firstHalfOfLetters, otherHalf)
  numberOfRows = length(completeLetters)
  middleRowIndex = floor(numberOfRows / 2)

  for each index 'i' from 0 to numberOfRows - 1:
    currentLetter = completeLetters[i]
    leadingSpaces = absoluteValue(middleRowIndex - i)
    line = ""

    add leadingSpaces to line

    add currentLetter to line

    if i is not 0 and i is not numberOfRows - 1:
      innerSpaces = 2 * (middleRowIndex - leadingSpaces) - 1
      add innerSpaces to line
      add currentLetter to line

    print line
```

# Implementations

## 🐍Python

```
def print_diamond_pattern(letters: list[str]) -> None:
    """
    Prints a diamond pattern to the console based on the provided array of letters.
    The function takes the first half of the diamond's letters and automatically
    generates the second half to create a symmetrical diamond shape.

    Args:
        letters: An array of strings representing the first half of the diamond's letters
                 in ascending order (e.g., ['A', 'B', 'C']).
    """
    # Creates the reversed version of the input array to form the bottom half
    # of the diamond.
    other_half: list[str] = letters[::-1]

    # Removes the first element of the reversed array to avoid duplication
    # of the middle letter in the complete diamond.
    if other_half:
        other_half.pop(0)

    # Combines the original letters and the reversed (shifted) letters to form
    # the complete sequence for the diamond.
    complete_letters: list[str] = letters + other_half

    # Determines the total number of rows in the diamond.
    n: int = len(complete_letters)

    # Calculates the index of the middle row of the diamond. This is used to
    # determine the number of leading spaces for each row.
    middle_index: int = n // 2

    # Iterates through each row of the diamond.
    for i in range(n):
        # Initializes an empty string to build the current row.
        line: str = ""

        # Calculates the number of leading spaces required for the current row
        # to center the diamond. The number of spaces increases as the row gets
        # closer to the top and bottom edges.
        num_spaces: int = abs(middle_index - i)

        # Adds the leading spaces to the current line.
        line += " " * num_spaces

        # Adds the letter for the current row (the first letter of the pair, or the
        # single letter for the top and bottom rows).
        line += complete_letters[i]

        # Checks if the current row is not the very first or the very last row.
        # These rows only contain a single letter.
        if i != 0 and i != n - 1:
            # Calculates the number of spaces between the two identical letters in
            # the current row. This number decreases as the row gets closer to the
            # top and bottom edges.
            inner_spaces: int = 2 * (middle_index - num_spaces) - 1

            # Adds the inner spaces to the current line.
            line += " " * inner_spaces

            # Adds the second identical letter to the current line.
            line += complete_letters[i]

        # Prints the complete line (row) to the console.
        print(line)

# Example usage of the print_diamond_pattern function with an initial array
# representing the first half of the diamond.
print_diamond_pattern(['A', 'B', 'C', 'D', 'E', 'F'])
```

## 🟦Typescript

```
/**
 * Prints a diamond pattern to the console based on the provided array of letters.
 * The function takes the first half of the diamond's letters and automatically
 * generates the second half to create a symmetrical diamond shape.
 *
 * @param letters An array of strings representing the first half of the diamond's letters
 * in ascending order (e.g., ['A', 'B', 'C']).
 */
function printDiamondPattern(letters: string[]): void {
  /**
   * Creates the reversed version of the input array to form the bottom half
   * of the diamond.
   */
  const otherHalf: string[] = [...letters].reverse();

  /**
   * Removes the first element of the reversed array to avoid duplication
   * of the middle letter in the complete diamond.
   */
  otherHalf.shift();

  /**
   * Combines the original letters and the reversed (shifted) letters to form
   * the complete sequence for the diamond.
   */
  const completeLetters: string[] = [...letters, ...otherHalf];

  /**
   * Determines the total number of rows in the diamond.
   */
  const n: number = completeLetters.length;

  /**
   * Calculates the index of the middle row of the diamond. This is used to
   * determine the number of leading spaces for each row.
   */
  const middleIndex: number = Math.floor(n / 2);

  /**
   * Iterates through each row of the diamond.
   */
  for (let i: number = 0; i < n; i++) {
    /**
     * Initializes an empty string to build the current row.
     */
    let line: string = "";

    /**
     * Calculates the number of leading spaces required for the current row
     * to center the diamond. The number of spaces increases as the row gets
     * closer to the top and bottom edges.
     */
    const numSpaces: number = Math.abs(middleIndex - i);

    /**
     * Adds the leading spaces to the current line.
     */
    for (let j: number = 0; j < numSpaces; j++) {
      line += " ";
    }

    /**
     * Adds the letter for the current row (the first letter of the pair, or the
     * single letter for the top and bottom rows).
     */
    line += completeLetters[i];

    /**
     * Checks if the current row is not the very first or the very last row.
     * These rows only contain a single letter.
     */
    if (i !== 0 && i !== n - 1) {
      /**
       * Calculates the number of spaces between the two identical letters in
       * the current row. This number decreases as the row gets closer to the
       * top and bottom edges.
       */
      const innerSpaces: number = 2 * (middleIndex - numSpaces) - 1;

      /**
       * Adds the inner spaces to the current line.
       */
      for (let k: number = 0; k < innerSpaces; k++) {
        line += " ";
      }

      /**
       * Adds the second identical letter to the current line.
       */
      line += completeLetters[i];
    }

    /**
     * Prints the complete line (row) to the console.
     */
    console.log(line);
  }
}

/**
 * Example usage of the printDiamondPattern function with an initial array
 * representing the first half of the diamond.
 */
printDiamondPattern(['A', 'B', 'C', 'D', 'E', 'F']);
```

## 🦀Rust

```
fn print_diamond_pattern(letters: &[&str]) {
    // Creates the reversed version of the input array to form the bottom half
    // of the diamond.
    let mut other_half: Vec<&str> = letters.iter().rev().cloned().collect();

    // Removes the first element of the reversed array to avoid duplication
    // of the middle letter in the complete diamond.
    if !other_half.is_empty() {
        other_half.remove(0);
    }

    // Combines the original letters and the reversed (shifted) letters to form
    // the complete sequence for the diamond.
    let complete_letters: Vec<&str> = letters.iter().chain(other_half.iter()).cloned().collect();

    // Determines the total number of rows in the diamond.
    let n: usize = complete_letters.len();

    // Calculates the index of the middle row of the diamond. This is used to
    // determine the number of leading spaces for each row.
    let middle_index: usize = n / 2;

    // Iterates through each row of the diamond.
    for i in 0..n {
        // Initializes an empty string to build the current row.
        let mut line: String = String::new();

        // Calculates the number of leading spaces required for the current row
        // to center the diamond. The number of spaces increases as the row gets
        // closer to the top and bottom edges.
        let num_spaces: usize = (middle_index as isize - i as isize).abs() as usize;

        // Adds the leading spaces to the current line.
        for _ in 0..num_spaces {
            line.push(' ');
        }

        // Adds the letter for the current row (the first letter of the pair, or the
        // single letter for the top and bottom rows).
        line.push_str(complete_letters[i]);

        // Checks if the current row is not the very first or the very last row.
        // These rows only contain a single letter.
        if i != 0 && i != n - 1 {
            // Calculates the number of spaces between the two identical letters in
            // the current row. This number decreases as the row gets closer to the
            // top and bottom edges.
            let inner_spaces: usize = 2 * (middle_index - num_spaces) - 1;

            // Adds the inner spaces to the current line.
            for _ in 0..inner_spaces {
                line.push(' ');
            }

            // Adds the second identical letter to the current line.
            line.push_str(complete_letters[i]);
        }

        // Prints the complete line (row) to the console.
        println!("{}", line);
    }
}

fn main() {
    // Example usage of the print_diamond_pattern function with an initial array
    // representing the first half of the diamond.
    print_diamond_pattern(&["A", "B", "C", "D", "E", "F"]);
}
```

---

*If you liked this content I’d appreciate an upvote or a comment. That helps me improve the quality of my posts as well as getting to know more about you, my dear reader.*

*Muchas gracias!*

*Follow me for more content like this.*

*[X](https://twitter.com/edca3911) | [PeakD](https://peakd.com/@simplestack) | [Rumble](https://rumble.com/user/simplestack) | [YouTube](https://www.youtube.com/@simple-stack-by-ed) | [Linked In](https://www.linkedin.com/in/edwardcasanova/) | [GitHub](https://github.com/ed3899) | [PayPal.me](https://paypal.me/edca3899?country.x=MX&locale.x=es_XC) | [Medium](https://medium.com/@ed.wacc1995/subscribe)*

*Down below you can find other ways to tip my work.*

```
BankTransfer: "710969000019398639", // CLABE
BAT: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
ETH: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
BTC: "33xxUWU5kjcPk1Kr9ucn9tQXd2DbQ1b9tE",
ADA: "addr1q9l3y73e82hhwfr49eu0fkjw34w9s406wnln7rk9m4ky5fag8akgnwf3y4r2uzqf00rw0pvsucql0pqkzag5n450facq8vwr5e",
DOT: "1rRDzfMLPi88RixTeVc2beA5h2Q3z1K1Uk3kqqyej7nWPNf",
DOGE: "DRph8GEwGccvBWCe4wEQsWsTvQvsEH4QKH",
DAI: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875"
```
👍  ,
properties (23)
authorsimplestack
permlinkdsa-medium-general-print-a-diamond-shape-typescript-python-and-rust
categoryalgorithms
json_metadata"{"app":"peakd/2025.3.6","format":"markdown","description":"This one really took me by surprise on an interview","portfolio":true,"tags":["algorithms","dsa","softwareengineering","softwaredevelopment","python","javascript","typescript","rust","coding","datastructures"],"users":["param","simplestack","simple-stack-by-","ed.wacc1995"],"image":["https://files.peakd.com/file/peakd-hive/simplestack/AKFAAYwC7MQupaPzNne2j8DdL1orztntzeKs4fQh3z4kp4PAoy4dbwf2w6D8kQk.png"]}"
created2025-04-01 17:20:51
last_update2025-04-01 17:20:51
depth0
children1
last_payout2025-04-08 17:20:51
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length13,232
author_reputation-7,742,141,582
root_title"DSA (Medium) - General - Print A Diamond Shape (Typescript, Python & Rust)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id141,825,924
net_rshares0
author_curate_reward""
vote details (2)
@hivebuzz ·
Congratulations @simplestack! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

<table><tr><td><img src="https://images.hive.blog/60x70/https://hivebuzz.me/@simplestack/posts.png?202504011959"></td><td>You published more than 60 posts.<br>Your next target is to reach 70 posts.</td></tr>
</table>

<sub>_You can view your badges on [your board](https://hivebuzz.me/@simplestack) and compare yourself to others in the [Ranking](https://hivebuzz.me/ranking)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>



**Check out our last posts:**
<table><tr><td><a href="/hive-122221/@hivebuzz/pum-202503-result"><img src="https://images.hive.blog/64x128/https://i.imgur.com/mzwqdSL.png"></a></td><td><a href="/hive-122221/@hivebuzz/pum-202503-result">Hive Power Up Month Challenge - March 2025 Winners List</a></td></tr><tr><td><a href="/hive-122221/@hivebuzz/pum-202504"><img src="https://images.hive.blog/64x128/https://i.imgur.com/M9RD8KS.png"></a></td><td><a href="/hive-122221/@hivebuzz/pum-202504">Be ready for the April edition of the Hive Power Up Month!</a></td></tr><tr><td><a href="/hive-122221/@hivebuzz/pud-202504"><img src="https://images.hive.blog/64x128/https://i.imgur.com/805FIIt.jpg"></a></td><td><a href="/hive-122221/@hivebuzz/pud-202504">Hive Power Up Day - April 1st 2025</a></td></tr></table>
properties (22)
authorhivebuzz
permlinknotify-1743537756
categoryalgorithms
json_metadata{"image":["https://hivebuzz.me/notify.t6.png"]}
created2025-04-01 20:02:36
last_update2025-04-01 20:02:36
depth1
children0
last_payout2025-04-08 20:02:36
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,430
author_reputation369,386,296,376,184
root_title"DSA (Medium) - General - Print A Diamond Shape (Typescript, Python & Rust)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id141,828,918
net_rshares0