Functional Programming
  • Preface
  • Getting Started
  • Sorting
    • Bubble Sort
    • Merge Sort
    • Insertion Sort
  • Stacks
    • Stack
  • Queues
    • Queue
    • Binary Heap (Priority Queue)
  • Trees
    • Binary Tree (Unbalanced)
    • Prefix Trie
  • Graphs
    • Undirected
    • Directed
    • Edge Weighted
  • Dynamic Programming
    • Knapsack
    • Longest Common Substring
    • Staircase
  • Leetcode/InterviewBit
    • 2 Sum [Easy]
    • Longest Valid Parentheses [Medium-Hard]
    • Kth Smallest Element [Medium]
    • Max Profit [2 variations: 1st Easy 2nd Hard]
    • Pretty Print 2D Matrix [Easy]
    • Max Contiguous Subarray (Kadane's) [Medium (just cause its tricky)]
    • Permutations [Medium]
    • Next Permutation [Medium]
Powered by GitBook
On this page

Was this helpful?

  1. Leetcode/InterviewBit

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 6 years ago

Was this helpful?