Fill a Special Grid - Problem

You are given a non-negative integer n representing a 2n x 2n grid. You must fill the grid with integers from 0 to 22n - 1 to make it special.

A grid is special if it satisfies all the following conditions:

  • All numbers in the top-right quadrant are smaller than those in the bottom-right quadrant.
  • All numbers in the bottom-right quadrant are smaller than those in the bottom-left quadrant.
  • All numbers in the bottom-left quadrant are smaller than those in the top-left quadrant.
  • Each of its quadrants is also a special grid.

Return the special 2n x 2n grid.

Note: Any 1x1 grid is special.

Input & Output

Example 1 — Base Case
$ Input: n = 0
Output: [[0]]
💡 Note: A 2^0 x 2^0 = 1x1 grid with single element 0. Any 1x1 grid is special by definition.
Example 2 — Small Grid
$ Input: n = 1
Output: [[3,0],[2,1]]
💡 Note: A 2^1 x 2^1 = 2x2 grid. Quadrants: TR=0, BR=1, BL=2, TL=3. Satisfies 0 < 1 < 2 < 3.
Example 3 — Larger Grid
$ Input: n = 2
Output: [[15,14,3,2],[13,12,1,0],[11,10,7,6],[9,8,5,4]]
💡 Note: A 4x4 grid where each 2x2 quadrant is special and follows the ordering: TR < BR < BL < TL

Constraints

  • 0 ≤ n ≤ 6
  • Grid size will be 2n x 2n
  • Numbers range from 0 to 22n - 1

Visualization

Tap to expand
Fill a Special Grid: n=1 → 2x2 GridInput: n = 1Grid size: 2¹ x 2¹ = 2x23021Output: [[3,0],[2,1]]Special Grid ✅0 < 1 < 2 < 3Quadrant Ordering: Top-Right < Bottom-Right < Bottom-Left < Top-LeftEach quadrant is recursively specialTime: O(2^(2n)) | Space: O(2^(2n))
Understanding the Visualization
1
Input
Integer n representing grid size 2^n x 2^n
2
Process
Fill grid maintaining quadrant ordering: TR < BR < BL < TL
3
Output
Special grid where each quadrant is recursively special
Key Takeaway
🎯 Key Insight: Use divide and conquer with proper value range assignment to maintain quadrant ordering at every level
Asked in
Google 25 Microsoft 20 Amazon 18 Facebook 15
35.6K Views
Medium Frequency
~30 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen