"""Problem-set search, filtering, sorting and paging. The catalogue lives in ``leetcode_questions`` and every list the site renders is produced by one SQL query against it, joined with the signed-in member's ``leetcode_progress`` rows when there is one. Filter state is expressed entirely in the URL so a filtered list can be linked, refreshed and shared. """ from __future__ import annotations import json from contextlib import closing from dataclasses import dataclass, field from typing import Any, Iterable, Sequence from urllib.parse import urlencode from . import content, store # The captured problem-set page rendered the pinned daily question plus # questions 1-100 in one uninterrupted list, so one page is exactly that many # rows. Paging then continues into the rest of the local catalogue. PER_PAGE = 101 MAX_PAGE = 999 # Every key the query layer accepts. ``frequency`` and ``contest-point`` are # deliberately absent from the visible sort menu (``content.SORT_OPTIONS``): # the source prints both behind a Premium lock and captured no values, so the # clone will not offer them as if they were source facts. They stay orderable # here because the stored figures are deterministic and the JSON surface is # expected to sort by any stored column. SORT_COLUMNS: dict[str, str] = { "custom": "q.number", "difficulty": "CASE q.difficulty WHEN 'Easy' THEN 1 WHEN 'Medium' THEN 2" " ELSE 3 END", "acceptance": "q.acceptance", "question-id": "q.number", "title": "LOWER(q.title)", "last-submitted": "COALESCE(p.last_submitted_at, '')", "frequency": "q.frequency", "contest-point": "q.contest_point", } DEFAULT_ORDER: dict[str, str] = { "custom": "asc", "difficulty": "asc", "acceptance": "asc", "question-id": "asc", "title": "asc", "last-submitted": "desc", "frequency": "desc", "contest-point": "desc", } @dataclass class ProblemQuery: category: str = "all" search: str = "" difficulty: str = "" status: str = "" topics: tuple[str, ...] = () language: str = "" sort: str = "custom" order: str = "" page: int = 1 @property def effective_order(self) -> str: if self.order in {"asc", "desc"}: return self.order return DEFAULT_ORDER.get(self.sort, "asc") @property def is_filtered(self) -> bool: return bool( self.search or self.difficulty or self.status or self.topics or self.language or self.sort != "custom" or self.order ) def path(self) -> str: if self.category and self.category != "all": return f"/problemset/{self.category}" return "/problemset/" def as_params(self, **overrides: Any) -> list[tuple[str, str]]: values: list[tuple[str, str]] = [] search = overrides.get("search", self.search) difficulty = overrides.get("difficulty", self.difficulty) status = overrides.get("status", self.status) topics = overrides.get("topics", self.topics) language = overrides.get("language", self.language) sort = overrides.get("sort", self.sort) order = overrides.get("order", self.order) page = overrides.get("page", self.page) if search: values.append(("search", search)) if difficulty: values.append(("difficulty", difficulty)) if status: values.append(("status", status)) for topic in topics: values.append(("topic", topic)) if language: values.append(("language", language)) if sort and sort != "custom": values.append(("sort", sort)) if order: values.append(("order", order)) if page and int(page) > 1: values.append(("page", str(page))) return values def url(self, **overrides: Any) -> str: category = overrides.pop("category", self.category) base = ( f"/problemset/{category}" if category and category != "all" else "/problemset/" ) params = self.as_params(**overrides) return f"{base}?{urlencode(params)}" if params else base def _first(values: Sequence[str]) -> str: for value in values: text = str(value).strip() if text: return text return "" def parse_query(params: Any, category: str = "all") -> ProblemQuery: """Build the query state from the request's own URL parameters.""" getlist = getattr(params, "getlist", None) def values(name: str) -> list[str]: if getlist is not None: return [str(item) for item in getlist(name)] raw = params.get(name) return [] if raw is None else [str(raw)] difficulty = _first(values("difficulty")) if difficulty not in {"", "Easy", "Medium", "Hard"}: difficulty = "" status = _first(values("status")).casefold() if status not in {"", "todo", "solved", "attempted"}: status = "" topics = tuple( topic for topic in dict.fromkeys( item.strip() for item in values("topic") if item.strip() ) if topic in content.ALL_TOPICS ) language = _first(values("language")) if language not in content.LANGUAGE_LABELS: language = "" sort = _first(values("sort")) or "custom" if sort not in SORT_COLUMNS: sort = "custom" order = _first(values("order")).casefold() if order not in {"asc", "desc"}: order = "" try: page = int(_first(values("page")) or "1") except ValueError: page = 1 page = max(1, min(page, MAX_PAGE)) valid_categories = {slug for slug, _ in content.CATEGORIES} return ProblemQuery( category=category if category in valid_categories else "all", search=_first(values("search"))[:120], difficulty=difficulty, status=status, topics=topics, language=language, sort=sort, order=order, page=page, ) @dataclass class ProblemPage: rows: list[dict[str, Any]] = field(default_factory=list) total: int = 0 page: int = 1 per_page: int = PER_PAGE solved: int = 0 catalogue_total: int = 0 @property def pages(self) -> int: return max(1, -(-self.total // self.per_page)) @property def start_index(self) -> int: return 0 if not self.total else (self.page - 1) * self.per_page + 1 @property def end_index(self) -> int: return min(self.total, self.page * self.per_page) @property def is_empty(self) -> bool: return self.total == 0 def _where(query: ProblemQuery, subject_id: str | None) -> tuple[str, list[Any]]: clauses: list[str] = [] parameters: list[Any] = [] if query.category != "all": clauses.append("q.category = ?") parameters.append(query.category) if query.search: clauses.append("(LOWER(q.title) LIKE ? OR CAST(q.number AS TEXT) LIKE ?)") needle = f"%{query.search.casefold()}%" parameters.extend([needle, f"%{query.search.strip()}%"]) if query.difficulty: clauses.append("q.difficulty = ?") parameters.append(query.difficulty) for topic in query.topics: clauses.append("q.topics_json LIKE ?") parameters.append(f'%"{topic}"%') if query.language: clauses.append("q.languages_json LIKE ?") parameters.append(f'%"{query.language}"%') if query.status and subject_id: if query.status == "todo": clauses.append("p.status IS NULL") else: clauses.append("p.status = ?") parameters.append(query.status) elif query.status == "solved" and not subject_id: clauses.append("1 = 0") return (" AND ".join(clauses) if clauses else "1 = 1"), parameters def run_query(query: ProblemQuery, subject_id: str | None) -> ProblemPage: where, parameters = _where(query, subject_id) column = SORT_COLUMNS.get(query.sort, "q.number") direction = "ASC" if query.effective_order == "asc" else "DESC" join_subject = subject_id or "" # The daily question sits above the list, as the captured page rendered it, # but only while the visitor has not chosen their own ordering. pinning = query.sort in {"custom", "question-id"} and not query.order pin = "CASE WHEN q.slug = ? THEN 0 ELSE 1 END, " if pinning else "" pin_parameters: list[Any] = [content.DAILY_SLUG] if pinning else [] with closing(store.connect()) as connection: total_row = connection.execute( "SELECT COUNT(*) FROM leetcode_questions q" " LEFT JOIN leetcode_progress p" " ON p.question_slug = q.slug AND p.subject_id = ?" f" WHERE {where}", [join_subject, *parameters], ).fetchone() total = int(total_row[0]) if total_row is not None else 0 pages = max(1, -(-total // PER_PAGE)) page = min(max(1, query.page), pages) rows = connection.execute( "SELECT q.*, p.status AS member_status," " p.last_submitted_at AS member_last_submitted" " FROM leetcode_questions q" " LEFT JOIN leetcode_progress p" " ON p.question_slug = q.slug AND p.subject_id = ?" f" WHERE {where}" f" ORDER BY {pin}{column} {direction}, q.number ASC" " LIMIT ? OFFSET ?", [ join_subject, *parameters, *pin_parameters, PER_PAGE, (page - 1) * PER_PAGE, ], ).fetchall() catalogue_row = connection.execute( "SELECT COUNT(*) FROM leetcode_questions" ).fetchone() catalogue_total = int(catalogue_row[0]) if catalogue_row is not None else 0 solved = 0 if subject_id: solved_row = connection.execute( "SELECT COUNT(*) FROM leetcode_progress" " WHERE subject_id = ? AND status = 'solved'", (subject_id,), ).fetchone() solved = int(solved_row[0]) if solved_row is not None else 0 return ProblemPage( rows=[_public_row(row) for row in rows], total=total, page=page, solved=solved, catalogue_total=catalogue_total, ) def _public_row(row: Any) -> dict[str, Any]: slug = str(row["slug"]) item = content.question(slug) return { "slug": slug, "number": int(row["number"]), "title": row["title"], "difficulty": row["difficulty"], "difficulty_label": content.difficulty_label(str(row["difficulty"])), "category": row["category"], "topics": json.loads(row["topics_json"]), "languages": json.loads(row["languages_json"]), "acceptance": float(row["acceptance"]), "frequency": int(row["frequency"]), "contest_point": int(row["contest_point"]), "status": row["member_status"], "last_submitted": row["member_last_submitted"], "is_daily": slug == content.DAILY_SLUG, "workspace_ready": bool(item and item.workspace_ready), } def random_slug(query: ProblemQuery, subject_id: str | None, seed: str = "") -> str | None: """Pick one question from the active filter for the shuffle control.""" import random where, parameters = _where(query, subject_id) with closing(store.connect()) as connection: slugs = [ str(row["slug"]) for row in connection.execute( "SELECT q.slug FROM leetcode_questions q" " LEFT JOIN leetcode_progress p" " ON p.question_slug = q.slug AND p.subject_id = ?" f" WHERE {where} ORDER BY q.number", [subject_id or "", *parameters], ) ] if not slugs: return None chooser = random.Random(seed) if seed else random.Random() return chooser.choice(slugs) def topic_counts(category: str = "all") -> list[tuple[str, int]]: counts: dict[str, int] = {} for question in content.iter_questions(): if category != "all" and question.category != category: continue for topic in question.topics: counts[topic] = counts.get(topic, 0) + 1 return sorted(counts.items(), key=lambda item: (-item[1], item[0])) def category_counts() -> dict[str, int]: counts: dict[str, int] = {"all": 0} for question in content.iter_questions(): counts["all"] += 1 counts[question.category] = counts.get(question.category, 0) + 1 return counts def iter_pages(page: int, pages: int) -> Iterable[int]: window = {1, pages, page, page - 1, page + 1} return sorted(number for number in window if 1 <= number <= pages)