Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    One page of products, in a stable order

    MediumAbout 25 minFull AccessLearn it: Skip, Take and Paging: O(1) Seeks, O(skip) Walks and Quadratic Paging

    The task

    The shop's product list is shown one page at a time, cheapest first. A product must never show up on two pages, or on none.

    Complete Page(List<Product> products, int page, int pageSize). Product is a record with an Id, a Name and a Price. Sort the products by Price, lowest first, and products with the same price by Id, smallest first. Pages are numbered from 1 and hold pageSize products each; return the products of page page, in that order. A page past the end gives an empty list, and the last page may be short. If page or pageSize is less than 1, throw an ArgumentOutOfRangeException. Do not change the input list. The list and its products are never null, ids are unique, and page times pageSize is at most 1,000,000,000.

    Signature

    public record Product(int Id, string Name, decimal Price);
    public static List<Product> Page(List<Product> products, int page, int pageSize)

    Examples

    • products [(3, "cap", 5), (1, "mug", 5), (2, "pen", 2), (4, "bag", 9)], page 1, pageSize 2 → [(2, "pen", 2), (1, "mug", 5)]. The pen is cheapest; the cap and the mug cost the same, so the smaller id, the mug, comes first.
    • the same products, page 3, pageSize 2 → []. Four products make only two pages.

    Limits: Up to 300,000 products.

    The tests check: the first page, the next page continuing where the first stopped, a page past the end, a short last page, equal prices ordered by id, every product on exactly one page, a page or page size below 1 refused, that the input list is not changed, and a deep page of 300,000 products in time.

    Hints

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      public record Product(int Id, string Name, decimal Price);
      
      public static class Solution
      {
          // Page number `page` (from 1) of the products sorted by price, then id.
          public static List<Product> Page(List<Product> products, int page, int pageSize)
          {
              throw new NotImplementedException();
          }
      }

      This problem comes with TechInterviewNotes Full Access

      Unlock all paid content on TechInterviewNotes.