Solve small string and API tasks
NVIDIASoftware Engineer · OnsiteLast updated
This problem tests your ability to handle nested structural validation using stacks and the design of a robust API integration function that aggregates paginated responses.
Part 1: Bracket Validator
Write a function is_valid(s: str) -> bool that determines if a string containing parentheses '()', curly braces '{}', and square brackets '[]' is valid. The string is valid if every opening bracket has a corresponding closing bracket of the same type and brackets are closed in the correct order.
Example:
- Input: "()[]{}", Output: True
- Input: "([)]", Output: False
Part 2: API Aggregator
You are provided a mock interface fetch_page(url: str, page_num: int) -> dict. The API returns a JSON object: {"data": [...], "next_page": int or None}. Write a function get_all_data(base_url: str) -> list that fetches data from all pages until next_page is null and returns a flat list of all items.
Constraints:
page_numstarts at 1.- You should handle basic JSON parsing errors.
- The total number of pages is unknown.
def get_all_data(base_url: str) -> list:
# Implementation here
Edge Cases:
- Empty strings for validation.
- API returning an empty data list or an error code.
- Malformed JSON responses.
Hints
Hint 1
For bracket validation, use a stack to keep track of opening brackets and match them against the most recently added bracket when a closing one is encountered.
Hint 2
For the API task, use a while-loop that continues as long as a valid page number or pointer exists in the previous response.
Hint 3
Remember to handle the case where the API returns an empty list but the next_page pointer is still valid.
Follow-up questions
- How would you modify the bracket validator to support arbitrary custom brackets like '' if they were provided in a dictionary mapping?
- If the API calls are slow, how would you implement concurrent fetching using threading or async/await to speed up the data aggregation?
- How would you handle rate limiting (e.g., 429 Too Many Requests) if the API suddenly throttled your requests?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.