Print X in JavaScript with O(n^2) Time Complexity


Given a positive integer n print matrix containing an X as in the example below

Example:

Input: n = 5
Output:
x---x
-x-x-
--x--
-x-x-
x---x
Explanation:
Each line contains exactly n = 5 characters and two 'x's.
Each diagonal contains 'x'



Hints:

Notice that on each line there will be exactly two x and the other characters are all -. The only exception is the middle line which will have only one x. How can we use this info?

We can print the matrix line by line. For each line we need to know the two columns where we should print x. How can we know these two columns for every line?

We'll store the columns' indices in two variables firstX and secondX, initially equal to 1 and n respectively for the first line.
How should these variables change from line to line?

firstX should get incremented and secondX should get decremented.
Now for each line, you now the 'special' columns. How will you print that line?

We'll use a for loop to iterate through every column index from 1 to n.
What should we do inside the loop?

We should use an if - else statement and check if the current index is firstX or secondX and if so, print x. Otherwise, print -.

Understanding the Problem

The core challenge of this problem is to generate a matrix of size n x n where the diagonals are marked with 'x' and the rest of the elements are '-'. This problem is significant in understanding how to manipulate and generate patterns in matrices, which is a common task in computer graphics, game development, and algorithm design.

Approach

To solve this problem, we need to understand the pattern of the 'x' characters in the matrix. The 'x' characters appear on the main diagonal (from top-left to bottom-right) and the anti-diagonal (from top-right to bottom-left). For each row i (0-indexed), the 'x' characters will be at positions i and n-1-i.

Naive Solution

A naive solution would involve iterating through each cell of the matrix and checking if it lies on either of the diagonals. This approach, while correct, is not optimal as it involves unnecessary checks for each cell.

Optimized Solution

An optimized solution involves directly calculating the positions of the 'x' characters for each row and constructing the row string accordingly. This reduces the number of checks and simplifies the logic.

Algorithm

The algorithm can be broken down into the following steps:

  1. Initialize two variables firstX and secondX to 0 and n-1 respectively.
  2. Iterate through each row from 0 to n-1.
  3. For each row, construct a string of length n where the characters at positions firstX and secondX are 'x' and the rest are '-'.
  4. Increment firstX and decrement secondX for the next row.
  5. Print the constructed string for each row.

Code Implementation

function printX(n) {
  // Initialize the positions of the 'x' characters
  let firstX = 0;
  let secondX = n - 1;

  // Iterate through each row
  for (let i = 0; i < n; i++) {
    let row = '';

    // Construct the row string
    for (let j = 0; j < n; j++) {
      if (j === firstX || j === secondX) {
        row += 'x';
      } else {
        row += '-';
      }
    }

    // Print the row
    console.log(row);

    // Update the positions for the next row
    firstX++;
    secondX--;
  }
}

// Example usage
printX(5);

Complexity Analysis

The time complexity of this solution is O(n^2) because we iterate through each cell of the n x n matrix. The space complexity is O(1) as we only use a few extra variables for the positions of the 'x' characters.

Edge Cases

Potential edge cases include:

  • n = 1: The matrix will be a single 'x'.
  • n = 2: The matrix will have 'x' characters on all positions.

These edge cases are handled naturally by the algorithm as it correctly calculates the positions of the 'x' characters for any positive integer n.

Testing

To test the solution comprehensively, we can use a variety of test cases:

  • Simple case: n = 3
  • Edge case: n = 1
  • Even number: n = 4
  • Odd number: n = 5

We can use the console to print the output and manually verify the correctness.

Thinking and Problem-Solving Tips

When approaching such problems, it's important to:

  • Understand the pattern or structure of the output.
  • Break down the problem into smaller, manageable parts.
  • Consider edge cases and how the algorithm handles them.
  • Optimize the solution by reducing unnecessary computations.

Practicing similar problems and studying different algorithms can help improve problem-solving skills.

Conclusion

In this blog post, we discussed how to generate a matrix with an 'X' pattern given a positive integer n. We explored the problem definition, understood the core challenge, and developed an optimized solution. By analyzing the complexity and considering edge cases, we ensured the robustness of our solution. Practicing such problems helps in developing a deeper understanding of matrix manipulations and pattern generation.

Additional Resources

For further reading and practice, consider the following resources: