Construct a unique matrix n x n for an input n

This is marked as Hard on the geek's platform.

Given an odd integer n, find a matrix of size n x n with the following conditions:

  1. Each cell contains an integer from 1 and n (inclusive).
  2. No integer appears twice in the same row or the same column.
  3. All 1’s must be at every possible distance from the center of the matrix. The center of a n x n square is cell ((n-1)/2, (n-1)/2) for odd n.

Example :

This is a very simple problem based on observation skills.

Steps:

  1. Place all the 1’s at their right position.

Take 2 pointers left=0 and right= nums-1 for columns, and alternatively put 1, while traversing rows(0 to nums-1).

do right=right-1 and left = left+1

2. Now for all the ones put the values from (1–5) at their place. Columnwise put the counting 1–5 like:

Let's jump to the coding part:

Happy Coding!

Software Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store