Pretty Print 2D Matrix [Easy]
https://www.interviewbit.com/problems/prettyprint/
Input: 4
Output:
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
Input: 3
Output:
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3
def prettyPrint(A: Int): Array[Array[Int]] = {
@tailrec
def go(at: Int, out: Array[Array[Int]]): Array[Array[Int]] = {
if (at <= 0) out
else {
val start = A - at
val end = (A * 2 - 1) - (A - at)
println(at)
go(
at - 1,
start.until(end).foldLeft(out) { (out, i) =>
out.updated(
i,
out(i).patch(start, Array.fill(at * 2 - 1)(at), at * 2 - 1))
}
)
}
}
go(A - 1, Array.fill(A * 2 - 1)(Array.fill(A * 2 - 1)(A)))
}
PreviousMax Profit [2 variations: 1st Easy 2nd Hard]NextMax Contiguous Subarray (Kadane's) [Medium (just cause its tricky)]
Last updated
Was this helpful?