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 - Recursive Solution INPUT Grid Size: 2^n x 2^n n = 0 1x1 Grid For n=2: 4x4 grid Q4 (max) Q1 (min) Q3 Q2 Order: Q1 < Q2 < Q3 < Q4 ALGORITHM STEPS 1 Base Case If n=0, return [[0]] 2 Recursive Call Get smaller grid (n-1) 3 Build Quadrants Place 4 copies with offsets +0 +size +2*size +3*size 4 Combine Merge into 2^n grid size = 4^(n-1) FINAL RESULT For n = 0: [[0]] OK - Valid Special Grid For n = 1 (2x2): 0 1 2 3 0 < 1 < 2 < 3 OK - Valid [[0,1],[2,3]] Key Insight: Divide and Conquer: Each quadrant is recursively special with values in specific ranges. Top-right gets smallest values (offset 0), then bottom-right (+size), bottom-left (+2*size), and top-left gets largest (+3*size). This ensures all ordering constraints are satisfied. TutorialsPoint - Fill a Special Grid | Optimal Recursive Solution
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