Find the bug · Easy

Fix the Pagination Helper

Easy Find the bug Most asked

paginate(items, page, pageSize) returns the items for a 1-based page number: page 1 is the first pageSize items. Pages past the end return an empty list.

Users report that page 1 skips the first results and the last page is always empty. Find the bug and fix it.

Example 1

Input: items = [1, 2, 3, 4, 5], page = 1, pageSize = 2
Output: [1, 2]
Explanation: The buggy version returns [3, 4].

Example 2

Input: items = [1, 2, 3, 4, 5], page = 3, pageSize = 2
Output: [5]

Constraints

  • page >= 1, pageSize >= 1

The buggy code

function paginate(items, page, pageSize) {
  const start = page * pageSize;
  return items.slice(start, start + pageSize);
}

Hints

Hint 1

Which index should page 1 start at?

Find and fix the bug

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the bug and the fix

Time O(pageSize) · Space O(pageSize)

The bug: page numbers are 1-based but the offset is computed as page x pageSize, which is the 0-based formula. Every page is shifted by one: page 1 shows page 2, and the real last page is unreachable.

The fix: offset = (page - 1) x pageSize. This is the same arithmetic as SQL LIMIT pageSize OFFSET (page - 1) * pageSize; for large tables, mention that keyset (cursor) pagination avoids scanning skipped rows.

Fixed version

function paginate(items, page, pageSize) {
  const start = (page - 1) * pageSize; // pages are 1-based
  return items.slice(start, start + pageSize);
}

Common mistakes

  • Computing the end index without clamping it to the list length (some languages throw).

Follow-up questions

  • Return totalPages too (ceil(n / pageSize)).
  • Why does OFFSET 100000 get slow in SQL, and what is keyset pagination?