Skip to the code
+25 XP

#730 Masonry Positions with Gaps

medium

A photo gallery lays out cards in columnCount columns, each columnWidth pixels wide, with gap pixels between columns and between cards in a column. Cards are placed in order at the bottom of the shortest column (leftmost on ties).

Write masonryLayout(heights, columnCount, columnWidth, gap) that returns { positions, height }. positions[i] is [x, y], the top-left corner of card i: column c starts at x = c * (columnWidth + gap), and the first card in a column has y = 0, with each next card gap pixels below the previous one. height is the container's height: the bottom of the lowest card, or 0 if there are no cards.

Example 1

Input: heights = [200,120,160,80,140], columnCount = 3, columnWidth = 100, gap = 10
Output: {"positions":[[0,0],[110,0],[220,0],[110,130],[220,170]],"height":310}

Card 3 goes under card 1 at y = 120 + 10. Card 4 goes under card 2 at y = 160 + 10, ending at 310, the lowest bottom.

Example 2

Input: heights = [], columnCount = 2, columnWidth = 50, gap = 8
Output: {"positions":[],"height":0}

No cards, no height.

Constraints

  • 0 <= heights.length <= 10^5, 1 <= heights[i] <= 10^4
  • 1 <= columnCount <= 20, 1 <= columnWidth <= 1000, 0 <= gap <= 100
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).