Web Crawling Discovery and Bracket Syntax Check
Trees & GraphsAuto-graded · 23 test casesLast updated
Perform a depth-bounded graph traversal over web pages based on domain filtering, and validate balanced brackets using a stack.
You are tasked with implementing a unified routine that processes two distinct sub-problems: traversing a simulated web graph and verifying a sequence of bracket characters.
Part 1: Graph Traversal (Web Crawler)
Given a directory of web pages pages, a list of starting seed URLs start_urls, a maximum crawling depth max_depth, and an allowed set of host domains domain_filter:
- A URL is permitted if its parsed hostname (e.g.,
urlparse(url).hostname) belongs to the setdomain_filter. - Discovery starts at depth 0 with all valid
start_urls. - Breadth-First Search (BFS) is used to explore outgoing links. An outgoing link found on a page at depth
dis reached at depthd + 1. - Outgoing links are explored only if the current page depth
d < max_depth. Ifdepth >= max_depth, do not inspect its outgoing links. - Record all uniquely discovered valid URLs.
pages is represented as a dictionary mapping a page URL to a tuple/list: [page_title, outgoing_links_list]. If a page URL is missing from pages or has no outgoing links entry, treat its outgoing links list as empty.
Part 2: Bracket Syntax Check
Given a string brackets containing bracket characters ((, ), [, ], {, }):
- Validate whether the brackets match in a balanced, LIFO order.
- If any invalid character is encountered, or a closer fails to match the most recent unmatched opener, the error occurs at that character's 0-based index.
- If all closers match correctly but there are unclosed opening brackets remaining at the end, the error index is defined as
len(brackets). - If the bracket sequence is entirely valid and balanced, there is no error index (represented as
Noneornullin Python/JSON output).
Return a dictionary with two keys:
'discovered_urls': A lexicographically sorted list of all unique discovered valid URLs.'bracket_error_index': The integer index of the first bracket error, orNoneif valid.
Constraints
0 <= len(start_urls) <= 10^40 <= max_depth <= 100domain_filtercontains valid domain names (e.g.,"example.com").bracketscontains only bracket characters standard to matching problems.len(brackets) <= 10^5
Examples
Example 1
Input: crawl_and_validate({'https://snowflake.com/': ['home', ['https://snowflake.com/about']], 'https://snowflake.com/about': ['about', ['https://snowflake.com/jobs', 'https://other.com/']], 'https://snowflake.com/jobs': ['jobs', []]}, ['https://snowflake.com/'], 2, ['snowflake.com'], '([]{})')
Output: {'discovered_urls': ['https://snowflake.com/', 'https://snowflake.com/about', 'https://snowflake.com/jobs'], 'bracket_error_index': None}
Example 2
Input: crawl_and_validate({'https://a.com/': ['home', ['https://a.com/x', 'https://b.com/y']], 'https://a.com/x': ['x', ['https://a.com/z']], 'https://a.com/z': ['z', ['https://a.com/']]}, ['https://a.com/'], 2, ['a.com'], '([)]')
Output: {'discovered_urls': ['https://a.com/', 'https://a.com/x', 'https://a.com/z'], 'bracket_error_index': 2}
Example 3
Input: crawl_and_validate({'https://a.com/': ['home', ['https://a.com/x']], 'https://a.com/x': ['x', ['https://a.com/']]}, ['https://a.com/'], 0, ['a.com'], '(((')
Output: {'discovered_urls': ['https://a.com/'], 'bracket_error_index': 3}
Hints
Hint 1
For the crawler, use a queue for standard BFS traversal tracking `(url, depth)` and a `set` to track visited/discovered URLs to prevent duplicate visits.
Hint 2
Only expand outgoing links from a page if its current depth is strictly less than `max_depth`.
Hint 3
For bracket validation, push opening brackets onto a stack. When encountering a closing bracket, check if the stack top matches. If any character is not a standard bracket or mismatches, report the current index. If leftover openers remain after iterating, return the string's total length.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem combines graph traversal (BFS) with sequence validation using a stack.
Part 1: Web Crawling Traversal
- Filtering: We maintain a
setof allowed domains for quick $O(1)$ lookups. Hostnames are extracted usingurlparse(url).hostname. - Breadth-First Search (BFS):
- We initialize a
queuewith valid initial URLs fromstart_urlspaired with depth0. - We maintain a
discoveredset to track all visited URLs and avoid infinite cycles. - For each dequeued URL, if
depth < max_depth, we inspect its outgoing links found inpages. - Any valid outgoing link not yet in
discoveredis added todiscoveredand enqueued withdepth + 1.
- We initialize a
- Output Sorting: The discovered set is converted to a sorted list as required.
Part 2: Bracket Parsing
- Stack Tracking: Iterate through
bracketsindex by index. - Validation:
- Push opening brackets (
(,[,{) onto a stack. - For closing brackets (
),],}), check whether the stack is non-empty and the top matches the corresponding opener. If not, record the current index as the error and terminate loop early. - If an unexpected character appears, record the current index as the error.
- Push opening brackets (
- Trailing Unclosed Brackets: If the loop completes without finding an index error but the stack is non-empty, the error index is
len(brackets).
Complexity Analysis
-
Time Complexity:
- Crawler: $O(V + E)$ where $V$ is the number of discovered URLs and $E$ is the total number of processed links. Sorting $V$ URLs takes $O(V \log V)$.
- Bracket Check: $O(N)$ where $N$ is
len(brackets), since each character is processed at most once. - Overall Time Complexity: $O(V \log V + E + N)$.
-
Space Complexity:
- Crawler: $O(V)$ auxiliary space to store discovered URLs and BFS queue items.
- Bracket Check: $O(N)$ space for the stack in the worst case (all open brackets).
- Overall Space Complexity: $O(V + N)$.
from collections import deque
from typing import Dict, List
from urllib.parse import urlparse
def crawl_and_validate(pages: Dict[str, List], start_urls: List[str], max_depth: int, domain_filter: List[str], brackets: str) -> Dict[str, object]:
allowed = set(domain_filter)
def is_allowed(url: str) -> bool:
return urlparse(url).hostname in allowed
discovered = set()
queue = deque()
for url in start_urls:
if is_allowed(url) and url not in discovered:
discovered.add(url)
queue.append((url, 0))
while queue:
url, depth = queue.popleft()
if depth >= max_depth:
continue
page = pages.get(url)
outgoing_links = page[1] if page and len(page) > 1 else []
for link in outgoing_links:
if is_allowed(link) and link not in discovered:
discovered.add(link)
queue.append((link, depth + 1))
pairs = {')': '(', ']': '[', '}': '{'}
openings = set(pairs.values())
stack = []
error_index = None
for index, char in enumerate(brackets):
if char in openings:
stack.append(char)
elif char in pairs:
if not stack or stack[-1] != pairs[char]:
error_index = index
break
stack.pop()
else:
error_index = index
break
if error_index is None and stack:
error_index = len(brackets)
return {
'discovered_urls': sorted(discovered),
'bracket_error_index': error_index,
}