175. CSS Grid Layout auto-placement algorithm - dense

JavaScriptCSS

few challengers  - accepted / - tried

This is a follow-up on 174. CSS Grid Layout auto-placement algorithm - sparse, please finish problem 174 first.

Well done on Problem 174, now please implement another packing mode dense with the same requirments.

Below are the same example but in dense mode, note the difference from problem 174.

layout(3, 3, [
  {
    id: 1,
    style: {
      gridColumnStart: 'span 2'
    }
  },
  {
    id: 2,
    style: {
      gridColumnStart: 'span 2'
    }
  },
  {
    id: 3
  },
  {
    id: 4
  },
  {
    id: 5
  }
])

/**
 [
  [1, 1, 3],
  [2, 2, 4], 
  [5, 0, 0]
 ]
 */
layout(3, 3, [
  {
    id: 1,
    style: {
      gridColumnStart: 'span 2',
      gridRowStart: 2
    }
  },
  {
    id: 2,
    style: {
      gridColumnStart: 2,
      gridColumnEnd: 'span 2'
    }
  },
  {
    id: 3
  },
  {
    id: 4
  },
  {
    id: 5
  }
])

/**
 [
  [3, 2, 2],
  [1, 1, 4], 
  [5, 0, 0]
 ]
 */

What is time & space complexity of your approach?