File size: 84,412 Bytes
fb2916f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 | """Seeded local question catalogue.
Three layers, with different provenance, and the difference matters:
*Catalogue rows* — number, title, slug, difficulty, acceptance rate, category
and topic tags for the exact 1,000-problem user-scoped sample — come from
``data/problem_catalogue.json``, which ``tools/build_local_data.py`` derives
mechanically from the Playwright evidence repository. The sample and its
Easy 300 / Medium 500 / Hard 200 split are declared by the evidence's own
``source-instances/scope-target.json``; the source population was enumerated at
4,029, and the other 3,029 problems are explicitly out of scope.
*Captured statement* — description, worked examples, constraints, follow-up,
hints, similar questions and the accepted/submission counters — also comes from
``data/problem_catalogue.json`` and is the text the anonymous Playwright capture
actually saw. 176 of the 1,000 sit behind LeetCode Premium; those rows carry an
explicit ``premium-locked`` access marker instead of an invented statement.
*Judge fixtures* — starter code, visible/hidden test cases, editorial and the
reference implementations used to compute expected output — are locally
authored for the small subset this clone gives a working workspace to. See
``SOURCE_PROVENANCE.md``.
``reference`` callables are ours and are used to compute the *expected* output
of a test case. They are never used to run guest code — see
:mod:`leetcode_app.judge`.
"""
from __future__ import annotations
import json
from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Any, Callable, Iterable, Sequence
DATA_DIR = Path(__file__).resolve().parent / "data"
INDEX: dict[str, Any] = json.loads(
(DATA_DIR / "problem_index.json").read_text(encoding="utf-8")
)
CATALOGUE: dict[str, Any] = json.loads(
(DATA_DIR / "problem_catalogue.json").read_text(encoding="utf-8")
)
#: The solved-count denominator the captured page printed ("0/4029 Solved").
SOURCE_TOTAL: int = int(CATALOGUE["source_population"])
#: The user-scoped sample this clone reconstructs: 1,000 of those 4,029.
SAMPLE_SIZE: int = int(CATALOGUE["sample_size"])
#: The sample's Easy/Medium/Hard split, keyed the way the evidence's
#: ``scope-target.json`` keys it: lowercase ``easy``/``medium``/``hard``. The
#: title-case labels live on :attr:`Question.difficulty`, which is what the
#: source page printed per row; use :func:`difficulty_label` to render one.
SAMPLE_DIFFICULTY_COUNTS: dict[str, int] = {
str(label).casefold(): int(value)
for label, value in CATALOGUE["difficulty_counts"].items()
}
SAMPLE_SELECTION: str = str(CATALOGUE["selection_method"])
#: The question the captured page pinned above the list with a calendar marker.
#: It is number 3069, which the 1,000-problem sample does not include, so the
#: local list pins nothing and says so rather than pinning a different row.
DAILY_SLUG: str = str(INDEX["daily_slug"])
# The captured Developer section offers three Playground samples by name. Their
# bodies were never shown, so the code below is this clone's own.
PLAYGROUND_SNIPPETS: tuple[dict[str, str], ...] = (
{
"title": "Linked List",
"code": (
"class ListNode:\n"
" def __init__(self, value, nxt=None):\n"
" self.value = value\n"
" self.next = nxt\n"
"\n"
"def to_list(head):\n"
" values = []\n"
" while head is not None:\n"
" values.append(head.value)\n"
" head = head.next\n"
" return values\n"
"\n"
"print(to_list(ListNode(1, ListNode(2, ListNode(3)))))"
),
},
{
"title": "Binary Tree",
"code": (
"class TreeNode:\n"
" def __init__(self, value, left=None, right=None):\n"
" self.value = value\n"
" self.left = left\n"
" self.right = right\n"
"\n"
"def inorder(node):\n"
" if node is None:\n"
" return []\n"
" return inorder(node.left) + [node.value] + inorder(node.right)\n"
"\n"
"print(inorder(TreeNode(2, TreeNode(1), TreeNode(3))))"
),
},
{
"title": "Fibonacci",
"code": (
"def fibonacci(n):\n"
" previous, current = 0, 1\n"
" for _ in range(n):\n"
" previous, current = current, previous + current\n"
" return previous\n"
"\n"
"print([fibonacci(n) for n in range(10)])"
),
},
)
ANONYMOUS_JUDGE_NOTICE = "You need to log in / sign up to run or submit"
VERIFICATION_REQUIRED = (
"Complete the verification challenge before continuing: tick the box so the "
"server can match the token it issued to this session."
)
NO_WORKSPACE_NOTICE = (
"This question is listed in the offline catalogue but its statement and "
"judge fixtures are not reproduced, so it cannot be run or submitted here."
)
EASY = "Easy"
MEDIUM = "Medium"
HARD = "Hard"
ALGORITHMS = "algorithms"
DATABASE = "database"
SHELL = "shell"
CONCURRENCY = "concurrency"
JAVASCRIPT = "javascript"
PANDAS = "pandas"
CATEGORIES: tuple[tuple[str, str], ...] = (
("all", "All Topics"),
(ALGORITHMS, "Algorithms"),
(DATABASE, "Database"),
(SHELL, "Shell"),
(CONCURRENCY, "Concurrency"),
(JAVASCRIPT, "JavaScript"),
(PANDAS, "pandas"),
)
LANGUAGE_LABELS: dict[str, str] = {
"cpp": "C++",
"java": "Java",
"python3": "Python3",
"javascript": "JavaScript",
"mysql": "MySQL",
"bash": "Bash",
"pandas": "Pandas",
}
DIFFICULTY_LABELS: dict[str, str] = {EASY: "Easy", MEDIUM: "Med.", HARD: "Hard"}
# The source opens its sort control as a popover the anonymous capture never
# expanded, so the option set below is this clone's own: every entry sorts a
# field the captured list actually printed, plus the member's own last
# submission. Frequency and contest points stay out because the source shows
# both behind a Premium lock and captured no values.
SORT_OPTIONS: tuple[tuple[str, str], ...] = (
("custom", "Custom"),
("question-id", "Question ID"),
("title", "Title"),
("difficulty", "Difficulty"),
("acceptance", "Acceptance"),
("last-submitted", "Last Submitted Time"),
)
STATUS_OPTIONS: tuple[tuple[str, str], ...] = (
("", "Status"),
("todo", "Todo"),
("solved", "Solved"),
("attempted", "Attempted"),
)
DIFFICULTY_OPTIONS: tuple[tuple[str, str], ...] = (
("", "Difficulty"),
(EASY, "Easy"),
(MEDIUM, "Medium"),
(HARD, "Hard"),
)
@dataclass(frozen=True)
class Example:
input: str
output: str
explanation: str = ""
@dataclass(frozen=True)
class SimilarQuestion:
"""One row of the "Similar Questions" list, with its own difficulty.
``slug`` is ``None`` when the captured row names a problem the enumeration
never resolved; such a row is rendered as plain text, never as a link.
"""
slug: str | None
title: str
difficulty: str
@dataclass(frozen=True)
class Question:
number: int
slug: str
title: str
difficulty: str
category: str = ALGORITHMS
topics: tuple[str, ...] = ()
companies: tuple[str, ...] = ()
acceptance: float = 0.0
frequency: int = 0
contest_point: int = 0
summary: str = ""
details: tuple[str, ...] = ()
examples: tuple[Example, ...] = ()
constraints: tuple[str, ...] = ()
hints: tuple[str, ...] = ()
follow_up: str = ""
similar: tuple[str, ...] = ()
languages: tuple[str, ...] = ()
starter: dict[str, str] = field(default_factory=dict)
editorial_title: str = ""
editorial_body: tuple[str, ...] = ()
editorial_code: dict[str, str] = field(default_factory=dict)
community_solutions: tuple[dict[str, str], ...] = ()
cases: tuple[str, ...] = ()
hidden_cases: tuple[str, ...] = ()
#: Parameter names the testcase console labels each input with, in order.
case_labels: tuple[str, ...] = ()
technique_tokens: tuple[str, ...] = ()
wrong_output: str = ""
entry_markers: dict[str, tuple[str, ...]] = field(default_factory=dict)
fixed_expected: dict[str, str] = field(default_factory=dict)
supports_custom_input: bool = True
#: Evidence-derived copy rather than locally authored fixture content.
copy_from_evidence: bool = False
#: Accepted/submission figures the captured detail page printed.
accepted_display: str = ""
submissions_display: str = ""
likes_display: str = ""
discussion_display: str = ""
#: ``public`` (statement captured), ``premium-locked`` (the capture saw the
#: paywall) or ``not-captured``.
access: str = "public"
#: Honest, per-problem notes about what the capture did and did not record.
evidence_notes: tuple[str, ...] = ()
#: The unsplit constraints run exactly as the captured page flattened it.
constraints_text: str = ""
@property
def total_cases(self) -> int:
return len(self.cases) + len(self.hidden_cases)
@property
def has_statement(self) -> bool:
"""Whether a captured public description is reproduced for this row."""
return bool(self.summary)
@property
def premium_locked(self) -> bool:
return self.access == "premium-locked"
@property
def workspace_ready(self) -> bool:
"""Whether this question has a statement and a runnable case set."""
return bool(self.summary and self.cases and self.languages)
@property
def default_language(self) -> str:
return self.languages[0] if self.languages else "python3"
@property
def difficulty_label(self) -> str:
return DIFFICULTY_LABELS.get(self.difficulty, self.difficulty)
# ---------------------------------------------------------------------------
# reference implementations (ours; used only to compute expected output)
# ---------------------------------------------------------------------------
def _two_sum(nums: list[int], target: int) -> list[int]:
seen: dict[int, int] = {}
for index, value in enumerate(nums):
if target - value in seen:
return [seen[target - value], index]
seen[value] = index
return []
def _add_two_numbers(left: list[int], right: list[int]) -> list[int]:
carry = 0
digits: list[int] = []
for position in range(max(len(left), len(right))):
total = carry
if position < len(left):
total += left[position]
if position < len(right):
total += right[position]
carry, digit = divmod(total, 10)
digits.append(digit)
if carry:
digits.append(carry)
return digits
def _longest_unique_substring(text: str) -> int:
start = 0
best = 0
last: dict[str, int] = {}
for index, character in enumerate(text):
if character in last and last[character] >= start:
start = last[character] + 1
last[character] = index
best = max(best, index - start + 1)
return best
def _median_two_sorted(left: list[int], right: list[int]) -> float:
merged = sorted(left + right)
if not merged:
return 0.0
middle = len(merged) // 2
if len(merged) % 2:
return float(merged[middle])
return (merged[middle - 1] + merged[middle]) / 2
def _longest_palindrome(text: str) -> str:
if not text:
return ""
best = text[0]
for center in range(len(text)):
for left, right in ((center, center), (center, center + 1)):
while left >= 0 and right < len(text) and text[left] == text[right]:
left -= 1
right += 1
candidate = text[left + 1 : right]
if len(candidate) > len(best):
best = candidate
return best
def _reverse_integer(value: int) -> int:
sign = -1 if value < 0 else 1
reversed_value = sign * int(str(abs(value))[::-1])
if reversed_value < -(2**31) or reversed_value > 2**31 - 1:
return 0
return reversed_value
def _is_palindrome_number(value: int) -> bool:
return value >= 0 and str(value) == str(value)[::-1]
def _max_water(height: list[int]) -> int:
left, right, best = 0, len(height) - 1, 0
while left < right:
best = max(best, (right - left) * min(height[left], height[right]))
if height[left] < height[right]:
left += 1
else:
right -= 1
return best
_ROMAN = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
def _roman_to_integer(text: str) -> int:
total = 0
for index, character in enumerate(text):
value = _ROMAN[character]
if index + 1 < len(text) and value < _ROMAN[text[index + 1]]:
total -= value
else:
total += value
return total
def _valid_parentheses(text: str) -> bool:
pairs = {")": "(", "]": "[", "}": "{"}
stack: list[str] = []
for character in text:
if character in pairs:
if not stack or stack.pop() != pairs[character]:
return False
else:
stack.append(character)
return not stack
def _merge_sorted_lists(left: list[int], right: list[int]) -> list[int]:
return sorted(left + right)
def _remove_duplicates(nums: list[int]) -> int:
write = 0
for value in nums:
if write == 0 or nums[write - 1] != value:
nums[write] = value
write += 1
return write
def _max_profit(prices: list[int]) -> int:
cheapest = None
best = 0
for price in prices:
if cheapest is None or price < cheapest:
cheapest = price
else:
best = max(best, price - cheapest)
return best
REFERENCES: dict[str, Callable[..., Any]] = {
"two-sum": _two_sum,
"add-two-numbers": _add_two_numbers,
"longest-substring-without-repeating-characters": _longest_unique_substring,
"median-of-two-sorted-arrays": _median_two_sorted,
"longest-palindromic-substring": _longest_palindrome,
"reverse-integer": _reverse_integer,
"palindrome-number": _is_palindrome_number,
"container-with-most-water": _max_water,
"roman-to-integer": _roman_to_integer,
"valid-parentheses": _valid_parentheses,
"merge-two-sorted-lists": _merge_sorted_lists,
"remove-duplicates-from-sorted-array": _remove_duplicates,
"best-time-to-buy-and-sell-stock": _max_profit,
}
def format_expected(value: Any) -> str:
"""Render a reference result the way the result panel shows it."""
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, float):
return f"{value:.5f}"
return json.dumps(value, separators=(",", ":"))
def parse_case(raw: str) -> list[Any]:
"""Parse a test-case block into positional arguments."""
arguments: list[Any] = []
for line in raw.splitlines():
stripped = line.strip()
if not stripped:
continue
arguments.append(json.loads(stripped))
return arguments
# ---------------------------------------------------------------------------
# catalogue
# ---------------------------------------------------------------------------
def _python_stub(signature: str) -> str:
return f"class Solution:\n def {signature}:\n "
_DETAILED: tuple[Question, ...] = (
# The only question whose statement, examples, constraints, hints, similar
# list, stats and starter code were captured directly. Every string below
# is transcribed from the two-sum-desktop evidence snapshot.
Question(
number=1,
slug="two-sum",
title="Two Sum",
difficulty=EASY,
category=ALGORITHMS,
topics=("Array", "Hash Table"),
companies=(),
acceptance=58.0,
frequency=97,
contest_point=3,
copy_from_evidence=True,
accepted_display="23,161,357",
submissions_display="39.9M",
likes_display="69.6K",
discussion_display="2.1K",
summary=(
"You are given an array of integers nums and an integer target, "
"return indices of the two numbers such that they add up to target."
),
details=(
"You may assume that each input would have exactly one solution, "
"and you may not use the same element twice.",
"You can return the answer in any order.",
),
examples=(
Example(
"nums = [2,7,11,15], target = 9",
"[0,1]",
"Because nums[0] + nums[1] == 9, we return [0, 1].",
),
Example("nums = [3,2,4], target = 6", "[1,2]"),
Example("nums = [3,3], target = 6", "[0,1]"),
),
constraints=(
"2 <= nums.length <= 10^4",
"-10^9 <= nums[i] <= 10^9",
"-10^9 <= target <= 10^9",
"Only one valid answer exists.",
),
hints=(
"A really brute force way would be to search for all possible pairs "
"of numbers but that would be too slow. Again, it's best to try out "
"brute force solutions just for completeness. It is from these brute "
"force solutions that you can come up with optimizations.",
"So, if we fix one of the numbers, say x, we have to scan the entire "
"array to find the next number y which is value - x where value is "
"the input parameter. Can we change our array somehow so that this "
"search becomes faster?",
"The second train of thought is, without changing the array, can we "
"use additional space somehow? Like maybe a hash map to speed up the "
"search?",
),
follow_up=(
"Can you come up with an algorithm that is less than O(n^2) time "
"complexity?"
),
similar=(
SimilarQuestion("3sum", "3Sum", MEDIUM),
SimilarQuestion("4sum", "4Sum", MEDIUM),
SimilarQuestion(
"two-sum-ii-input-array-is-sorted",
"Two Sum II - Input Array Is Sorted",
MEDIUM,
),
SimilarQuestion(
"two-sum-iii-data-structure-design",
"Two Sum III - Data structure design",
EASY,
),
SimilarQuestion("subarray-sum-equals-k", "Subarray Sum Equals K", MEDIUM),
SimilarQuestion(
"two-sum-iv-input-is-a-bst", "Two Sum IV - Input is a BST", EASY
),
SimilarQuestion("two-sum-less-than-k", "Two Sum Less Than K", EASY),
SimilarQuestion(
"max-number-of-k-sum-pairs", "Max Number of K-Sum Pairs", MEDIUM
),
SimilarQuestion("count-good-meals", "Count Good Meals", MEDIUM),
SimilarQuestion(
"count-number-of-pairs-with-absolute-difference-k",
"Count Number of Pairs With Absolute Difference K",
EASY,
),
SimilarQuestion(
"number-of-pairs-of-strings-with-concatenation-equal-to-target",
"Number of Pairs of Strings With Concatenation Equal to Target",
MEDIUM,
),
SimilarQuestion(
"find-all-k-distant-indices-in-an-array",
"Find All K-Distant Indices in an Array",
EASY,
),
SimilarQuestion(
"first-letter-to-appear-twice", "First Letter to Appear Twice", EASY
),
SimilarQuestion(
"number-of-excellent-pairs", "Number of Excellent Pairs", HARD
),
SimilarQuestion(
"number-of-arithmetic-triplets", "Number of Arithmetic Triplets", EASY
),
SimilarQuestion(
"node-with-highest-edge-score", "Node With Highest Edge Score", MEDIUM
),
SimilarQuestion(
"check-distances-between-same-letters",
"Check Distances Between Same Letters",
EASY,
),
SimilarQuestion(
"find-subarrays-with-equal-sum", "Find Subarrays With Equal Sum", EASY
),
SimilarQuestion(
"largest-positive-integer-that-exists-with-its-negative",
"Largest Positive Integer That Exists With Its Negative",
EASY,
),
SimilarQuestion(
"number-of-distinct-averages", "Number of Distinct Averages", EASY
),
SimilarQuestion(
"count-pairs-whose-sum-is-less-than-target",
"Count Pairs Whose Sum is Less than Target",
EASY,
),
),
languages=("cpp", "java", "python3", "javascript"),
starter={
# Transcribed from the captured editor pane, including its blank
# body line, so the clone opens on the same six lines.
"cpp": (
"class Solution {\npublic:\n vector<int> twoSum("
"vector<int>& nums, int target) {\n \n }\n};"
),
"java": (
"class Solution {\n public int[] twoSum(int[] nums, int target)"
" {\n \n }\n}"
),
"python3": _python_stub(
"twoSum(self, nums: List[int], target: int) -> List[int]"
),
"javascript": (
"/**\n * @param {number[]} nums\n * @param {number} target\n"
" * @return {number[]}\n */\nvar twoSum = function(nums, target) "
"{\n \n};"
),
},
editorial_title="Approach: one-pass hash table",
editorial_body=(
"Walk the array once. For every value, ask whether the complement "
"target - value has already been seen.",
"Storing each value with its index as you go turns the inner search "
"into a constant-time lookup, so the whole scan is O(n) time and "
"O(n) extra space.",
),
editorial_code={
"python3": (
"class Solution:\n"
" def twoSum(self, nums: List[int], target: int) -> List[int]:\n"
" seen = {}\n"
" for index, value in enumerate(nums):\n"
" if target - value in seen:\n"
" return [seen[target - value], index]\n"
" seen[value] = index\n"
" return []"
)
},
community_solutions=(
{
"author": "hashmap_daily",
"title": "Clean one-pass hash map, beats 98%",
"votes": "1.2K",
"language": "Python3",
},
{
"author": "two_pointer_fan",
"title": "Sort + two pointers when indices are not needed",
"votes": "402",
"language": "C++",
},
),
# Case set and parameter labels as the captured console showed them.
cases=("[2,7,11,15]\n9", "[3,2,4]\n6", "[3,3]\n6"),
case_labels=("nums", "target"),
hidden_cases=("[1,5,9,13]\n22", "[0,4,3,0]\n0"),
technique_tokens=(
"dict",
"map",
"hash",
"seen",
"enumerate",
"for ",
"while ",
),
wrong_output="[]",
),
Question(
number=2,
slug="add-two-numbers",
title="Add Two Numbers",
difficulty=MEDIUM,
category=ALGORITHMS,
topics=("Linked List", "Math", "Recursion"),
companies=("Microsoft", "Amazon"),
acceptance=45.3,
frequency=71,
contest_point=4,
summary=(
"Two non-empty lists represent two non-negative integers stored in "
"reverse order, one digit per node. Add the two numbers and return "
"the sum as a list in the same reverse order."
),
details=("The digits are given least significant first.",),
examples=(
Example("l1 = [2,4,3], l2 = [5,6,4]", "[7,0,8]", "342 + 465 = 807."),
Example("l1 = [0], l2 = [0]", "[0]"),
Example("l1 = [9,9,9], l2 = [1]", "[0,0,0,1]"),
),
constraints=(
"The number of nodes in each list is in the range [1, 100].",
"0 <= Node.val <= 9",
),
hints=("Keep one carry digit while walking both lists together.",),
similar=("two-sum", "merge-two-sorted-lists"),
languages=("cpp", "java", "python3", "javascript"),
starter={
"python3": _python_stub(
"addTwoNumbers(self, l1: List[int], l2: List[int]) -> List[int]"
),
"cpp": (
"class Solution {\npublic:\n vector<int> addTwoNumbers("
"vector<int>& l1, vector<int>& l2) {\n \n }\n};"
),
"java": (
"class Solution {\n public int[] addTwoNumbers(int[] l1,"
" int[] l2) {\n \n }\n}"
),
"javascript": (
"var addTwoNumbers = function(l1, l2) {\n \n};"
),
},
editorial_title="Approach: elementary addition with a carry",
editorial_body=(
"Walk both lists at the same time, adding the two available digits "
"plus the carry from the previous position.",
"Remember to append one final node when the last carry is non-zero.",
),
editorial_code={
"python3": (
"class Solution:\n"
" def addTwoNumbers(self, l1: List[int], l2: List[int])"
" -> List[int]:\n"
" carry, out = 0, []\n"
" for position in range(max(len(l1), len(l2))):\n"
" total = carry\n"
" if position < len(l1):\n"
" total += l1[position]\n"
" if position < len(l2):\n"
" total += l2[position]\n"
" carry, digit = divmod(total, 10)\n"
" out.append(digit)\n"
" if carry:\n"
" out.append(carry)\n"
" return out"
)
},
community_solutions=(
{
"author": "carry_the_one",
"title": "Iterative with dummy head, O(max(m,n))",
"votes": "876",
"language": "Java",
},
),
cases=("[2,4,3]\n[5,6,4]", "[0]\n[0]", "[9,9,9]\n[1]"),
hidden_cases=("[5]\n[5]", "[1,8]\n[0]"),
technique_tokens=("carry", "while ", "for ", "divmod", "%", "next"),
wrong_output="[0]",
),
Question(
number=3,
slug="longest-substring-without-repeating-characters",
title="Longest Substring Without Repeating Characters",
difficulty=MEDIUM,
category=ALGORITHMS,
topics=("Hash Table", "String", "Sliding Window"),
companies=("Amazon", "Adobe", "Bloomberg"),
acceptance=36.8,
frequency=88,
contest_point=4,
summary=(
"Given a string s, find the length of the longest substring that "
"contains no repeated characters."
),
details=("A substring is a contiguous, non-empty run of characters.",),
examples=(
Example('s = "abcabcbb"', "3", 'The answer is "abc", with length 3.'),
Example('s = "bbbbb"', "1"),
Example('s = "pwwkew"', "3"),
),
constraints=(
"0 <= s.length <= 5 * 10^4",
"s consists of English letters, digits, symbols and spaces.",
),
hints=("Slide a window and remember the last index of each character.",),
similar=("longest-palindromic-substring", "two-sum"),
languages=("cpp", "java", "python3", "javascript"),
starter={
"python3": _python_stub(
"lengthOfLongestSubstring(self, s: str) -> int"
),
"cpp": (
"class Solution {\npublic:\n int lengthOfLongestSubstring("
"string s) {\n \n }\n};"
),
"java": (
"class Solution {\n public int lengthOfLongestSubstring("
"String s) {\n \n }\n}"
),
"javascript": "var lengthOfLongestSubstring = function(s) {\n \n};",
},
editorial_title="Approach: sliding window",
editorial_body=(
"Keep a window [start, index]. When the current character was last "
"seen inside the window, move start just past that occurrence.",
"Each character is visited once, so the scan is O(n).",
),
editorial_code={
"python3": (
"class Solution:\n"
" def lengthOfLongestSubstring(self, s: str) -> int:\n"
" last, start, best = {}, 0, 0\n"
" for index, character in enumerate(s):\n"
" if character in last and last[character] >= start:\n"
" start = last[character] + 1\n"
" last[character] = index\n"
" best = max(best, index - start + 1)\n"
" return best"
)
},
community_solutions=(
{
"author": "window_watcher",
"title": "Sliding window with a 128-slot array",
"votes": "990",
"language": "C++",
},
),
cases=('"abcabcbb"', '"bbbbb"', '"pwwkew"'),
hidden_cases=('""', '"dvdf"'),
technique_tokens=("set", "dict", "map", "window", "while ", "for ", "index"),
wrong_output="0",
),
Question(
number=4,
slug="median-of-two-sorted-arrays",
title="Median of Two Sorted Arrays",
difficulty=HARD,
category=ALGORITHMS,
topics=("Array", "Binary Search", "Divide and Conquer"),
companies=("Google", "Apple"),
acceptance=43.1,
frequency=64,
contest_point=6,
summary=(
"Given two sorted arrays nums1 and nums2, return the median of the "
"two arrays combined."
),
details=("The overall run time complexity should be O(log (m+n)).",),
examples=(
Example("nums1 = [1,3], nums2 = [2]", "2.00000", "merged = [1,2,3]."),
Example("nums1 = [1,2], nums2 = [3,4]", "2.50000"),
),
constraints=(
"nums1.length == m",
"nums2.length == n",
"0 <= m <= 1000",
"0 <= n <= 1000",
),
hints=("Binary search the partition point of the shorter array.",),
similar=("merge-two-sorted-lists",),
languages=("cpp", "java", "python3"),
starter={
"python3": _python_stub(
"findMedianSortedArrays(self, nums1: List[int],"
" nums2: List[int]) -> float"
),
"cpp": (
"class Solution {\npublic:\n double findMedianSortedArrays("
"vector<int>& nums1, vector<int>& nums2) {\n \n }\n};"
),
"java": (
"class Solution {\n public double findMedianSortedArrays("
"int[] nums1, int[] nums2) {\n \n }\n}"
),
},
editorial_title="Approach: partition by binary search",
editorial_body=(
"Binary search the shorter array for the split that puts exactly "
"half of the combined elements on the left.",
"A merge is easier to write and is accepted here, but the binary "
"search is what meets the logarithmic bound.",
),
editorial_code={
"python3": (
"class Solution:\n"
" def findMedianSortedArrays(self, nums1, nums2) -> float:\n"
" merged = sorted(nums1 + nums2)\n"
" middle = len(merged) // 2\n"
" if len(merged) % 2:\n"
" return float(merged[middle])\n"
" return (merged[middle - 1] + merged[middle]) / 2"
)
},
community_solutions=(
{
"author": "log_time",
"title": "True O(log(min(m,n))) partition walkthrough",
"votes": "2.1K",
"language": "Java",
},
),
cases=("[1,3]\n[2]", "[1,2]\n[3,4]"),
hidden_cases=("[]\n[1]", "[0,0]\n[0,0]"),
technique_tokens=(
"merge",
"sort",
"binary",
"while ",
"for ",
"partition",
),
wrong_output="0.00000",
),
Question(
number=5,
slug="longest-palindromic-substring",
title="Longest Palindromic Substring",
difficulty=MEDIUM,
category=ALGORITHMS,
topics=("Two Pointers", "String", "Dynamic Programming"),
companies=("Amazon", "Microsoft"),
acceptance=35.4,
frequency=69,
contest_point=4,
summary="Given a string s, return the longest palindromic substring in s.",
details=("A palindrome reads the same forwards and backwards.",),
examples=(
Example('s = "babad"', '"bab"', '"aba" is also a valid answer.'),
Example('s = "cbbd"', '"bb"'),
),
constraints=(
"1 <= s.length <= 1000",
"s consists of digits and English letters.",
),
hints=("Expand around every center, including the gaps between letters.",),
similar=("longest-substring-without-repeating-characters",),
languages=("cpp", "java", "python3", "javascript"),
starter={
"python3": _python_stub("longestPalindrome(self, s: str) -> str"),
"cpp": (
"class Solution {\npublic:\n string longestPalindrome("
"string s) {\n \n }\n};"
),
"java": (
"class Solution {\n public String longestPalindrome(String s)"
" {\n \n }\n}"
),
"javascript": "var longestPalindrome = function(s) {\n \n};",
},
editorial_title="Approach: expand around center",
editorial_body=(
"There are 2n - 1 centers. Expand outwards from each while the "
"characters match and keep the longest run.",
"The scan is O(n^2) time and O(1) extra space.",
),
editorial_code={
"python3": (
"class Solution:\n"
" def longestPalindrome(self, s: str) -> str:\n"
" best = s[:1]\n"
" for center in range(len(s)):\n"
" for left, right in ((center, center),"
" (center, center + 1)):\n"
" while left >= 0 and right < len(s) and"
" s[left] == s[right]:\n"
" left -= 1\n"
" right += 1\n"
" if right - left - 1 > len(best):\n"
" best = s[left + 1:right]\n"
" return best"
)
},
community_solutions=(
{
"author": "center_expand",
"title": "Expand around center, no DP table",
"votes": "654",
"language": "Python3",
},
),
cases=('"babad"', '"cbbd"'),
hidden_cases=('"a"', '"ac"'),
technique_tokens=("expand", "for ", "while ", "dp", "center"),
wrong_output='""',
),
Question(
number=7,
slug="reverse-integer",
title="Reverse Integer",
difficulty=MEDIUM,
category=ALGORITHMS,
topics=("Math",),
companies=("Bloomberg",),
acceptance=29.6,
frequency=41,
contest_point=4,
summary=(
"Given a signed 32-bit integer x, return x with its digits reversed. "
"Return 0 when reversing causes the value to fall outside the signed "
"32-bit range."
),
details=(),
examples=(
Example("x = 123", "321"),
Example("x = -123", "-321"),
Example("x = 1534236469", "0", "The reversed value overflows."),
),
constraints=("-2^31 <= x <= 2^31 - 1",),
hints=("Check the bound before you append the next digit.",),
similar=("palindrome-number",),
languages=("cpp", "java", "python3", "javascript"),
starter={
"python3": _python_stub("reverse(self, x: int) -> int"),
"cpp": (
"class Solution {\npublic:\n int reverse(int x) {\n"
" \n }\n};"
),
"java": "class Solution {\n public int reverse(int x) {\n \n }\n}",
"javascript": "var reverse = function(x) {\n \n};",
},
editorial_title="Approach: pop and push digits with an overflow guard",
editorial_body=(
"Peel digits off with modulo and rebuild the reversed value, "
"checking the 32-bit bound before each multiply.",
),
editorial_code={
"python3": (
"class Solution:\n"
" def reverse(self, x: int) -> int:\n"
" sign = -1 if x < 0 else 1\n"
" value = sign * int(str(abs(x))[::-1])\n"
" if value < -2**31 or value > 2**31 - 1:\n"
" return 0\n"
" return value"
)
},
community_solutions=(
{
"author": "overflow_guard",
"title": "Why the check must happen before the multiply",
"votes": "310",
"language": "C++",
},
),
cases=("123", "-123", "120"),
hidden_cases=("0", "1534236469"),
technique_tokens=("while ", "%", "reversed", "str(", "abs"),
wrong_output="0",
),
Question(
number=9,
slug="palindrome-number",
title="Palindrome Number",
difficulty=EASY,
category=ALGORITHMS,
topics=("Math",),
companies=("Apple",),
acceptance=58.2,
frequency=33,
contest_point=3,
summary=(
"Given an integer x, return true when x reads the same backwards "
"and forwards."
),
details=("Negative values are never palindromes.",),
examples=(
Example("x = 121", "true"),
Example("x = -121", "false", "Reversed it reads -121- which differs."),
Example("x = 10", "false"),
),
constraints=("-2^31 <= x <= 2^31 - 1",),
hints=("Try it without turning the number into a string.",),
similar=("reverse-integer",),
languages=("cpp", "java", "python3", "javascript"),
starter={
"python3": _python_stub("isPalindrome(self, x: int) -> bool"),
"cpp": (
"class Solution {\npublic:\n bool isPalindrome(int x) {\n"
" \n }\n};"
),
"java": (
"class Solution {\n public boolean isPalindrome(int x) {\n"
" \n }\n}"
),
"javascript": "var isPalindrome = function(x) {\n \n};",
},
editorial_title="Approach: reverse half of the number",
editorial_body=(
"Reversing only half the digits avoids any overflow and stops as "
"soon as the remaining prefix is no longer larger.",
),
editorial_code={
"python3": (
"class Solution:\n"
" def isPalindrome(self, x: int) -> bool:\n"
" if x < 0:\n"
" return False\n"
" return str(x) == str(x)[::-1]"
)
},
community_solutions=(
{
"author": "half_reverse",
"title": "No string conversion, reverse half the digits",
"votes": "521",
"language": "Java",
},
),
cases=("121", "-121", "10"),
hidden_cases=("0", "1000021"),
technique_tokens=("str(", "while ", "%", "reverse"),
wrong_output="true",
),
Question(
number=11,
slug="container-with-most-water",
title="Container With Most Water",
difficulty=MEDIUM,
category=ALGORITHMS,
topics=("Array", "Two Pointers", "Greedy"),
companies=("Amazon", "Goldman Sachs"),
acceptance=56.1,
frequency=58,
contest_point=4,
summary=(
"Given an array height of n non-negative integers, pick two lines "
"that together with the x-axis hold the most water and return that "
"amount."
),
details=("You may not slant the container.",),
examples=(
Example("height = [1,8,6,2,5,4,8,3,7]", "49"),
Example("height = [1,1]", "1"),
),
constraints=("2 <= n <= 10^5", "0 <= height[i] <= 10^4"),
hints=("Start at both ends and always move the shorter side inwards.",),
similar=("best-time-to-buy-and-sell-stock",),
languages=("cpp", "java", "python3", "javascript"),
starter={
"python3": _python_stub("maxArea(self, height: List[int]) -> int"),
"cpp": (
"class Solution {\npublic:\n int maxArea(vector<int>& height)"
" {\n \n }\n};"
),
"java": (
"class Solution {\n public int maxArea(int[] height) {\n"
" \n }\n}"
),
"javascript": "var maxArea = function(height) {\n \n};",
},
editorial_title="Approach: two pointers",
editorial_body=(
"The area is bounded by the shorter line, so moving the taller line "
"inwards can never help. Always advance the shorter side.",
),
editorial_code={
"python3": (
"class Solution:\n"
" def maxArea(self, height: List[int]) -> int:\n"
" left, right, best = 0, len(height) - 1, 0\n"
" while left < right:\n"
" best = max(best, (right - left) *"
" min(height[left], height[right]))\n"
" if height[left] < height[right]:\n"
" left += 1\n"
" else:\n"
" right -= 1\n"
" return best"
)
},
community_solutions=(
{
"author": "greedy_walk",
"title": "Proof that moving the shorter line is safe",
"votes": "1.5K",
"language": "Python3",
},
),
cases=("[1,8,6,2,5,4,8,3,7]", "[1,1]"),
hidden_cases=("[4,3,2,1,4]", "[1,2,1]"),
technique_tokens=("while ", "for ", "min(", "max(", "left", "right"),
wrong_output="0",
),
Question(
number=13,
slug="roman-to-integer",
title="Roman to Integer",
difficulty=EASY,
category=ALGORITHMS,
topics=("Hash Table", "Math", "String"),
companies=("Facebook",),
acceptance=63.4,
frequency=47,
contest_point=3,
summary="Given a roman numeral s, convert it to an integer.",
details=(
"A smaller numeral placed before a larger one is subtracted, so IV "
"is four and IX is nine.",
),
examples=(
Example('s = "III"', "3"),
Example('s = "LVIII"', "58", "L = 50, V = 5, III = 3."),
Example('s = "MCMXCIV"', "1994"),
),
constraints=("1 <= s.length <= 15", "s contains only I, V, X, L, C, D, M."),
hints=("Compare each numeral with the one after it.",),
similar=("valid-parentheses",),
languages=("cpp", "java", "python3", "javascript"),
starter={
"python3": _python_stub("romanToInt(self, s: str) -> int"),
"cpp": (
"class Solution {\npublic:\n int romanToInt(string s) {\n"
" \n }\n};"
),
"java": (
"class Solution {\n public int romanToInt(String s) {\n"
" \n }\n}"
),
"javascript": "var romanToInt = function(s) {\n \n};",
},
editorial_title="Approach: look ahead one numeral",
editorial_body=(
"Map every numeral to its value. Subtract when the next numeral is "
"larger, otherwise add.",
),
editorial_code={
"python3": (
"class Solution:\n"
" def romanToInt(self, s: str) -> int:\n"
" values = {'I': 1, 'V': 5, 'X': 10, 'L': 50,"
" 'C': 100, 'D': 500, 'M': 1000}\n"
" total = 0\n"
" for index, character in enumerate(s):\n"
" value = values[character]\n"
" if index + 1 < len(s) and value <"
" values[s[index + 1]]:\n"
" total -= value\n"
" else:\n"
" total += value\n"
" return total"
)
},
community_solutions=(
{
"author": "numeral_notes",
"title": "Single pass, no special cases table",
"votes": "288",
"language": "Java",
},
),
cases=('"III"', '"LVIII"', '"MCMXCIV"'),
hidden_cases=('"IV"', '"MMXXIV"'),
technique_tokens=("dict", "map", "for ", "while ", "values"),
wrong_output="0",
),
Question(
number=20,
slug="valid-parentheses",
title="Valid Parentheses",
difficulty=EASY,
category=ALGORITHMS,
topics=("String", "Stack"),
companies=("Amazon", "Microsoft", "Spotify"),
acceptance=41.9,
frequency=84,
contest_point=3,
summary=(
"Given a string s containing only the characters (), [] and {}, "
"determine whether the brackets are closed in the right order."
),
details=(
"Every opening bracket must be closed by the same type of bracket, "
"and brackets must close in the correct order.",
),
examples=(
Example('s = "()"', "true"),
Example('s = "()[]{}"', "true"),
Example('s = "(]"', "false"),
),
constraints=("1 <= s.length <= 10^4",),
hints=("A stack keeps the most recent unmatched opening bracket on top.",),
similar=("roman-to-integer",),
languages=("cpp", "java", "python3", "javascript"),
starter={
"python3": _python_stub("isValid(self, s: str) -> bool"),
"cpp": (
"class Solution {\npublic:\n bool isValid(string s) {\n"
" \n }\n};"
),
"java": (
"class Solution {\n public boolean isValid(String s) {\n"
" \n }\n}"
),
"javascript": "var isValid = function(s) {\n \n};",
},
editorial_title="Approach: stack",
editorial_body=(
"Push opening brackets. On a closing bracket the top of the stack "
"must be its partner, otherwise the string is invalid.",
"The string is valid only when the stack is empty at the end.",
),
editorial_code={
"python3": (
"class Solution:\n"
" def isValid(self, s: str) -> bool:\n"
" pairs = {')': '(', ']': '[', '}': '{'}\n"
" stack = []\n"
" for character in s:\n"
" if character in pairs:\n"
" if not stack or stack.pop() !="
" pairs[character]:\n"
" return False\n"
" else:\n"
" stack.append(character)\n"
" return not stack"
)
},
community_solutions=(
{
"author": "stack_it_up",
"title": "Stack solution with early exit on odd length",
"votes": "742",
"language": "Python3",
},
),
cases=('"()"', '"()[]{}"', '"(]"'),
hidden_cases=('"([])"', '"(("'),
technique_tokens=("stack", "append", "push", "pop", "for ", "while "),
wrong_output="true",
),
Question(
number=21,
slug="merge-two-sorted-lists",
title="Merge Two Sorted Lists",
difficulty=EASY,
category=ALGORITHMS,
topics=("Linked List", "Recursion"),
companies=("Amazon", "Apple"),
acceptance=65.8,
frequency=62,
contest_point=3,
summary=(
"You are given the heads of two sorted lists. Splice them together "
"into one sorted list and return it."
),
details=(),
examples=(
Example("list1 = [1,2,4], list2 = [1,3,4]", "[1,1,2,3,4,4]"),
Example("list1 = [], list2 = []", "[]"),
Example("list1 = [], list2 = [0]", "[0]"),
),
constraints=(
"The number of nodes in both lists is in the range [0, 50].",
"Both list1 and list2 are sorted in non-decreasing order.",
),
hints=("A dummy head node removes every special case.",),
similar=("add-two-numbers", "median-of-two-sorted-arrays"),
languages=("cpp", "java", "python3", "javascript"),
starter={
"python3": _python_stub(
"mergeTwoLists(self, list1: List[int], list2: List[int])"
" -> List[int]"
),
"cpp": (
"class Solution {\npublic:\n vector<int> mergeTwoLists("
"vector<int>& list1, vector<int>& list2) {\n \n }\n};"
),
"java": (
"class Solution {\n public int[] mergeTwoLists(int[] list1,"
" int[] list2) {\n \n }\n}"
),
"javascript": "var mergeTwoLists = function(list1, list2) {\n \n};",
},
editorial_title="Approach: iterative merge with a dummy head",
editorial_body=(
"Attach the smaller head each round, then append whichever list "
"still has nodes left.",
),
editorial_code={
"python3": (
"class Solution:\n"
" def mergeTwoLists(self, list1, list2) -> List[int]:\n"
" out, i, j = [], 0, 0\n"
" while i < len(list1) and j < len(list2):\n"
" if list1[i] <= list2[j]:\n"
" out.append(list1[i])\n"
" i += 1\n"
" else:\n"
" out.append(list2[j])\n"
" j += 1\n"
" out.extend(list1[i:])\n"
" out.extend(list2[j:])\n"
" return out"
)
},
community_solutions=(
{
"author": "dummy_head",
"title": "Recursive one-liner versus the iterative merge",
"votes": "430",
"language": "C++",
},
),
cases=("[1,2,4]\n[1,3,4]", "[]\n[]", "[]\n[0]"),
hidden_cases=("[5]\n[1,2,3]", "[2,2]\n[2]"),
technique_tokens=("while ", "for ", "next", "recur", "merge"),
wrong_output="[]",
),
Question(
number=26,
slug="remove-duplicates-from-sorted-array",
title="Remove Duplicates from Sorted Array",
difficulty=EASY,
category=ALGORITHMS,
topics=("Array", "Two Pointers"),
companies=("Facebook",),
acceptance=59.3,
frequency=52,
contest_point=3,
summary=(
"Given a sorted array nums, remove the duplicates in place so each "
"unique value appears once, and return the number of unique values."
),
details=("The relative order of the kept values must stay the same.",),
examples=(
Example("nums = [1,1,2]", "2", "nums becomes [1,2,_]."),
Example("nums = [0,0,1,1,1,2,2,3,3,4]", "5"),
),
constraints=(
"1 <= nums.length <= 3 * 10^4",
"nums is sorted in non-decreasing order.",
),
hints=("Keep a write pointer just behind the read pointer.",),
similar=("container-with-most-water",),
languages=("cpp", "java", "python3", "javascript"),
starter={
"python3": _python_stub("removeDuplicates(self, nums: List[int]) -> int"),
"cpp": (
"class Solution {\npublic:\n int removeDuplicates("
"vector<int>& nums) {\n \n }\n};"
),
"java": (
"class Solution {\n public int removeDuplicates(int[] nums)"
" {\n \n }\n}"
),
"javascript": "var removeDuplicates = function(nums) {\n \n};",
},
editorial_title="Approach: two pointers",
editorial_body=(
"One pointer reads every element, the other writes the next unique "
"value. The write pointer ends at the answer.",
),
editorial_code={
"python3": (
"class Solution:\n"
" def removeDuplicates(self, nums: List[int]) -> int:\n"
" write = 0\n"
" for value in nums:\n"
" if write == 0 or nums[write - 1] != value:\n"
" nums[write] = value\n"
" write += 1\n"
" return write"
)
},
community_solutions=(
{
"author": "slow_fast",
"title": "Slow/fast pointer template for in-place removal",
"votes": "265",
"language": "Java",
},
),
cases=("[1,1,2]", "[0,0,1,1,1,2,2,3,3,4]"),
hidden_cases=("[1]", "[2,2,2,2]"),
technique_tokens=("for ", "while ", "pointer", "index", "slow", "write"),
wrong_output="0",
),
Question(
number=121,
slug="best-time-to-buy-and-sell-stock",
title="Best Time to Buy and Sell Stock",
difficulty=EASY,
category=ALGORITHMS,
topics=("Array", "Dynamic Programming"),
companies=("Amazon", "Bloomberg"),
acceptance=54.6,
frequency=76,
contest_point=3,
summary=(
"You are given an array prices where prices[i] is the price of a "
"stock on day i. Choose one day to buy and a later day to sell, and "
"return the largest profit. Return 0 when no profit is possible."
),
details=(),
examples=(
Example(
"prices = [7,1,5,3,6,4]",
"5",
"Buy on day 2 (price = 1) and sell on day 5 (price = 6).",
),
Example("prices = [7,6,4,3,1]", "0", "No transaction is profitable."),
),
constraints=("1 <= prices.length <= 10^5", "0 <= prices[i] <= 10^4"),
hints=("Track the cheapest price seen so far while you scan.",),
similar=("container-with-most-water", "two-sum"),
languages=("cpp", "java", "python3", "javascript"),
starter={
"python3": _python_stub("maxProfit(self, prices: List[int]) -> int"),
"cpp": (
"class Solution {\npublic:\n int maxProfit(vector<int>& prices)"
" {\n \n }\n};"
),
"java": (
"class Solution {\n public int maxProfit(int[] prices) {\n"
" \n }\n}"
),
"javascript": "var maxProfit = function(prices) {\n \n};",
},
editorial_title="Approach: one pass",
editorial_body=(
"Keep the minimum price seen so far and the best profit against it. "
"One scan is enough.",
),
editorial_code={
"python3": (
"class Solution:\n"
" def maxProfit(self, prices: List[int]) -> int:\n"
" cheapest, best = None, 0\n"
" for price in prices:\n"
" if cheapest is None or price < cheapest:\n"
" cheapest = price\n"
" else:\n"
" best = max(best, price - cheapest)\n"
" return best"
)
},
community_solutions=(
{
"author": "one_pass_profit",
"title": "Running minimum, O(n) time O(1) space",
"votes": "980",
"language": "Python3",
},
),
cases=("[7,1,5,3,6,4]", "[7,6,4,3,1]"),
hidden_cases=("[1]", "[2,4,1]"),
technique_tokens=("for ", "while ", "min(", "max(", "profit", "cheapest"),
wrong_output="0",
),
Question(
number=175,
slug="combine-two-tables",
title="Combine Two Tables",
difficulty=EASY,
category=DATABASE,
topics=("Database",),
companies=("Amazon",),
acceptance=76.4,
frequency=44,
contest_point=3,
summary=(
"Write a solution to report the first name, last name, city and "
"state of every person in Person, whether or not an address exists "
"for them in Address."
),
details=("Return the result table in any order.",),
examples=(
Example(
"Person = [[1, 'Wang', 'Allen'], [2, 'Alice', 'Bob']]\n"
"Address = [[1, 2, 'New York City', 'New York']]",
"[['Allen', 'Wang', null, null],"
" ['Bob', 'Alice', 'New York City', 'New York']]",
"There is no address for personId = 1, so the city and state "
"columns are null.",
),
),
constraints=(
"personId is the primary key of Person.",
"addressId is the primary key of Address.",
),
hints=("An outer join keeps rows that have no matching address.",),
similar=("recyclable-and-low-fat-products",),
languages=("mysql",),
starter={"mysql": "# Write your MySQL query statement below\n"},
editorial_title="Approach: left join",
editorial_body=(
"An inner join would drop people who have no address row, so the "
"join has to be a left join from Person.",
),
editorial_code={
"mysql": (
"SELECT p.firstName, p.lastName, a.city, a.state\n"
"FROM Person p\n"
"LEFT JOIN Address a ON p.personId = a.personId;"
)
},
community_solutions=(
{
"author": "join_notes",
"title": "Left join versus inner join on this table pair",
"votes": "150",
"language": "MySQL",
},
),
cases=("Person, Address",),
hidden_cases=("Person only",),
technique_tokens=("left join", "join"),
wrong_output="[]",
supports_custom_input=False,
fixed_expected={
"Person, Address": (
"[['Allen','Wang',null,null],"
"['Bob','Alice','New York City','New York']]"
),
"Person only": "[['Allen','Wang',null,null]]",
},
),
Question(
number=1757,
slug="recyclable-and-low-fat-products",
title="Recyclable and Low Fat Products",
difficulty=EASY,
category=DATABASE,
topics=("Database",),
companies=(),
acceptance=88.1,
frequency=25,
contest_point=3,
summary=(
"Write a solution to find the ids of products that are both low fat "
"and recyclable."
),
details=("Return the result table in any order.",),
examples=(
Example(
"Products = [[0,'Y','N'], [1,'Y','Y'], [2,'N','Y'],"
" [3,'Y','Y'], [4,'N','N']]",
"[[1], [3]]",
"Only products 1 and 3 are both low fat and recyclable.",
),
),
constraints=("product_id is the primary key of Products.",),
hints=("Both flags have to be 'Y' at the same time.",),
similar=("combine-two-tables",),
languages=("mysql",),
starter={"mysql": "# Write your MySQL query statement below\n"},
editorial_title="Approach: filter both flags",
editorial_body=("A single WHERE clause with two equality tests is enough.",),
editorial_code={
"mysql": (
"SELECT product_id\nFROM Products\n"
"WHERE low_fats = 'Y' AND recyclable = 'Y';"
)
},
community_solutions=(
{
"author": "sql_starter",
"title": "The shortest correct WHERE clause",
"votes": "96",
"language": "MySQL",
},
),
cases=("Products",),
hidden_cases=("Products (empty)",),
technique_tokens=("where",),
wrong_output="[]",
supports_custom_input=False,
fixed_expected={"Products": "[[1],[3]]", "Products (empty)": "[]"},
),
Question(
number=195,
slug="tenth-line",
title="Tenth Line",
difficulty=EASY,
category=SHELL,
topics=("Shell",),
companies=(),
acceptance=35.9,
frequency=12,
contest_point=3,
summary=(
"Given a text file file.txt, print only its tenth line. Print "
"nothing when the file has fewer than ten lines."
),
details=(),
examples=(
Example(
"file.txt contains the lines Line 1 through Line 10",
"Line 10",
),
),
constraints=("The solution must be a one-line shell command.",),
hints=("sed, awk, head and tail can all address a line by number.",),
similar=(),
languages=("bash",),
starter={"bash": "# Read from the file file.txt and output the tenth line\n"},
editorial_title="Approach: address the line directly",
editorial_body=(
"sed can print one addressed line and quit; awk can test NR. Either "
"reads the file once.",
),
editorial_code={"bash": "sed -n '10p' file.txt"},
community_solutions=(
{
"author": "one_liner",
"title": "sed, awk, tail | head — three ways",
"votes": "88",
"language": "Bash",
},
),
cases=("file.txt (12 lines)",),
hidden_cases=("file.txt (4 lines)",),
technique_tokens=("sed", "awk", "head", "tail", "nl"),
wrong_output="",
supports_custom_input=False,
fixed_expected={"file.txt (12 lines)": "Line 10", "file.txt (4 lines)": ""},
),
Question(
number=1114,
slug="print-in-order",
title="Print in Order",
difficulty=EASY,
category=CONCURRENCY,
topics=("Concurrency",),
companies=("Microsoft",),
acceptance=68.7,
frequency=21,
contest_point=3,
summary=(
"Three different threads call first, second and third on the same "
"instance. Change the program so that second always runs after "
"first, and third always runs after second."
),
details=(
"The threads may be scheduled in any order, so the ordering has to "
"be enforced by the class itself.",
),
examples=(
Example("nums = [1,2,3]", '"onetwothree"'),
Example(
"nums = [1,3,2]",
'"onetwothree"',
"The call order does not change the printed order.",
),
),
constraints=("nums is a permutation of [1, 2, 3].",),
hints=("Two synchronisation primitives are enough to chain the calls.",),
similar=(),
languages=("python3", "java", "cpp"),
starter={
"python3": (
"class Foo:\n def __init__(self):\n pass\n\n"
" def first(self, printFirst):\n \n\n"
" def second(self, printSecond):\n \n\n"
" def third(self, printThird):\n "
),
"java": (
"class Foo {\n public Foo() {}\n\n"
" public void first(Runnable printFirst) throws"
" InterruptedException {\n \n }\n}"
),
"cpp": (
"class Foo {\npublic:\n Foo() {}\n\n"
" void first(function<void()> printFirst) {\n \n }\n};"
),
},
editorial_title="Approach: chain two events",
editorial_body=(
"Give the class two events. first sets the first event, second "
"waits on it and sets the second, third waits on the second.",
),
editorial_code={
"python3": (
"from threading import Event\n\n\n"
"class Foo:\n"
" def __init__(self):\n"
" self.first_done = Event()\n"
" self.second_done = Event()\n\n"
" def first(self, printFirst):\n"
" printFirst()\n"
" self.first_done.set()\n"
" return None\n\n"
" def second(self, printSecond):\n"
" self.first_done.wait()\n"
" printSecond()\n"
" self.second_done.set()\n"
" return None\n\n"
" def third(self, printThird):\n"
" self.second_done.wait()\n"
" printThird()\n"
" return None"
)
},
community_solutions=(
{
"author": "sync_primitives",
"title": "Events, semaphores and condition variables compared",
"votes": "204",
"language": "Python3",
},
),
cases=("[1,2,3]", "[1,3,2]"),
hidden_cases=("[3,2,1]",),
technique_tokens=(
"lock",
"semaphore",
"event",
"condition",
"barrier",
"acquire",
"wait",
),
wrong_output='"onethreetwo"',
entry_markers={
"python3": ("class foo", "def "),
"java": ("class foo",),
"cpp": ("class foo",),
},
supports_custom_input=False,
fixed_expected={
"[1,2,3]": '"onetwothree"',
"[1,3,2]": '"onetwothree"',
"[3,2,1]": '"onetwothree"',
},
),
Question(
number=2620,
slug="counter",
title="Counter",
difficulty=EASY,
category=JAVASCRIPT,
topics=("JavaScript",),
companies=(),
acceptance=79.5,
frequency=18,
contest_point=3,
summary=(
"Given an integer n, return a counter function. The counter returns "
"n on its first call and one more than the previous result on every "
"call after that."
),
details=(),
examples=(
Example(
"n = 10, calls = ['call','call','call']",
"[10,11,12]",
"The counter starts at 10 and increases by one each call.",
),
Example("n = -2, calls = ['call','call','call']", "[-2,-1,0]"),
),
constraints=("-1000 <= n <= 1000", "At most 1000 calls are made.",),
hints=("A closure keeps the current value between calls.",),
similar=(),
languages=("javascript",),
starter={
"javascript": (
"/**\n * @param {number} n\n * @return {Function} counter\n */\n"
"var createCounter = function(n) {\n \n};"
)
},
editorial_title="Approach: closure over a mutable counter",
editorial_body=(
"The returned function captures n by reference, so incrementing it "
"after returning gives the next caller the next value.",
),
editorial_code={
"javascript": (
"var createCounter = function(n) {\n"
" let current = n;\n"
" return function() {\n"
" return current++;\n"
" };\n"
"};"
)
},
community_solutions=(
{
"author": "closure_club",
"title": "Why let and not var in the returned closure",
"votes": "133",
"language": "JavaScript",
},
),
cases=("10\n[\"call\",\"call\",\"call\"]", "-2\n[\"call\",\"call\",\"call\"]"),
hidden_cases=("0\n[\"call\"]",),
technique_tokens=("++", "+ 1", "+1", "let ", "var ", "const "),
wrong_output="[0,0,0]",
supports_custom_input=False,
fixed_expected={
"10\n[\"call\",\"call\",\"call\"]": "[10,11,12]",
"-2\n[\"call\",\"call\",\"call\"]": "[-2,-1,0]",
"0\n[\"call\"]": "[0]",
},
),
Question(
number=2877,
slug="create-a-dataframe-from-list",
title="Create a DataFrame from List",
difficulty=EASY,
category=PANDAS,
topics=("Pandas",),
companies=(),
acceptance=83.2,
frequency=15,
contest_point=3,
summary=(
"Write a solution to create a DataFrame from a two-dimensional list "
"student_data. The DataFrame has the columns student_id and age, "
"in that order."
),
details=("Each inner list holds one student id followed by one age.",),
examples=(
Example(
"student_data = [[1,15],[2,11],[3,11],[4,20]]",
"student_id age\n1 15\n2 11\n3 11\n4 20",
),
),
constraints=(
"student_data has exactly two columns.",
"0 <= student_data.length <= 100",
),
hints=("The DataFrame constructor accepts data and columns together.",),
similar=(),
languages=("pandas",),
starter={
"pandas": (
"import pandas as pd\n\n\n"
"def createDataframe(student_data: List[List[int]])"
" -> pd.DataFrame:\n "
)
},
editorial_title="Approach: the DataFrame constructor",
editorial_body=(
"pd.DataFrame takes the nested list directly; pass the column names "
"so the order is fixed.",
),
editorial_code={
"pandas": (
"import pandas as pd\n\n\n"
"def createDataframe(student_data: List[List[int]])"
" -> pd.DataFrame:\n"
" return pd.DataFrame(student_data,"
" columns=['student_id', 'age'])"
)
},
community_solutions=(
{
"author": "frame_it",
"title": "Column order matters — pass columns explicitly",
"votes": "77",
"language": "Pandas",
},
),
cases=("[[1,15],[2,11],[3,11],[4,20]]",),
hidden_cases=("[]",),
technique_tokens=("dataframe",),
wrong_output="student_id age",
supports_custom_input=False,
fixed_expected={
"[[1,15],[2,11],[3,11],[4,20]]": (
"student_id age\n1 15\n2 11\n3 11\n4 20"
),
"[]": "Empty DataFrame",
},
),
)
# ---------------------------------------------------------------------------
# composition: index rows (evidence) + detail (local, except two-sum)
# ---------------------------------------------------------------------------
_TAG_DATA: dict[str, Any] = json.loads(
(DATA_DIR / "local_topic_tags.json").read_text(encoding="utf-8")
)
LOCAL_TOPIC_TAGS: dict[str, tuple[str, ...]] = {
slug: tuple(labels) for slug, labels in _TAG_DATA["tags"].items()
}
#: Every topic the 75 captured ``/tag/<slug>/`` instances named, with the
#: question count that page printed. The counts describe the *source* bank, not
#: this clone's 1,000-problem sample, so they are labelled as source figures
#: wherever they are shown.
SOURCE_TOPIC_VOCABULARY: tuple[dict[str, Any], ...] = tuple(
dict(row) for row in CATALOGUE["topics"]
)
TOPIC_SLUG_TO_LABEL: dict[str, str] = {
str(row["slug"]): str(row["label"]) for row in SOURCE_TOPIC_VOCABULARY
}
TOPIC_LABEL_TO_SLUG: dict[str, str] = {
str(row["label"]): str(row["slug"]) for row in SOURCE_TOPIC_VOCABULARY
}
_DETAIL_BY_SLUG: dict[str, Question] = {item.slug: item for item in _DETAILED}
def _deterministic_metrics(number: int, difficulty: str) -> tuple[int, int]:
"""Stable frequency/contest-point figures derived from the question number.
The source prints both behind a Premium lock, so nothing about them was
captured. They exist only to give the catalogue a stable secondary sort and
are never rendered as if they were source facts.
"""
weight = {EASY: 3, MEDIUM: 5, HARD: 7}.get(difficulty, 4)
frequency = (number * 37 + weight * 11) % 101
return min(frequency, 100), weight
PREMIUM_LOCKED_NOTICE = (
"Subscribe to unlock. This problem sits behind a LeetCode Premium "
"subscription, so the anonymous Playwright capture recorded the "
"subscription wall rather than the statement. This offline clone "
"reproduces the wall instead of inventing a problem."
)
NOT_CAPTURED_NOTICE = (
"This problem is part of the 1,000-problem sample and its catalogue row is "
"evidence, but the capture recorded no public statement for it."
)
def _compose() -> tuple[Question, ...]:
"""The catalogue: exactly the 1,000 sampled problems, in number order.
Each row starts from the captured catalogue entry, gains the captured
statement when the capture recorded one, and then merges the locally
authored judge fixture when this clone ships one for that slug. A fixture
whose slug is outside the 1,000-problem sample is not composed at all —
the sample is the scope.
"""
composed: list[Question] = []
for row in CATALOGUE["problems"]:
slug = str(row["slug"])
number = int(row["number"])
difficulty = str(row["difficulty"])
frequency, contest_point = _deterministic_metrics(number, difficulty)
fixture = _DETAIL_BY_SLUG.get(slug)
base = fixture if fixture is not None else Question(
number=number, slug=slug, title=str(row["title"]), difficulty=difficulty
)
captured = bool(row.get("description"))
summary = str(row.get("description") or "")
if row.get("access") == "premium-locked":
summary = ""
examples = tuple(
Example(
input=str(entry.get("input", "")),
output=str(entry.get("output", "")),
explanation=str(entry.get("explanation", "")),
)
for entry in row.get("examples", ())
)
similar = tuple(
SimilarQuestion(
slug=entry.get("slug"),
title=str(entry.get("title", "")),
difficulty=str(entry.get("difficulty", "")),
)
for entry in row.get("similar", ())
)
topics = tuple(row.get("topics") or ()) or LOCAL_TOPIC_TAGS.get(slug, base.topics)
composed.append(
replace(
base,
# The captured catalogue row is the authority for every listed
# field; the fixture only supplies what the capture could not.
number=number,
title=str(row["title"]),
difficulty=difficulty,
acceptance=float(row["acceptance"]),
category=str(row.get("category") or ALGORITHMS),
topics=topics,
frequency=frequency,
contest_point=contest_point,
access=str(row.get("access") or "public"),
summary=summary or ("" if row.get("access") != "public" else base.summary),
details=() if captured else base.details,
examples=examples or (() if captured else base.examples),
constraints=tuple(row.get("constraints") or ()) or (() if captured else base.constraints),
constraints_text=str(row.get("constraints_text") or ""),
follow_up=str(row.get("follow_up") or "") or ("" if captured else base.follow_up),
hints=tuple(row.get("hints") or ()) or (() if captured else base.hints),
similar=similar or (() if captured else base.similar),
accepted_display=str(row.get("accepted_display") or ""),
submissions_display=str(row.get("submissions_display") or ""),
discussion_display=str(row.get("discussion_display") or ""),
copy_from_evidence=captured,
evidence_notes=tuple(row.get("notes") or ()),
)
)
composed.sort(key=lambda item: item.number)
return tuple(composed)
QUESTIONS: tuple[Question, ...] = _compose()
BY_SLUG: dict[str, Question] = {question.slug: question for question in QUESTIONS}
#: Catalogue order: the daily question is pinned above the ascending list,
#: exactly as the captured page rendered it.
LISTING_ORDER: tuple[Question, ...] = (
(BY_SLUG[DAILY_SLUG],) if DAILY_SLUG in BY_SLUG else ()
) + tuple(item for item in QUESTIONS if item.slug != DAILY_SLUG)
ALL_TOPICS: tuple[str, ...] = tuple(
sorted({topic for question in QUESTIONS for topic in question.topics})
)
ALL_LANGUAGES: tuple[str, ...] = tuple(
sorted({language for question in QUESTIONS for language in question.languages})
)
WORKSPACE_SLUGS: tuple[str, ...] = tuple(
item.slug for item in QUESTIONS if item.workspace_ready
)
def question(slug: str) -> Question | None:
return BY_SLUG.get(slug)
def topic_for_slug(tag_slug: str) -> str | None:
"""Map a source ``/tag/<slug>`` path onto the topic label we filter on."""
label = TOPIC_SLUG_TO_LABEL.get(tag_slug)
return label if label in ALL_TOPICS else None
def normalize_language(item: Question, requested: str | None) -> str:
if requested and requested in item.languages:
return requested
return item.default_language
def neighbours(slug: str) -> dict[str, str]:
"""The previous/next question the workspace header steps through."""
order = [item.slug for item in LISTING_ORDER]
if slug not in order:
return {"previous": slug, "next": slug}
index = order.index(slug)
return {
"previous": order[index - 1] if index else order[-1],
"next": order[(index + 1) % len(order)],
}
def similar_questions(item: Question) -> list[dict[str, Any]]:
"""The Similar Questions rows, each flagged with whether it is local.
Rows the offline catalogue does not carry are rendered as plain text. The
clone never emits a link it cannot serve.
"""
rows: list[dict[str, Any]] = []
for entry in item.similar:
if isinstance(entry, SimilarQuestion):
slug, title, difficulty = entry.slug, entry.title, entry.difficulty
else:
target = BY_SLUG.get(str(entry))
if target is None:
continue
slug, title, difficulty = target.slug, target.title, target.difficulty
rows.append(
{
"slug": slug,
"title": title,
"difficulty": difficulty,
"available": bool(slug) and slug in BY_SLUG,
}
)
return rows
def social_notice(provider: str) -> str:
subject, verb = {
"google": ("Google", "is"),
"github": ("GitHub", "is"),
"apple": ("Apple", "is"),
"more": ("The other providers", "are"),
}.get(provider, (provider, "is"))
return (
f"{subject} {verb} not connected. Federated sign-in needs a third-party "
"identity provider, and this offline clone reaches no remote origin, "
"so use a local LeetCode account instead."
)
def detail_payload(item: Question) -> dict[str, Any]:
"""The presentation payload persisted alongside the catalogue row."""
return {
"summary": item.summary,
"details": list(item.details),
"examples": [
{
"input": example.input,
"output": example.output,
"explanation": example.explanation,
}
for example in item.examples
],
"constraints": list(item.constraints),
"hints": list(item.hints),
"follow_up": item.follow_up,
"similar": [row["slug"] for row in similar_questions(item)],
"languages": list(item.languages),
"starter": dict(item.starter),
"editorial_title": item.editorial_title,
"editorial_body": list(item.editorial_body),
"editorial_code": dict(item.editorial_code),
"community_solutions": [dict(row) for row in item.community_solutions],
"cases": list(item.cases),
"hidden_cases": list(item.hidden_cases),
"supports_custom_input": item.supports_custom_input,
}
def iter_questions() -> Iterable[Question]:
return QUESTIONS
def language_label(language: str) -> str:
return LANGUAGE_LABELS.get(language, language)
def difficulty_label(difficulty: str) -> str:
return DIFFICULTY_LABELS.get(difficulty, difficulty)
def category_label(category: str) -> str:
for slug, label in CATEGORIES:
if slug == category:
return label
return category
def sort_label(value: str) -> str:
for slug, label in SORT_OPTIONS:
if slug == value:
return label
return "Custom"
def normalize_languages(values: Sequence[str]) -> tuple[str, ...]:
return tuple(value for value in values if value in LANGUAGE_LABELS)
|