Problem · Simulation

Format a Centered Pagination Bar

Learn this problem
MediumMixpanel logoMixpanelFULLTIMEPHONE SCREEN

Problem statement

Format the state of a pagination navigation bar.

The result is a space-separated string containing page numbers and, when pages are hidden, .... Surround currentPage with square brackets. The bar must obey these rules:

  • Show exactly min(totalPages, maxVisiblePages) page-number tokens. Ellipsis tokens do not count as page numbers.
  • Always show pages 1 and totalPages.
  • If not all pages fit, show one consecutive window of the remaining page numbers. Center currentPage in that window when possible; otherwise shift the window toward the nearer boundary.
  • If the interior window has an even number of slots and either centered placement would fit, place currentPage in the left-middle slot so one more page appears to its right.
  • Insert one ... token between any two shown page numbers that are not consecutive.

Return the formatted navigation bar.

Function

paginate(currentPage: int, totalPages: int, maxVisiblePages: int) → String

Examples

Example 1

currentPage = 1totalPages = 30maxVisiblePages = 11return = "[1] 2 3 4 5 6 7 8 9 10 ... 30"

The nine interior slots shift to the beginning, so pages 2 through 10 are shown.

Example 2

currentPage = 5totalPages = 30maxVisiblePages = 11return = "1 2 3 4 [5] 6 7 8 9 10 ... 30"

The centered ideal would begin before the interior boundary, so the window remains at pages 2 through 10.

Example 3

currentPage = 10totalPages = 30maxVisiblePages = 11return = "1 ... 6 7 8 9 [10] 11 12 13 14 ... 30"

The selected page is centered in the nine-page interior window from 6 through 14.

Example 4

currentPage = 24totalPages = 30maxVisiblePages = 11return = "1 ... 20 21 22 23 [24] 25 26 27 28 ... 30"

The selected page is centered in the interior window from 20 through 28.

Example 5

currentPage = 30totalPages = 30maxVisiblePages = 11return = "1 ... 21 22 23 24 25 26 27 28 29 [30]"

The interior window shifts to its latest possible position so the selected last page remains visible.

Example 6

currentPage = 3totalPages = 5maxVisiblePages = 11return = "1 2 [3] 4 5"

All five pages fit, so the result contains no ellipsis.

Constraints

  • 1 <= totalPages <= 10^9.
  • 1 <= currentPage <= totalPages.
  • 3 <= maxVisiblePages <= 101.

More Mixpanel problems

drafts saved locally
public String paginate(int currentPage, int totalPages, int maxVisiblePages) {
    // write your code here
}
currentPage1
totalPages30
maxVisiblePages11
expected"[1] 2 3 4 5 6 7 8 9 10 ... 30"
checking account