Amazon Online Assessment (OA) - Fetch Items To Display

A search engine website wants implement a new feature that allows their users to sort their search results.

Each search result consists of a URL, a timestamp, and a relevance score. Given an array of results, the name of the column to sort by, and the sort order (ascending or descending), the page number and size of each page, implement a function that returns a list of results.

Input

sortColumn: a number representing the column to sort by: 0 = URL, 1 = timestamp, 2 = relevance

sortOrder: a number representing the sort order: 0 = ascending, 1 = descending

pageSize: the number of results that is required to be displayed on a single page

pageIndex: the page number, starting from 0

results: a map of URL strings to tuples representing the (relevance, timestamp)

Output

Return a list of URLs to be displayed.

Note

pageSize is never zero, and is always less than the number of results.

Examples

Example 1:

Input:

sortColumn = 1

sortOrder = 0

pageSize = 2

pageIndex = 1

results = [["foo.com", 10, 15], ["bar.com", 3, 4]. ["baz.com", 17, 8]]

Output: ["baz"]
Explanation:

There are 3 results.

Sort them by relevance(sortColumn = 1) in ascending order results = [["bar.com", 3, 4], ["foo.com", 10, 15], ["baz.com", 17, 8]].

Display up to 2 results on each page.

The page 0 contains 2 results ["bar.com", "foo.com"] and page 1 contains only 1 result ["baz.com"].

Therefore, the output is ["baz.com"].

Try it yourself

Solution

Explanation

We sort the results by the sortColumn and order. Then using the pageSize and the pageIndex we can figure out how many results on the previous pages and the index of the first result on the target pageIndex page. For example, pageIndex = 1 and pageSize = 2, there are 1 * 2 = 2 results on page 0 so the index the first result of page 1 should be 2. Finally we return all the results on the target page.

1
1
from typing import Dict, List, Tuple
2
2
3
3
def fetch_results_to_display(sort_column: int, sort_order: int, results_per_page: int, page_index: int, results: Dict[str, Tuple[int, int]]) -> List[str]:
4
-
    # WRITE YOUR BRILLIANT CODE HERE
4
+
    ordered = [(name, rel, price) for name, (rel, price) in results.items()]
5
-
    return []
5
+
    ordered.sort(key=lambda x: x[sort_column], reverse=sort_order == 1) # sort by sort_column and reverse order if needed
6
+
    start_index = results_per_page * page_index # find the start index of the first result on the target page
7
+
    return [name for name, _, _ in ordered[start_index:start_index + results_per_page]] # return only the name of each result on the page
8
+
6
9
if __name__ == '__main__':
7
10
    sort_column = int(input())
8
11
    sort_order = int(input())
9
12
    results_per_page = int(input())
10
13
    page_index = int(input())
Expand 8 lines ...