Spaces:
Running
Running
File size: 191,298 Bytes
8800c81 88c96ae 8800c81 88c96ae 8800c81 88c96ae 8800c81 | 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 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 | // Canonical 150 LeetCode / NeetCode DSA Review Dataset
// Pre-seeded with rich descriptions, examples, constraints, starter code, and reference solutions.
// Zero-cold-start, instant O(1) offline and guest-mode support.
export interface CatalogExample {
input: string;
output: string;
explanation?: string;
}
export interface CatalogProblem {
id: string;
problem_number: number;
name: string;
pattern: string;
difficulty: 'Easy' | 'Medium' | 'Hard';
time_complexity: string;
space_complexity: string;
starter_code: string;
description: string;
examples: CatalogExample[];
constraints: string[];
leetcode_url: string;
reference_solution?: string;
}
export const NEETCODE_150_DATA: CatalogProblem[] = [
{
"id": "nc-217",
"problem_number": 217,
"name": "Contains Duplicate",
"pattern": "Arrays & Hashing",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def containsDuplicate(self, nums: list[int]) -> bool:\n pass",
"description": "Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.",
"examples": [
{
"input": "nums = [1,2,3,1]",
"output": "true"
},
{
"input": "nums = [1,2,3,4]",
"output": "false"
}
],
"constraints": [
"1 <= nums.length <= 10^5",
"-10^9 <= nums[i] <= 10^9"
],
"leetcode_url": "https://leetcode.com/problems/contains-duplicate/",
"reference_solution": "class Solution:\n def containsDuplicate(self, nums: list[int]) -> bool:\n seen = set()\n for n in nums:\n if n in seen:\n return True\n seen.add(n)\n return False"
},
{
"id": "nc-242",
"problem_number": 242,
"name": "Valid Anagram",
"pattern": "Arrays & Hashing",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n pass",
"description": "Given two strings s and t, return true if t is an anagram of s, and false otherwise.",
"examples": [
{
"input": "s = \"anagram\", t = \"nagaram\"",
"output": "true"
},
{
"input": "s = \"rat\", t = \"car\"",
"output": "false"
}
],
"constraints": [
"1 <= s.length, t.length <= 5 * 10^4",
"s and t consist of lowercase English letters."
],
"leetcode_url": "https://leetcode.com/problems/valid-anagram/",
"reference_solution": "class Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n if len(s) != len(t):\n return False\n counts = {}\n for char in s:\n counts[char] = counts.get(char, 0) + 1\n for char in t:\n if char not in counts or counts[char] == 0:\n return False\n counts[char] -= 1\n return True"
},
{
"id": "nc-1",
"problem_number": 1,
"name": "Two Sum",
"pattern": "Arrays & Hashing",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def twoSum(self, nums: list[int], target: int) -> list[int]:\n pass",
"description": "Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.",
"examples": [
{
"input": "nums = [2,7,11,15], target = 9",
"output": "[0,1]"
}
],
"constraints": [
"2 <= nums.length <= 10^4",
"-10^9 <= nums[i] <= 10^9",
"Exactly one solution exists."
],
"leetcode_url": "https://leetcode.com/problems/two-sum/",
"reference_solution": "class Solution:\n def twoSum(self, nums: list[int], target: int) -> list[int]:\n prev = {}\n for i, n in enumerate(nums):\n diff = target - n\n if diff in prev:\n return [prev[diff], i]\n prev[n] = i\n return []"
},
{
"id": "nc-49",
"problem_number": 49,
"name": "Group Anagrams",
"pattern": "Arrays & Hashing",
"difficulty": "Medium",
"time_complexity": "O(M * N)",
"space_complexity": "O(M * N)",
"starter_code": "class Solution:\n def groupAnagrams(self, strs: list[str]) -> list[list[str]]:\n pass",
"description": "Given an array of strings strs, group the anagrams together. You can return the answer in any order.",
"examples": [
{
"input": "strs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]",
"output": "[[\"bat\"],[\"nat\",\"tan\"],[\"ate\",\"eat\",\"tea\"]]"
}
],
"constraints": [
"1 <= strs.length <= 10^4",
"0 <= strs[i].length <= 100"
],
"leetcode_url": "https://leetcode.com/problems/group-anagrams/",
"reference_solution": "from collections import defaultdict\n\nclass Solution:\n def groupAnagrams(self, strs: list[str]) -> list[list[str]]:\n res = defaultdict(list)\n for s in strs:\n count = [0] * 26\n for c in s:\n count[ord(c) - ord('a')] += 1\n res[tuple(count)].append(s)\n return list(res.values())"
},
{
"id": "nc-347",
"problem_number": 347,
"name": "Top K Frequent Elements",
"pattern": "Arrays & Hashing",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def topKFrequent(self, nums: list[int], k: int) -> list[int]:\n pass",
"description": "Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.",
"examples": [
{
"input": "nums = [1,1,1,2,2,3], k = 2",
"output": "[1,2]"
}
],
"constraints": [
"1 <= nums.length <= 10^5",
"1 <= k <= unique elements count"
],
"leetcode_url": "https://leetcode.com/problems/top-k-frequent-elements/",
"reference_solution": "class Solution:\n def topKFrequent(self, nums: list[int], k: int) -> list[int]:\n count = {}\n freq = [[] for _ in range(len(nums) + 1)]\n for n in nums:\n count[n] = 1 + count.get(n, 0)\n for n, c in count.items():\n freq[c].append(n)\n res = []\n for i in range(len(freq) - 1, 0, -1):\n for n in freq[i]:\n res.append(n)\n if len(res) == k:\n return res\n return res"
},
{
"id": "nc-271",
"problem_number": 271,
"name": "Encode and Decode Strings",
"pattern": "Arrays & Hashing",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Codec:\n def encode(self, strs: list[str]) -> str:\n pass\n def decode(self, s: str) -> list[str]:\n pass",
"description": "Design an algorithm to encode a list of strings to a single string and decode it back.",
"examples": [
{
"input": "dummy_input = [\"lint\",\"code\",\"love\",\"you\"]",
"output": "[\"lint\",\"code\",\"love\",\"you\"]"
}
],
"constraints": [
"1 <= strs.length <= 200"
],
"leetcode_url": "https://leetcode.com/problems/encode-and-decode-strings/",
"reference_solution": "class Codec:\n def encode(self, strs: list[str]) -> str:\n res = \"\"\n for s in strs:\n res += str(len(s)) + \"#\" + s\n return res\n\n def decode(self, s: str) -> list[str]:\n res, i = [], 0\n while i < len(s):\n j = i\n while s[j] != \"#\":\n j += 1\n length = int(s[i:j])\n res.append(s[j + 1 : j + 1 + length])\n i = j + 1 + length\n return res"
},
{
"id": "nc-238",
"problem_number": 238,
"name": "Product of Array Except Self",
"pattern": "Arrays & Hashing",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def productExceptSelf(self, nums: list[int]) -> list[int]:\n pass",
"description": "Given an integer array nums, return an array answer such that answer[i] is equal to the product of all elements except nums[i]. Without division in O(n).",
"examples": [
{
"input": "nums = [1,2,3,4]",
"output": "[24,12,8,6]"
}
],
"constraints": [
"2 <= nums.length <= 10^5",
"-30 <= nums[i] <= 30"
],
"leetcode_url": "https://leetcode.com/problems/product-of-array-except-self/",
"reference_solution": "class Solution:\n def productExceptSelf(self, nums: list[int]) -> list[int]:\n res = [1] * len(nums)\n prefix = 1\n for i in range(len(nums)):\n res[i] = prefix\n prefix *= nums[i]\n postfix = 1\n for i in range(len(nums) - 1, -1, -1):\n res[i] *= postfix\n postfix *= nums[i]\n return res"
},
{
"id": "nc-36",
"problem_number": 36,
"name": "Valid Sudoku",
"pattern": "Arrays & Hashing",
"difficulty": "Medium",
"time_complexity": "O(1)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def isValidSudoku(self, board: list[list[str]]) -> bool:\n pass",
"description": "Determine if a 9 x 9 Sudoku board is valid according to Sudoku rules.",
"examples": [
{
"input": "board = [[\"5\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"],[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",.\"],[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",.\"],[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"],[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"],[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"],[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",.\"],[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"],[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]",
"output": "true"
}
],
"constraints": [
"board is 9x9",
"digits 1-9 or '.'"
],
"leetcode_url": "https://leetcode.com/problems/valid-sudoku/",
"reference_solution": "from collections import defaultdict\n\nclass Solution:\n def isValidSudoku(self, board: list[list[str]]) -> bool:\n cols = defaultdict(set)\n rows = defaultdict(set)\n squares = defaultdict(set)\n for r in range(9):\n for c in range(9):\n if board[r][c] == \".\":\n continue\n val = board[r][c]\n if val in rows[r] or val in cols[c] or val in squares[(r // 3, c // 3)]:\n return False\n cols[c].add(val)\n rows[r].add(val)\n squares[(r // 3, c // 3)].add(val)\n return True"
},
{
"id": "nc-128",
"problem_number": 128,
"name": "Longest Consecutive Sequence",
"pattern": "Arrays & Hashing",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def longestConsecutive(self, nums: list[int]) -> int:\n pass",
"description": "Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence in O(n) time.",
"examples": [
{
"input": "nums = [100,4,200,1,3,2]",
"output": "4"
}
],
"constraints": [
"0 <= nums.length <= 10^5"
],
"leetcode_url": "https://leetcode.com/problems/longest-consecutive-sequence/",
"reference_solution": "class Solution:\n def longestConsecutive(self, nums: list[int]) -> int:\n numSet = set(nums)\n longest = 0\n for n in numSet:\n if (n - 1) not in numSet:\n length = 1\n while (n + length) in numSet:\n length += 1\n longest = max(longest, length)\n return longest"
},
{
"id": "nc-125",
"problem_number": 125,
"name": "Valid Palindrome",
"pattern": "Two Pointers",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def isPalindrome(self, s: str) -> bool:\n pass",
"description": "Check if a string is a palindrome considering only alphanumeric characters and ignoring cases.",
"examples": [
{
"input": "s = \"A man, a plan, a canal: Panama\"",
"output": "true"
}
],
"constraints": [
"1 <= s.length <= 2 * 10^5"
],
"leetcode_url": "https://leetcode.com/problems/valid-palindrome/",
"reference_solution": "class Solution:\n def isPalindrome(self, s: str) -> bool:\n l, r = 0, len(s) - 1\n while l < r:\n while l < r and not s[l].isalnum():\n l += 1\n while l < r and not s[r].isalnum():\n r -= 1\n if s[l].lower() != s[r].lower():\n return False\n l += 1\n r -= 1\n return True"
},
{
"id": "nc-167",
"problem_number": 167,
"name": "Two Sum II - Input Array Is Sorted",
"pattern": "Two Pointers",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def twoSum(self, numbers: list[int], target: int) -> list[int]:\n pass",
"description": "Given a 1-indexed sorted array numbers, find two numbers that add up to target.",
"examples": [
{
"input": "numbers = [2,7,11,15], target = 9",
"output": "[1,2]"
}
],
"constraints": [
"2 <= numbers.length <= 3 * 10^4"
],
"leetcode_url": "https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/",
"reference_solution": "class Solution:\n def twoSum(self, numbers: list[int], target: int) -> list[int]:\n l, r = 0, len(numbers) - 1\n while l < r:\n cur = numbers[l] + numbers[r]\n if cur > target:\n r -= 1\n elif cur < target:\n l += 1\n else:\n return [l + 1, r + 1]\n return []"
},
{
"id": "nc-15",
"problem_number": 15,
"name": "3Sum",
"pattern": "Two Pointers",
"difficulty": "Medium",
"time_complexity": "O(N^2)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def threeSum(self, nums: list[int]) -> list[list[int]]:\n pass",
"description": "Find all unique triplets in nums that sum to 0.",
"examples": [
{
"input": "nums = [-1,0,1,2,-1,-4]",
"output": "[[-1,-1,2],[-1,0,1]]"
}
],
"constraints": [
"3 <= nums.length <= 3000"
],
"leetcode_url": "https://leetcode.com/problems/3sum/",
"reference_solution": "class Solution:\n def threeSum(self, nums: list[int]) -> list[list[int]]:\n res = []\n nums.sort()\n for i, a in enumerate(nums):\n if a > 0:\n break\n if i > 0 and a == nums[i - 1]:\n continue\n l, r = i + 1, len(nums) - 1\n while l < r:\n threeSum = a + nums[l] + nums[r]\n if threeSum > 0:\n r -= 1\n elif threeSum < 0:\n l += 1\n else:\n res.append([a, nums[l], nums[r]])\n l += 1\n r -= 1\n while nums[l] == nums[l - 1] and l < r:\n l += 1\n return res"
},
{
"id": "nc-11",
"problem_number": 11,
"name": "Container With Most Water",
"pattern": "Two Pointers",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def maxArea(self, height: list[int]) -> int:\n pass",
"description": "Find two lines that together with the x-axis form a container storing the most water.",
"examples": [
{
"input": "height = [1,8,6,2,5,4,8,3,7]",
"output": "49"
}
],
"constraints": [
"2 <= height.length <= 10^5"
],
"leetcode_url": "https://leetcode.com/problems/container-with-most-water/",
"reference_solution": "class Solution:\n def maxArea(self, height: list[int]) -> int:\n l, r = 0, len(height) - 1\n res = 0\n while l < r:\n res = max(res, min(height[l], height[r]) * (r - l))\n if height[l] <= height[r]:\n l += 1\n else:\n r -= 1\n return res"
},
{
"id": "nc-42",
"problem_number": 42,
"name": "Trapping Rain Water",
"pattern": "Two Pointers",
"difficulty": "Hard",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def trap(self, height: list[int]) -> int:\n pass",
"description": "Compute how much water an elevation map can trap after raining.",
"examples": [
{
"input": "height = [0,1,0,2,1,0,1,3,2,1,2,1]",
"output": "6"
}
],
"constraints": [
"1 <= height.length <= 2 * 10^4"
],
"leetcode_url": "https://leetcode.com/problems/trapping-rain-water/",
"reference_solution": "class Solution:\n def trap(self, height: list[int]) -> int:\n if not height:\n return 0\n l, r = 0, len(height) - 1\n leftMax, rightMax = height[l], height[r]\n res = 0\n while l < r:\n if leftMax < rightMax:\n l += 1\n leftMax = max(leftMax, height[l])\n res += leftMax - height[l]\n else:\n r -= 1\n rightMax = max(rightMax, height[r])\n res += rightMax - height[r]\n return res"
},
{
"id": "nc-121",
"problem_number": 121,
"name": "Best Time to Buy and Sell Stock",
"pattern": "Sliding Window",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def maxProfit(self, prices: list[int]) -> int:\n pass",
"description": "Maximize profit by choosing a single day to buy one stock and choosing a different day in the future to sell it.",
"examples": [
{
"input": "prices = [7,1,5,3,6,4]",
"output": "5"
}
],
"constraints": [
"1 <= prices.length <= 10^5"
],
"leetcode_url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock/",
"reference_solution": "class Solution:\n def maxProfit(self, prices: list[int]) -> int:\n l, r = 0, 1\n maxP = 0\n while r < len(prices):\n if prices[l] < prices[r]:\n maxP = max(maxP, prices[r] - prices[l])\n else:\n l = r\n r += 1\n return maxP"
},
{
"id": "nc-3",
"problem_number": 3,
"name": "Longest Substring Without Repeating Characters",
"pattern": "Sliding Window",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n pass",
"description": "Find the length of the longest substring without duplicate characters.",
"examples": [
{
"input": "s = \"abcabcbb\"",
"output": "3"
}
],
"constraints": [
"0 <= s.length <= 5 * 10^4"
],
"leetcode_url": "https://leetcode.com/problems/longest-substring-without-repeating-characters/",
"reference_solution": "class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n charSet = set()\n l, res = 0, 0\n for r in range(len(s)):\n while s[r] in charSet:\n charSet.remove(s[l])\n l += 1\n charSet.add(s[r])\n res = max(res, r - l + 1)\n return res"
},
{
"id": "nc-424",
"problem_number": 424,
"name": "Longest Repeating Character Replacement",
"pattern": "Sliding Window",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def characterReplacement(self, s: str, k: int) -> int:\n pass",
"description": "Choose at most k characters and replace them with any other uppercase character to get the longest substring containing the same letter.",
"examples": [
{
"input": "s = \"ABAB\", k = 2",
"output": "4"
}
],
"constraints": [
"1 <= s.length <= 10^5",
"0 <= k <= s.length"
],
"leetcode_url": "https://leetcode.com/problems/longest-repeating-character-replacement/",
"reference_solution": "class Solution:\n def characterReplacement(self, s: str, k: int) -> int:\n count = {}\n res = l = maxf = 0\n for r in range(len(s)):\n count[s[r]] = 1 + count.get(s[r], 0)\n maxf = max(maxf, count[s[r]])\n while (r - l + 1) - maxf > k:\n count[s[l]] -= 1\n l += 1\n res = max(res, r - l + 1)\n return res"
},
{
"id": "nc-567",
"problem_number": 567,
"name": "Permutation in String",
"pattern": "Sliding Window",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def checkInclusion(self, s1: str, s2: str) -> bool:\n pass",
"description": "Return true if s2 contains a permutation of s1, or false otherwise.",
"examples": [
{
"input": "s1 = \"ab\", s2 = \"eidbaooo\"",
"output": "true"
}
],
"constraints": [
"1 <= s1.length, s2.length <= 10^4"
],
"leetcode_url": "https://leetcode.com/problems/permutation-in-string/",
"reference_solution": "class Solution:\n def checkInclusion(self, s1: str, s2: str) -> bool:\n if len(s1) > len(s2):\n return False\n s1C, s2C = [0] * 26, [0] * 26\n for i in range(len(s1)):\n s1C[ord(s1[i]) - ord('a')] += 1\n s2C[ord(s2[i]) - ord('a')] += 1\n matches = sum(1 for i in range(26) if s1C[i] == s2C[i])\n l = 0\n for r in range(len(s1), len(s2)):\n if matches == 26:\n return True\n idx = ord(s2[r]) - ord('a')\n s2C[idx] += 1\n if s1C[idx] == s2C[idx]: matches += 1\n elif s1C[idx] + 1 == s2C[idx]: matches -= 1\n idx = ord(s2[l]) - ord('a')\n s2C[idx] -= 1\n if s1C[idx] == s2C[idx]: matches += 1\n elif s1C[idx] - 1 == s2C[idx]: matches -= 1\n l += 1\n return matches == 26"
},
{
"id": "nc-76",
"problem_number": 76,
"name": "Minimum Window Substring",
"pattern": "Sliding Window",
"difficulty": "Hard",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def minWindow(self, s: str, t: str) -> str:\n pass",
"description": "Given two strings s and t, return the minimum window substring of s such that every character in t is included in the window.",
"examples": [
{
"input": "s = \"ADOBECODEBANC\", t = \"ABC\"",
"output": "\"BANC\""
}
],
"constraints": [
"1 <= s.length, t.length <= 10^5"
],
"leetcode_url": "https://leetcode.com/problems/minimum-window-substring/",
"reference_solution": "class Solution:\n def minWindow(self, s: str, t: str) -> str:\n if not t: return \"\"\n countT, window = {}, {}\n for c in t: countT[c] = 1 + countT.get(c, 0)\n have, need = 0, len(countT)\n res, resLen = [-1, -1], float('inf')\n l = 0\n for r in range(len(s)):\n c = s[r]\n window[c] = 1 + window.get(c, 0)\n if c in countT and window[c] == countT[c]: have += 1\n while have == need:\n if (r - l + 1) < resLen:\n res = [l, r]\n resLen = r - l + 1\n window[s[l]] -= 1\n if s[l] in countT and window[s[l]] < countT[s[l]]: have -= 1\n l += 1\n l, r = res\n return s[l:r+1] if resLen != float('inf') else \"\""
},
{
"id": "nc-239",
"problem_number": 239,
"name": "Sliding Window Maximum",
"pattern": "Sliding Window",
"difficulty": "Hard",
"time_complexity": "O(N)",
"space_complexity": "O(K)",
"starter_code": "class Solution:\n def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:\n pass",
"description": "Return the max sliding window of size k moving from very left of array to very right.",
"examples": [
{
"input": "nums = [1,3,-1,-3,5,3,6,7], k = 3",
"output": "[3,3,5,5,6,7]"
}
],
"constraints": [
"1 <= nums.length <= 10^5",
"1 <= k <= nums.length"
],
"leetcode_url": "https://leetcode.com/problems/sliding-window-maximum/",
"reference_solution": "from collections import deque\n\nclass Solution:\n def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:\n output = []\n q = deque()\n l = r = 0\n while r < len(nums):\n while q and nums[q[-1]] < nums[r]:\n q.pop()\n q.append(r)\n if l > q[0]:\n q.popleft()\n if (r + 1) >= k:\n output.append(nums[q[0]])\n l += 1\n r += 1\n return output"
},
{
"id": "nc-20",
"problem_number": 20,
"name": "Valid Parentheses",
"pattern": "Stack",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def isValid(self, s: str) -> bool:\n pass",
"description": "Determine if the input string has valid matching brackets '()', '{}', '[]'.",
"examples": [
{
"input": "s = \"()[]{}\"",
"output": "true"
},
{
"input": "s = \"(]\"",
"output": "false"
}
],
"constraints": [
"1 <= s.length <= 10^4"
],
"leetcode_url": "https://leetcode.com/problems/valid-parentheses/",
"reference_solution": "class Solution:\n def isValid(self, s: str) -> bool:\n Map = {\")\": \"(\", \"]\": \"[\", \"}\": \"{\"}\n stack = []\n for c in s:\n if c not in Map:\n stack.append(c)\n continue\n if not stack or stack[-1] != Map[c]:\n return False\n stack.pop()\n return not stack"
},
{
"id": "nc-155",
"problem_number": 155,
"name": "Min Stack",
"pattern": "Stack",
"difficulty": "Medium",
"time_complexity": "O(1)",
"space_complexity": "O(N)",
"starter_code": "class MinStack:\n def __init__(self):\n pass\n def push(self, val: int) -> None:\n pass\n def pop(self) -> None:\n pass\n def top(self) -> int:\n pass\n def getMin(self) -> int:\n pass",
"description": "Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.",
"examples": [
{
"input": "[\"MinStack\",\"push\",\"push\",\"push\",\"getMin\",\"pop\",\"top\",\"getMin\"]",
"output": "[null,null,null,null,-3,null,0,-2]"
}
],
"constraints": [
"Methods push, pop, top and getMin are called."
],
"leetcode_url": "https://leetcode.com/problems/min-stack/",
"reference_solution": "class MinStack:\n def __init__(self):\n self.stack = []\n self.minStack = []\n def push(self, val: int) -> None:\n self.stack.append(val)\n val = min(val, self.minStack[-1] if self.minStack else val)\n self.minStack.append(val)\n def pop(self) -> None:\n self.stack.pop()\n self.minStack.pop()\n def top(self) -> int:\n return self.stack[-1]\n def getMin(self) -> int:\n return self.minStack[-1]"
},
{
"id": "nc-150",
"problem_number": 150,
"name": "Evaluate Reverse Polish Notation",
"pattern": "Stack",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def evalRPN(self, tokens: list[str]) -> int:\n pass",
"description": "Evaluate the value of an arithmetic expression in Reverse Polish Notation.",
"examples": [
{
"input": "tokens = [\"2\",\"1\",\"+\",\"3\",\"*\"]",
"output": "9"
}
],
"constraints": [
"1 <= tokens.length <= 10^4"
],
"leetcode_url": "https://leetcode.com/problems/evaluate-reverse-polish-notation/",
"reference_solution": "class Solution:\n def evalRPN(self, tokens: list[str]) -> int:\n stack = []\n for c in tokens:\n if c == \"+\":\n stack.append(stack.pop() + stack.pop())\n elif c == \"-\":\n a, b = stack.pop(), stack.pop()\n stack.append(b - a)\n elif c == \"*\":\n stack.append(stack.pop() * stack.pop())\n elif c == \"/\":\n a, b = stack.pop(), stack.pop()\n stack.append(int(float(b) / a))\n else:\n stack.append(int(c))\n return stack[0]"
},
{
"id": "nc-739",
"problem_number": 739,
"name": "Daily Temperatures",
"pattern": "Stack",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def dailyTemperatures(self, temperatures: list[int]) -> list[int]:\n pass",
"description": "Given daily temperatures, return an array answer where answer[i] is the days you have to wait after ith day to get warmer temperature.",
"examples": [
{
"input": "temperatures = [73,74,75,71,69,72,76,73]",
"output": "[1,1,4,2,1,1,0,0]"
}
],
"constraints": [
"1 <= temperatures.length <= 10^5"
],
"leetcode_url": "https://leetcode.com/problems/daily-temperatures/",
"reference_solution": "class Solution:\n def dailyTemperatures(self, temperatures: list[int]) -> list[int]:\n res = [0] * len(temperatures)\n stack = []\n for i, t in enumerate(temperatures):\n while stack and t > stack[-1][0]:\n stackT, stackInd = stack.pop()\n res[stackInd] = i - stackInd\n stack.append((t, i))\n return res"
},
{
"id": "nc-853",
"problem_number": 853,
"name": "Car Fleet",
"pattern": "Stack",
"difficulty": "Medium",
"time_complexity": "O(N log N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def carFleet(self, target: int, position: list[int], speed: list[int]) -> int:\n pass",
"description": "Calculate how many car fleets will arrive at destination target position.",
"examples": [
{
"input": "target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]",
"output": "3"
}
],
"constraints": [
"n == position.length == speed.length"
],
"leetcode_url": "https://leetcode.com/problems/car-fleet/",
"reference_solution": "class Solution:\n def carFleet(self, target: int, position: list[int], speed: list[int]) -> int:\n pair = [(p, s) for p, s in zip(position, speed)]\n pair.sort(reverse=True)\n stack = []\n for p, s in pair:\n stack.append((target - p) / s)\n if len(stack) >= 2 and stack[-1] <= stack[-2]:\n stack.pop()\n return len(stack)"
},
{
"id": "nc-84",
"problem_number": 84,
"name": "Largest Rectangle in Histogram",
"pattern": "Stack",
"difficulty": "Hard",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def largestRectangleArea(self, heights: list[int]) -> int:\n pass",
"description": "Given an array of integers heights representing bar heights, return area of the largest rectangle in histogram.",
"examples": [
{
"input": "heights = [2,1,5,6,2,3]",
"output": "10"
}
],
"constraints": [
"1 <= heights.length <= 10^5"
],
"leetcode_url": "https://leetcode.com/problems/largest-rectangle-in-histogram/",
"reference_solution": "class Solution:\n def largestRectangleArea(self, heights: list[int]) -> int:\n maxArea = 0\n stack = []\n for i, h in enumerate(heights):\n start = i\n while stack and stack[-1][1] > h:\n index, height = stack.pop()\n maxArea = max(maxArea, height * (i - index))\n start = index\n stack.append((start, h))\n for i, h in stack:\n maxArea = max(maxArea, h * (len(heights) - i))\n return maxArea"
},
{
"id": "nc-704",
"problem_number": 704,
"name": "Binary Search",
"pattern": "Binary Search",
"difficulty": "Easy",
"time_complexity": "O(log N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def search(self, nums: list[int], target: int) -> int:\n pass",
"description": "Given an array of integers nums which is sorted in ascending order, search target in nums in O(log n) runtime.",
"examples": [
{
"input": "nums = [-1,0,3,5,9,12], target = 9",
"output": "4"
}
],
"constraints": [
"1 <= nums.length <= 10^4"
],
"leetcode_url": "https://leetcode.com/problems/binary-search/",
"reference_solution": "class Solution:\n def search(self, nums: list[int], target: int) -> int:\n l, r = 0, len(nums) - 1\n while l <= r:\n m = l + ((r - l) // 2)\n if nums[m] > target:\n r = m - 1\n elif nums[m] < target:\n l = m + 1\n else:\n return m\n return -1"
},
{
"id": "nc-74",
"problem_number": 74,
"name": "Search a 2D Matrix",
"pattern": "Binary Search",
"difficulty": "Medium",
"time_complexity": "O(log(M * N))",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:\n pass",
"description": "Write an efficient algorithm that searches for a value target in an m x n integer matrix with sorted rows.",
"examples": [
{
"input": "matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3",
"output": "true"
}
],
"constraints": [
"m == matrix.length",
"n == matrix[i].length"
],
"leetcode_url": "https://leetcode.com/problems/search-a-2d-matrix/",
"reference_solution": "class Solution:\n def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:\n ROWS, COLS = len(matrix), len(matrix[0])\n top, bot = 0, ROWS - 1\n while top <= bot:\n row = (top + bot) // 2\n if target > matrix[row][-1]:\n top = row + 1\n elif target < matrix[row][0]:\n bot = row - 1\n else:\n break\n if not (top <= bot):\n return False\n row = (top + bot) // 2\n l, r = 0, COLS - 1\n while l <= r:\n m = (l + r) // 2\n if target > matrix[row][m]:\n l = m + 1\n elif target < matrix[row][m]:\n r = m - 1\n else:\n return True\n return False"
},
{
"id": "nc-875",
"problem_number": 875,
"name": "Koko Eating Bananas",
"pattern": "Binary Search",
"difficulty": "Medium",
"time_complexity": "O(N log(max(P)))",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def minEatingSpeed(self, piles: list[int], h: int) -> int:\n pass",
"description": "Return the minimum integer k such that Koko can eat all bananas within h hours.",
"examples": [
{
"input": "piles = [3,6,7,11], h = 8",
"output": "4"
}
],
"constraints": [
"1 <= piles.length <= 10^4",
"piles.length <= h <= 10^9"
],
"leetcode_url": "https://leetcode.com/problems/koko-eating-bananas/",
"reference_solution": "import math\n\nclass Solution:\n def minEatingSpeed(self, piles: list[int], h: int) -> int:\n l, r = 1, max(piles)\n res = r\n while l <= r:\n k = (l + r) // 2\n totalTime = sum(math.ceil(p / k) for p in piles)\n if totalTime <= h:\n res = k\n r = k - 1\n else:\n l = k + 1\n return res"
},
{
"id": "nc-153",
"problem_number": 153,
"name": "Find Minimum in Rotated Sorted Array",
"pattern": "Binary Search",
"difficulty": "Medium",
"time_complexity": "O(log N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def findMin(self, nums: list[int]) -> int:\n pass",
"description": "Given the sorted rotated array nums of unique elements, return the minimum element in O(log n).",
"examples": [
{
"input": "nums = [3,4,5,1,2]",
"output": "1"
}
],
"constraints": [
"n == nums.length",
"1 <= n <= 5000"
],
"leetcode_url": "https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/",
"reference_solution": "class Solution:\n def findMin(self, nums: list[int]) -> int:\n res = nums[0]\n l, r = 0, len(nums) - 1\n while l <= r:\n if nums[l] < nums[r]:\n res = min(res, nums[l])\n break\n m = (l + r) // 2\n res = min(res, nums[m])\n if nums[m] >= nums[l]:\n l = m + 1\n else:\n r = m - 1\n return res"
},
{
"id": "nc-33",
"problem_number": 33,
"name": "Search in Rotated Sorted Array",
"pattern": "Binary Search",
"difficulty": "Medium",
"time_complexity": "O(log N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def search(self, nums: list[int], target: int) -> int:\n pass",
"description": "Given rotated sorted array nums with unique values and target, return index of target or -1 in O(log n).",
"examples": [
{
"input": "nums = [4,5,6,7,0,1,2], target = 0",
"output": "4"
}
],
"constraints": [
"1 <= nums.length <= 5000"
],
"leetcode_url": "https://leetcode.com/problems/search-in-rotated-sorted-array/",
"reference_solution": "class Solution:\n def search(self, nums: list[int], target: int) -> int:\n l, r = 0, len(nums) - 1\n while l <= r:\n mid = (l + r) // 2\n if target == nums[mid]: return mid\n if nums[l] <= nums[mid]:\n if target > nums[mid] or target < nums[l]: l = mid + 1\n else: r = mid - 1\n else:\n if target < nums[mid] or target > nums[r]: r = mid - 1\n else: l = mid + 1\n return -1"
},
{
"id": "nc-981",
"problem_number": 981,
"name": "Time Based Key-Value Store",
"pattern": "Binary Search",
"difficulty": "Medium",
"time_complexity": "O(log N)",
"space_complexity": "O(N)",
"starter_code": "class TimeMap:\n def __init__(self):\n pass\n def set(self, key: str, value: str, timestamp: int) -> None:\n pass\n def get(self, key: str, timestamp: int) -> str:\n pass",
"description": "Design a time-based key-value data structure that can store multiple values for the same key at different time stamps.",
"examples": [
{
"input": "[\"TimeMap\",\"set\",\"get\",\"get\",\"set\",\"get\",\"get\"]",
"output": "[null,null,\"bar\",\"bar\",null,\"bar2\",\"bar2\"]"
}
],
"constraints": [
"1 <= key.length, value.length <= 100"
],
"leetcode_url": "https://leetcode.com/problems/time-based-key-value-store/",
"reference_solution": "class TimeMap:\n def __init__(self):\n self.keyStore = {}\n def set(self, key: str, value: str, timestamp: int) -> None:\n if key not in self.keyStore: self.keyStore[key] = []\n self.keyStore[key].append([value, timestamp])\n def get(self, key: str, timestamp: int) -> str:\n res, values = \"\", self.keyStore.get(key, [])\n l, r = 0, len(values) - 1\n while l <= r:\n m = (l + r) // 2\n if values[m][1] <= timestamp:\n res = values[m][0]\n l = m + 1\n else:\n r = m - 1\n return res"
},
{
"id": "nc-4",
"problem_number": 4,
"name": "Median of Two Sorted Arrays",
"pattern": "Binary Search",
"difficulty": "Hard",
"time_complexity": "O(log(min(N, M)))",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def findMedianSortedArrays(self, nums1: list[int], nums2: list[int]) -> float:\n pass",
"description": "Given two sorted arrays nums1 and nums2, return median of two sorted arrays in O(log (m+n)).",
"examples": [
{
"input": "nums1 = [1,3], nums2 = [2]",
"output": "2.00000"
}
],
"constraints": [
"nums1.length == m",
"nums2.length == n"
],
"leetcode_url": "https://leetcode.com/problems/median-of-two-sorted-arrays/",
"reference_solution": "class Solution:\n def findMedianSortedArrays(self, nums1: list[int], nums2: list[int]) -> float:\n A, B = nums1, nums2\n total = len(nums1) + len(nums2)\n half = total // 2\n if len(B) < len(A): A, B = B, A\n l, r = 0, len(A) - 1\n while True:\n i = (l + r) // 2\n j = half - i - 2\n Aleft = A[i] if i >= 0 else float(\"-infinity\")\n Aright = A[i + 1] if (i + 1) < len(A) else float(\"infinity\")\n Bleft = B[j] if j >= 0 else float(\"-infinity\")\n Bright = B[j + 1] if (j + 1) < len(B) else float(\"infinity\")\n if Aleft <= Bright and Bleft <= Aright:\n if total % 2:\n return min(Aright, Bright)\n return (max(Aleft, Bleft) + min(Aright, Bright)) / 2\n elif Aleft > Bright:\n r = i - 1\n else:\n l = i + 1"
},
{
"id": "nc-206",
"problem_number": 206,
"name": "Reverse Linked List",
"pattern": "Linked List",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n pass",
"description": "Given the head of a singly linked list, reverse the list, and return the reversed list.",
"examples": [
{
"input": "head = [1,2,3,4,5]",
"output": "[5,4,3,2,1]"
}
],
"constraints": [
"The number of nodes in the list is in range [0, 5000]."
],
"leetcode_url": "https://leetcode.com/problems/reverse-linked-list/",
"reference_solution": "class Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n prev, curr = None, head\n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n return prev"
},
{
"id": "nc-21",
"problem_number": 21,
"name": "Merge Two Sorted Lists",
"pattern": "Linked List",
"difficulty": "Easy",
"time_complexity": "O(N + M)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n pass",
"description": "Merge two sorted linked lists into one sorted list.",
"examples": [
{
"input": "list1 = [1,2,4], list2 = [1,3,4]",
"output": "[1,1,2,3,4,4]"
}
],
"constraints": [
"Number of nodes in both lists is in range [0, 50]."
],
"leetcode_url": "https://leetcode.com/problems/merge-two-sorted-lists/",
"reference_solution": "class Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n dummy = node = ListNode()\n while list1 and list2:\n if list1.val < list2.val:\n node.next = list1\n list1 = list1.next\n else:\n node.next = list2\n list2 = list2.next\n node = node.next\n node.next = list1 or list2\n return dummy.next"
},
{
"id": "nc-141",
"problem_number": 141,
"name": "Linked List Cycle",
"pattern": "Linked List",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def hasCycle(self, head: Optional[ListNode]) -> bool:\n pass",
"description": "Given head, return true if there is a cycle in the linked list.",
"examples": [
{
"input": "head = [3,2,0,-4], pos = 1",
"output": "true"
}
],
"constraints": [
"The number of the nodes in the list is in range [0, 10^4]."
],
"leetcode_url": "https://leetcode.com/problems/linked-list-cycle/",
"reference_solution": "class Solution:\n def hasCycle(self, head: Optional[ListNode]) -> bool:\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n return True\n return False"
},
{
"id": "nc-143",
"problem_number": 143,
"name": "Reorder List",
"pattern": "Linked List",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n pass",
"description": "Reorder the list to be on the following form: L0 \u2192 Ln \u2192 L1 \u2192 Ln - 1 \u2192 L2 \u2192 Ln - 2 \u2192 \u2026",
"examples": [
{
"input": "head = [1,2,3,4]",
"output": "[1,4,2,3]"
}
],
"constraints": [
"Number of nodes in list is in range [1, 5 * 10^4]."
],
"leetcode_url": "https://leetcode.com/problems/reorder-list/",
"reference_solution": "class Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n slow, fast = head, head.next\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n second = slow.next\n prev = slow.next = None\n while second:\n tmp = second.next\n second.next = prev\n prev = second\n second = tmp\n first, second = head, prev\n while second:\n tmp1, tmp2 = first.next, second.next\n first.next = second\n second.next = tmp1\n first, second = tmp1, tmp2"
},
{
"id": "nc-19",
"problem_number": 19,
"name": "Remove Nth Node From End of List",
"pattern": "Linked List",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n pass",
"description": "Remove the nth node from the end of the list and return its head.",
"examples": [
{
"input": "head = [1,2,3,4,5], n = 2",
"output": "[1,2,3,5]"
}
],
"constraints": [
"1 <= sz <= 30",
"1 <= n <= sz"
],
"leetcode_url": "https://leetcode.com/problems/remove-nth-node-from-end-of-list/",
"reference_solution": "class Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n dummy = ListNode(0, head)\n left = dummy\n right = head\n while n > 0 and right:\n right = right.next\n n -= 1\n while right:\n left = left.next\n right = right.next\n left.next = left.next.next\n return dummy.next"
},
{
"id": "nc-138",
"problem_number": 138,
"name": "Copy List with Random Pointer",
"pattern": "Linked List",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':\n pass",
"description": "Construct a deep copy of a linked list where each node has next and random pointers.",
"examples": [
{
"input": "head = [[7,null],[13,0],[11,4],[10,2],[1,0]]",
"output": "[[7,null],[13,0],[11,4],[10,2],[1,0]]"
}
],
"constraints": [
"0 <= n <= 1000"
],
"leetcode_url": "https://leetcode.com/problems/copy-list-with-random-pointer/",
"reference_solution": "class Solution:\n def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':\n oldToCopy = {None: None}\n cur = head\n while cur:\n oldToCopy[cur] = Node(cur.val)\n cur = cur.next\n cur = head\n while cur:\n copy = oldToCopy[cur]\n copy.next = oldToCopy[cur.next]\n copy.random = oldToCopy[cur.random]\n cur = cur.next\n return oldToCopy[head]"
},
{
"id": "nc-2",
"problem_number": 2,
"name": "Add Two Numbers",
"pattern": "Linked List",
"difficulty": "Medium",
"time_complexity": "O(max(N, M))",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n pass",
"description": "Add two non-empty linked lists representing two non-negative integers stored in reverse order.",
"examples": [
{
"input": "l1 = [2,4,3], l2 = [5,6,4]",
"output": "[7,0,8]"
}
],
"constraints": [
"Number of nodes in range [1, 100]."
],
"leetcode_url": "https://leetcode.com/problems/add-two-numbers/",
"reference_solution": "class Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n dummy = ListNode()\n cur = dummy\n carry = 0\n while l1 or l2 or carry:\n v1 = l1.val if l1 else 0\n v2 = l2.val if l2 else 0\n val = v1 + v2 + carry\n carry = val // 10\n val = val % 10\n cur.next = ListNode(val)\n cur = cur.next\n l1 = l1.next if l1 else None\n l2 = l2.next if l2 else None\n return dummy.next"
},
{
"id": "nc-287",
"problem_number": 287,
"name": "Find the Duplicate Number",
"pattern": "Linked List",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def findDuplicate(self, nums: list[int]) -> int:\n pass",
"description": "Find the duplicate number in nums without modifying the array and using only O(1) extra space.",
"examples": [
{
"input": "nums = [1,3,4,2,2]",
"output": "2"
}
],
"constraints": [
"1 <= n <= 10^5",
"nums.length == n + 1"
],
"leetcode_url": "https://leetcode.com/problems/find-the-duplicate-number/",
"reference_solution": "class Solution:\n def findDuplicate(self, nums: list[int]) -> int:\n slow = fast = 0\n while True:\n slow = nums[slow]\n fast = nums[nums[fast]]\n if slow == fast:\n break\n slow2 = 0\n while True:\n slow = nums[slow]\n slow2 = nums[slow2]\n if slow == slow2:\n return slow"
},
{
"id": "nc-146",
"problem_number": 146,
"name": "LRU Cache",
"pattern": "Linked List",
"difficulty": "Medium",
"time_complexity": "O(1)",
"space_complexity": "O(capacity)",
"starter_code": "class LRUCache:\n def __init__(self, capacity: int):\n pass\n def get(self, key: int) -> int:\n pass\n def put(self, key: int, value: int) -> None:\n pass",
"description": "Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.",
"examples": [
{
"input": "[\"LRUCache\",\"put\",\"put\",\"get\",\"put\",\"get\",\"put\",\"get\",\"get\",\"get\"]",
"output": "[null,null,null,1,null,-1,null,-1,3,4]"
}
],
"constraints": [
"1 <= capacity <= 3000"
],
"leetcode_url": "https://leetcode.com/problems/lru-cache/",
"reference_solution": "class Node:\n def __init__(self, k, v):\n self.key, self.val = k, v\n self.prev = self.next = None\n\nclass LRUCache:\n def __init__(self, capacity: int):\n self.cap = capacity\n self.cache = {}\n self.left, self.right = Node(0, 0), Node(0, 0)\n self.left.next, self.right.prev = self.right, self.left\n def remove(self, node):\n prev, nxt = node.prev, node.next\n prev.next, nxt.prev = nxt, prev\n def insert(self, node):\n prev, nxt = self.right.prev, self.right\n prev.next = nxt.prev = node\n node.next, node.prev = nxt, prev\n def get(self, key: int) -> int:\n if key in self.cache:\n self.remove(self.cache[key])\n self.insert(self.cache[key])\n return self.cache[key].val\n return -1\n def put(self, key: int, value: int) -> None:\n if key in self.cache:\n self.remove(self.cache[key])\n self.cache[key] = Node(key, value)\n self.insert(self.cache[key])\n if len(self.cache) > self.cap:\n lru = self.left.next\n self.remove(lru)\n del self.cache[lru.key]"
},
{
"id": "nc-23",
"problem_number": 23,
"name": "Merge k Sorted Lists",
"pattern": "Linked List",
"difficulty": "Hard",
"time_complexity": "O(N log K)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def mergeKLists(self, lists: list[Optional[ListNode]]) -> Optional[ListNode]:\n pass",
"description": "Merge all the linked-lists into one sorted linked-list and return it.",
"examples": [
{
"input": "lists = [[1,4,5],[1,3,4],[2,6]]",
"output": "[1,1,2,3,4,4,5,6]"
}
],
"constraints": [
"k == lists.length",
"0 <= k <= 10^4"
],
"leetcode_url": "https://leetcode.com/problems/merge-k-sorted-lists/",
"reference_solution": "class Solution:\n def mergeKLists(self, lists: list[Optional[ListNode]]) -> Optional[ListNode]:\n if not lists or len(lists) == 0:\n return None\n while len(lists) > 1:\n mergedLists = []\n for i in range(0, len(lists), 2):\n l1 = lists[i]\n l2 = lists[i + 1] if (i + 1) < len(lists) else None\n mergedLists.append(self.mergeList(l1, l2))\n lists = mergedLists\n return lists[0]\n def mergeList(self, l1, l2):\n dummy = node = ListNode()\n while l1 and l2:\n if l1.val < l2.val:\n node.next, l1 = l1, l1.next\n else:\n node.next, l2 = l2, l2.next\n node = node.next\n node.next = l1 or l2\n return dummy.next"
},
{
"id": "nc-25",
"problem_number": 25,
"name": "Reverse Nodes in k-Group",
"pattern": "Linked List",
"difficulty": "Hard",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n pass",
"description": "Reverse the nodes of the list k at a time, and return the modified list.",
"examples": [
{
"input": "head = [1,2,3,4,5], k = 2",
"output": "[2,1,4,3,5]"
}
],
"constraints": [
"1 <= k <= sz <= 5000"
],
"leetcode_url": "https://leetcode.com/problems/reverse-nodes-in-k-group/",
"reference_solution": "class Solution:\n def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n dummy = ListNode(0, head)\n groupPrev = dummy\n while True:\n kth = self.getKth(groupPrev, k)\n if not kth:\n break\n groupNext = kth.next\n prev, curr = kth.next, groupPrev.next\n while curr != groupNext:\n tmp = curr.next\n curr.next = prev\n prev = curr\n curr = tmp\n tmp = groupPrev.next\n groupPrev.next = kth\n groupPrev = tmp\n return dummy.next\n def getKth(self, curr, k):\n while curr and k > 0:\n curr = curr.next\n k -= 1\n return curr"
},
{
"id": "nc-226",
"problem_number": 226,
"name": "Invert Binary Tree",
"pattern": "Trees",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n pass",
"description": "Given the root of a binary tree, invert the tree, and return its root.",
"examples": [
{
"input": "root = [4,2,7,1,3,6,9]",
"output": "[4,7,2,9,6,3,1]"
}
],
"constraints": [
"The number of nodes in the tree is in the range [0, 100]."
],
"leetcode_url": "https://leetcode.com/problems/invert-binary-tree/",
"reference_solution": "class Solution:\n def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n if not root:\n return None\n root.left, root.right = root.right, root.left\n self.invertTree(root.left)\n self.invertTree(root.right)\n return root"
},
{
"id": "nc-104",
"problem_number": 104,
"name": "Maximum Depth of Binary Tree",
"pattern": "Trees",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def maxDepth(self, root: Optional[TreeNode]) -> int:\n pass",
"description": "Given the root of a binary tree, return its maximum depth.",
"examples": [
{
"input": "root = [3,9,20,null,null,15,7]",
"output": "3"
}
],
"constraints": [
"Number of nodes is in range [0, 10^4]."
],
"leetcode_url": "https://leetcode.com/problems/maximum-depth-of-binary-tree/",
"reference_solution": "class Solution:\n def maxDepth(self, root: Optional[TreeNode]) -> int:\n if not root:\n return 0\n return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))"
},
{
"id": "nc-543",
"problem_number": 543,
"name": "Diameter of Binary Tree",
"pattern": "Trees",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n pass",
"description": "Return the length of the diameter of the tree.",
"examples": [
{
"input": "root = [1,2,3,4,5]",
"output": "3"
}
],
"constraints": [
"Number of nodes in range [1, 10^4]."
],
"leetcode_url": "https://leetcode.com/problems/diameter-of-binary-tree/",
"reference_solution": "class Solution:\n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n res = 0\n def dfs(curr):\n nonlocal res\n if not curr:\n return 0\n left, right = dfs(curr.left), dfs(curr.right)\n res = max(res, left + right)\n return 1 + max(left, right)\n dfs(root)\n return res"
},
{
"id": "nc-110",
"problem_number": 110,
"name": "Balanced Binary Tree",
"pattern": "Trees",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def isBalanced(self, root: Optional[TreeNode]) -> bool:\n pass",
"description": "Determine if a binary tree is height-balanced.",
"examples": [
{
"input": "root = [3,9,20,null,null,15,7]",
"output": "true"
}
],
"constraints": [
"Number of nodes in range [0, 5000]."
],
"leetcode_url": "https://leetcode.com/problems/balanced-binary-tree/",
"reference_solution": "class Solution:\n def isBalanced(self, root: Optional[TreeNode]) -> bool:\n def dfs(root):\n if not root:\n return [True, 0]\n left, right = dfs(root.left), dfs(root.right)\n balanced = left[0] and right[0] and abs(left[1] - right[1]) <= 1\n return [balanced, 1 + max(left[1], right[1])]\n return dfs(root)[0]"
},
{
"id": "nc-100",
"problem_number": 100,
"name": "Same Tree",
"pattern": "Trees",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:\n pass",
"description": "Check if two binary trees are structurally identical and the nodes have the same value.",
"examples": [
{
"input": "p = [1,2,3], q = [1,2,3]",
"output": "true"
}
],
"constraints": [
"Number of nodes in range [0, 100]."
],
"leetcode_url": "https://leetcode.com/problems/same-tree/",
"reference_solution": "class Solution:\n def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:\n if not p and not q:\n return True\n if p and q and p.val == q.val:\n return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\n return False"
},
{
"id": "nc-572",
"problem_number": 572,
"name": "Subtree of Another Tree",
"pattern": "Trees",
"difficulty": "Easy",
"time_complexity": "O(S * T)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n pass",
"description": "Return true if there is a subtree of root with the same structure and node values of subRoot.",
"examples": [
{
"input": "root = [3,4,5,1,2], subRoot = [4,1,2]",
"output": "true"
}
],
"constraints": [
"Number of nodes in root is in range [1, 2000]."
],
"leetcode_url": "https://leetcode.com/problems/subtree-of-another-tree/",
"reference_solution": "class Solution:\n def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n if not subRoot:\n return True\n if not root:\n return False\n if self.sameTree(root, subRoot):\n return True\n return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)\n def sameTree(self, root, subRoot):\n if not root and not subRoot:\n return True\n if root and subRoot and root.val == subRoot.val:\n return self.sameTree(root.left, subRoot.left) and self.sameTree(root.right, subRoot.right)\n return False"
},
{
"id": "nc-235",
"problem_number": 235,
"name": "Lowest Common Ancestor of a Binary Search Tree",
"pattern": "Trees",
"difficulty": "Medium",
"time_complexity": "O(log N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n pass",
"description": "Find the lowest common ancestor (LCA) node of two given nodes in the BST.",
"examples": [
{
"input": "root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8",
"output": "6"
}
],
"constraints": [
"All Node.val are unique."
],
"leetcode_url": "https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/",
"reference_solution": "class Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n cur = root\n while cur:\n if p.val > cur.val and q.val > cur.val:\n cur = cur.right\n elif p.val < cur.val and q.val < cur.val:\n cur = cur.left\n else:\n return cur"
},
{
"id": "nc-102",
"problem_number": 102,
"name": "Binary Tree Level Order Traversal",
"pattern": "Trees",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def levelOrder(self, root: Optional[TreeNode]) -> list[list[int]]:\n pass",
"description": "Return the level order traversal of its nodes' values (i.e., from left to right, level by level).",
"examples": [
{
"input": "root = [3,9,20,null,null,15,7]",
"output": "[[3],[9,20],[15,7]]"
}
],
"constraints": [
"Number of nodes in range [0, 2000]."
],
"leetcode_url": "https://leetcode.com/problems/binary-tree-level-order-traversal/",
"reference_solution": "from collections import deque\n\nclass Solution:\n def levelOrder(self, root: Optional[TreeNode]) -> list[list[int]]:\n res = []\n q = deque([root])\n while q:\n val = []\n for _ in range(len(q)):\n node = q.popleft()\n if node:\n val.append(node.val)\n q.append(node.left)\n q.append(node.right)\n if val:\n res.append(val)\n return res"
},
{
"id": "nc-199",
"problem_number": 199,
"name": "Binary Tree Right Side View",
"pattern": "Trees",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def rightSideView(self, root: Optional[TreeNode]) -> list[int]:\n pass",
"description": "Return the values of the nodes you can see ordered from top to bottom standing on the right side.",
"examples": [
{
"input": "root = [1,2,3,null,5,null,4]",
"output": "[1,3,4]"
}
],
"constraints": [
"Number of nodes in range [0, 100]."
],
"leetcode_url": "https://leetcode.com/problems/binary-tree-right-side-view/",
"reference_solution": "from collections import deque\n\nclass Solution:\n def rightSideView(self, root: Optional[TreeNode]) -> list[int]:\n res = []\n q = deque([root])\n while q:\n rightSide = None\n for _ in range(len(q)):\n node = q.popleft()\n if node:\n rightSide = node\n q.append(node.left)\n q.append(node.right)\n if rightSide:\n res.append(rightSide.val)\n return res"
},
{
"id": "nc-1448",
"problem_number": 1448,
"name": "Count Good Nodes in Binary Tree",
"pattern": "Trees",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def goodNodes(self, root: TreeNode) -> int:\n pass",
"description": "A node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.",
"examples": [
{
"input": "root = [3,1,4,3,null,1,5]",
"output": "4"
}
],
"constraints": [
"Number of nodes in range [1, 10^5]."
],
"leetcode_url": "https://leetcode.com/problems/count-good-nodes-in-binary-tree/",
"reference_solution": "class Solution:\n def goodNodes(self, root: TreeNode) -> int:\n def dfs(node, maxVal):\n if not node:\n return 0\n res = 1 if node.val >= maxVal else 0\n maxVal = max(maxVal, node.val)\n res += dfs(node.left, maxVal)\n res += dfs(node.right, maxVal)\n return res\n return dfs(root, root.val)"
},
{
"id": "nc-98",
"problem_number": 98,
"name": "Validate Binary Search Tree",
"pattern": "Trees",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n pass",
"description": "Determine if a binary tree is a valid binary search tree (BST).",
"examples": [
{
"input": "root = [2,1,3]",
"output": "true"
}
],
"constraints": [
"Number of nodes in range [1, 10^4]."
],
"leetcode_url": "https://leetcode.com/problems/validate-binary-search-tree/",
"reference_solution": "class Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n def valid(node, left, right):\n if not node:\n return True\n if not (left < node.val < right):\n return False\n return valid(node.left, left, node.val) and valid(node.right, node.val, right)\n return valid(root, float(\"-inf\"), float(\"inf\"))"
},
{
"id": "nc-230",
"problem_number": 230,
"name": "Kth Smallest Element in a BST",
"pattern": "Trees",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:\n pass",
"description": "Given the root of a BST, return the kth smallest value (1-indexed) of all the values in the tree.",
"examples": [
{
"input": "root = [3,1,4,null,2], k = 1",
"output": "1"
}
],
"constraints": [
"1 <= k <= n <= 10^4"
],
"leetcode_url": "https://leetcode.com/problems/kth-smallest-element-in-a-bst/",
"reference_solution": "class Solution:\n def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:\n stack = []\n curr = root\n while stack or curr:\n while curr:\n stack.append(curr)\n curr = curr.left\n curr = stack.pop()\n k -= 1\n if k == 0:\n return curr.val\n curr = curr.right"
},
{
"id": "nc-105",
"problem_number": 105,
"name": "Construct Binary Tree from Preorder and Inorder Traversal",
"pattern": "Trees",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def buildTree(self, preorder: list[int], inorder: list[int]) -> Optional[TreeNode]:\n pass",
"description": "Construct and return the binary tree given two integer arrays preorder and inorder.",
"examples": [
{
"input": "preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]",
"output": "[3,9,20,null,null,15,7]"
}
],
"constraints": [
"1 <= preorder.length <= 3000"
],
"leetcode_url": "https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/",
"reference_solution": "class Solution:\n def buildTree(self, preorder: list[int], inorder: list[int]) -> Optional[TreeNode]:\n if not preorder or not inorder:\n return None\n root = TreeNode(preorder[0])\n mid = inorder.index(preorder[0])\n root.left = self.buildTree(preorder[1 : mid + 1], inorder[:mid])\n root.right = self.buildTree(preorder[mid + 1 :], inorder[mid + 1 :])\n return root"
},
{
"id": "nc-124",
"problem_number": 124,
"name": "Binary Tree Maximum Path Sum",
"pattern": "Trees",
"difficulty": "Hard",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def maxPathSum(self, root: Optional[TreeNode]) -> int:\n pass",
"description": "Return the maximum path sum of any non-empty path in a binary tree.",
"examples": [
{
"input": "root = [1,2,3]",
"output": "6"
},
{
"input": "root = [-10,9,20,null,null,15,7]",
"output": "42"
}
],
"constraints": [
"Number of nodes in range [1, 3 * 10^4]."
],
"leetcode_url": "https://leetcode.com/problems/binary-tree-maximum-path-sum/",
"reference_solution": "class Solution:\n def maxPathSum(self, root: Optional[TreeNode]) -> int:\n res = [root.val]\n def dfs(root):\n if not root:\n return 0\n leftMax = max(dfs(root.left), 0)\n rightMax = max(dfs(root.right), 0)\n res[0] = max(res[0], root.val + leftMax + rightMax)\n return root.val + max(leftMax, rightMax)\n dfs(root)\n return res[0]"
},
{
"id": "nc-297",
"problem_number": 297,
"name": "Serialize and Deserialize Binary Tree",
"pattern": "Trees",
"difficulty": "Hard",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Codec:\n def serialize(self, root):\n pass\n def deserialize(self, data):\n pass",
"description": "Design an algorithm to serialize and deserialize a binary tree.",
"examples": [
{
"input": "root = [1,2,3,null,null,4,5]",
"output": "[1,2,3,null,null,4,5]"
}
],
"constraints": [
"Number of nodes in range [0, 10^4]."
],
"leetcode_url": "https://leetcode.com/problems/serialize-and-deserialize-binary-tree/",
"reference_solution": "class Codec:\n def serialize(self, root):\n res = []\n def dfs(node):\n if not node:\n res.append(\"N\")\n return\n res.append(str(node.val))\n dfs(node.left)\n dfs(node.right)\n dfs(root)\n return \",\".join(res)\n def deserialize(self, data):\n vals = data.split(\",\")\n self.i = 0\n def dfs():\n if vals[self.i] == \"N\":\n self.i += 1\n return None\n node = TreeNode(int(vals[self.i]))\n self.i += 1\n node.left = dfs()\n node.right = dfs()\n return node\n return dfs()"
},
{
"id": "nc-703",
"problem_number": 703,
"name": "Kth Largest Element in a Stream",
"pattern": "Heap / Priority Queue",
"difficulty": "Easy",
"time_complexity": "O(N log K)",
"space_complexity": "O(K)",
"starter_code": "class KthLargest:\n def __init__(self, k: int, nums: list[int]):\n pass\n def add(self, val: int) -> int:\n pass",
"description": "Design a class to find the kth largest element in a stream.",
"examples": [
{
"input": "[\"KthLargest\",\"add\",\"add\",\"add\",\"add\",\"add\"]",
"output": "[null,4,5,5,8,8]"
}
],
"constraints": [
"1 <= k <= 10^4"
],
"leetcode_url": "https://leetcode.com/problems/kth-largest-element-in-a-stream/",
"reference_solution": "import heapq\n\nclass KthLargest:\n def __init__(self, k: int, nums: list[int]):\n self.minHeap, self.k = nums, k\n heapq.heapify(self.minHeap)\n while len(self.minHeap) > k: heapq.heappop(self.minHeap)\n def add(self, val: int) -> int:\n heapq.heappush(self.minHeap, val)\n if len(self.minHeap) > self.k: heapq.heappop(self.minHeap)\n return self.minHeap[0]"
},
{
"id": "nc-1046",
"problem_number": 1046,
"name": "Last Stone Weight",
"pattern": "Heap / Priority Queue",
"difficulty": "Easy",
"time_complexity": "O(N log N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def lastStoneWeight(self, stones: list[int]) -> int:\n pass",
"description": "Smash the two heaviest stones x and y together until at most one stone is left.",
"examples": [
{
"input": "stones = [2,7,4,1,8,1]",
"output": "1"
}
],
"constraints": [
"1 <= stones.length <= 30"
],
"leetcode_url": "https://leetcode.com/problems/last-stone-weight/",
"reference_solution": "import heapq\n\nclass Solution:\n def lastStoneWeight(self, stones: list[int]) -> int:\n stones = [-s for s in stones]\n heapq.heapify(stones)\n while len(stones) > 1:\n first = heapq.heappop(stones)\n second = heapq.heappop(stones)\n if second > first: heapq.heappush(stones, first - second)\n stones.append(0)\n return abs(stones[0])"
},
{
"id": "nc-973",
"problem_number": 973,
"name": "K Closest Points to Origin",
"pattern": "Heap / Priority Queue",
"difficulty": "Medium",
"time_complexity": "O(N log K)",
"space_complexity": "O(K)",
"starter_code": "class Solution:\n def kClosest(self, points: list[list[int]], k: int) -> list[list[int]]:\n pass",
"description": "Given an array of points, return the k closest points to the origin (0, 0).",
"examples": [
{
"input": "points = [[1,3],[-2,2]], k = 1",
"output": "[[-2,2]]"
}
],
"constraints": [
"1 <= k <= points.length <= 10^4"
],
"leetcode_url": "https://leetcode.com/problems/k-closest-points-to-origin/",
"reference_solution": "import heapq\n\nclass Solution:\n def kClosest(self, points: list[list[int]], k: int) -> list[list[int]]:\n pts = []\n for x, y in points:\n dist = (x ** 2) + (y ** 2)\n pts.append([dist, x, y])\n heapq.heapify(pts)\n res = []\n for _ in range(k):\n dist, x, y = heapq.heappop(pts)\n res.append([x, y])\n return res"
},
{
"id": "nc-215",
"problem_number": 215,
"name": "Kth Largest Element in an Array",
"pattern": "Heap / Priority Queue",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def findKthLargest(self, nums: list[int], k: int) -> int:\n pass",
"description": "Given an integer array nums and an integer k, return the kth largest element in the array.",
"examples": [
{
"input": "nums = [3,2,1,5,6,4], k = 2",
"output": "5"
}
],
"constraints": [
"1 <= k <= nums.length <= 10^5"
],
"leetcode_url": "https://leetcode.com/problems/kth-largest-element-in-an-array/",
"reference_solution": "import heapq\n\nclass Solution:\n def findKthLargest(self, nums: list[int], k: int) -> int:\n return heapq.nlargest(k, nums)[-1]"
},
{
"id": "nc-621",
"problem_number": 621,
"name": "Task Scheduler",
"pattern": "Heap / Priority Queue",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def leastInterval(self, tasks: list[str], n: int) -> int:\n pass",
"description": "Return the minimum number of CPU intervals required to complete all tasks with cooling period n.",
"examples": [
{
"input": "tasks = [\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"], n = 2",
"output": "8"
}
],
"constraints": [
"1 <= tasks.length <= 10^4",
"0 <= n <= 100"
],
"leetcode_url": "https://leetcode.com/problems/task-scheduler/",
"reference_solution": "from collections import Counter, deque\nimport heapq\n\nclass Solution:\n def leastInterval(self, tasks: list[str], n: int) -> int:\n count = Counter(tasks)\n maxHeap = [-cnt for cnt in count.values()]\n heapq.heapify(maxHeap)\n time = 0\n q = deque()\n while maxHeap or q:\n time += 1\n if maxHeap:\n cnt = 1 + heapq.heappop(maxHeap)\n if cnt: q.append([cnt, time + n])\n if q and q[0][1] == time:\n heapq.heappush(maxHeap, q.popleft()[0])\n return time"
},
{
"id": "nc-355",
"problem_number": 355,
"name": "Design Twitter",
"pattern": "Heap / Priority Queue",
"difficulty": "Medium",
"time_complexity": "O(10 log K)",
"space_complexity": "O(N)",
"starter_code": "class Twitter:\n def __init__(self):\n pass\n def postTweet(self, userId: int, tweetId: int) -> None:\n pass\n def getNewsFeed(self, userId: int) -> list[int]:\n pass\n def follow(self, followerId: int, followeeId: int) -> None:\n pass\n def unfollow(self, followerId: int, followeeId: int) -> None:\n pass",
"description": "Design a simplified version of Twitter where users can post tweets, follow/unfollow, and get the 10 most recent tweets.",
"examples": [
{
"input": "[\"Twitter\",\"postTweet\",\"getNewsFeed\",\"follow\",\"postTweet\",\"getNewsFeed\"]",
"output": "[null,null,[5],null,null,[6,5]]"
}
],
"constraints": [
"1 <= userId, followeeId <= 500"
],
"leetcode_url": "https://leetcode.com/problems/design-twitter/",
"reference_solution": "from collections import defaultdict\nimport heapq\n\nclass Twitter:\n def __init__(self):\n self.count = 0\n self.tweetMap = defaultdict(list)\n self.followMap = defaultdict(set)\n def postTweet(self, userId: int, tweetId: int) -> None:\n self.tweetMap[userId].append([self.count, tweetId])\n self.count -= 1\n def getNewsFeed(self, userId: int) -> list[int]:\n res, minHeap = [], []\n self.followMap[userId].add(userId)\n for followeeId in self.followMap[userId]:\n if followeeId in self.tweetMap:\n index = len(self.tweetMap[followeeId]) - 1\n count, tweetId = self.tweetMap[followeeId][index]\n heapq.heappush(minHeap, [count, tweetId, followeeId, index - 1])\n while minHeap and len(res) < 10:\n count, tweetId, followeeId, index = heapq.heappop(minHeap)\n res.append(tweetId)\n if index >= 0:\n count, tweetId = self.tweetMap[followeeId][index]\n heapq.heappush(minHeap, [count, tweetId, followeeId, index - 1])\n return res\n def follow(self, followerId: int, followeeId: int) -> None:\n self.followMap[followerId].add(followeeId)\n def unfollow(self, followerId: int, followeeId: int) -> None:\n if followeeId in self.followMap[followerId]: self.followMap[followerId].remove(followeeId)"
},
{
"id": "nc-295",
"problem_number": 295,
"name": "Find Median from Data Stream",
"pattern": "Heap / Priority Queue",
"difficulty": "Hard",
"time_complexity": "O(log N)",
"space_complexity": "O(N)",
"starter_code": "class MedianFinder:\n def __init__(self):\n pass\n def addNum(self, num: int) -> None:\n pass\n def findMedian(self) -> float:\n pass",
"description": "Find the median of all elements added so far from a data stream.",
"examples": [
{
"input": "[\"MedianFinder\",\"addNum\",\"addNum\",\"findMedian\",\"addNum\",\"findMedian\"]",
"output": "[null,null,null,1.5,null,2.0]"
}
],
"constraints": [
"-10^5 <= num <= 10^5"
],
"leetcode_url": "https://leetcode.com/problems/find-median-from-data-stream/",
"reference_solution": "import heapq\n\nclass MedianFinder:\n def __init__(self):\n self.small, self.large = [], []\n def addNum(self, num: int) -> None:\n if self.large and num > self.large[0]: heapq.heappush(self.large, num)\n else: heapq.heappush(self.small, -1 * num)\n if len(self.small) > len(self.large) + 1:\n val = -1 * heapq.heappop(self.small)\n heapq.heappush(self.large, val)\n if len(self.large) > len(self.small) + 1:\n val = heapq.heappop(self.large)\n heapq.heappush(self.small, -1 * val)\n def findMedian(self) -> float:\n if len(self.small) > len(self.large): return -1 * self.small[0]\n elif len(self.large) > len(self.small): return self.large[0]\n return (-1 * self.small[0] + self.large[0]) / 2.0"
},
{
"id": "nc-78",
"problem_number": 78,
"name": "Subsets",
"pattern": "Backtracking",
"difficulty": "Medium",
"time_complexity": "O(N * 2^N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def subsets(self, nums: list[int]) -> list[list[int]]:\n pass",
"description": "Given an integer array nums of unique elements, return all possible subsets (the power set).",
"examples": [
{
"input": "nums = [1,2,3]",
"output": "[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]"
}
],
"constraints": [
"1 <= nums.length <= 10"
],
"leetcode_url": "https://leetcode.com/problems/subsets/",
"reference_solution": "class Solution:\n def subsets(self, nums: list[int]) -> list[list[int]]:\n res = []\n subset = []\n def dfs(i):\n if i >= len(nums):\n res.append(subset.copy())\n return\n subset.append(nums[i])\n dfs(i + 1)\n subset.pop()\n dfs(i + 1)\n dfs(0)\n return res"
},
{
"id": "nc-39",
"problem_number": 39,
"name": "Combination Sum",
"pattern": "Backtracking",
"difficulty": "Medium",
"time_complexity": "O(2^target)",
"space_complexity": "O(target)",
"starter_code": "class Solution:\n def combinationSum(self, candidates: list[int], target: int) -> list[list[int]]:\n pass",
"description": "Return a list of all unique combinations of candidates where the chosen numbers sum to target.",
"examples": [
{
"input": "candidates = [2,3,6,7], target = 7",
"output": "[[2,2,3],[7]]"
}
],
"constraints": [
"1 <= candidates.length <= 30"
],
"leetcode_url": "https://leetcode.com/problems/combination-sum/",
"reference_solution": "class Solution:\n def combinationSum(self, candidates: list[int], target: int) -> list[list[int]]:\n res = []\n def dfs(i, cur, total):\n if total == target:\n res.append(cur.copy())\n return\n if i >= len(candidates) or total > target:\n return\n cur.append(candidates[i])\n dfs(i, cur, total + candidates[i])\n cur.pop()\n dfs(i + 1, cur, total)\n dfs(0, [], 0)\n return res"
},
{
"id": "nc-40",
"problem_number": 40,
"name": "Combination Sum II",
"pattern": "Backtracking",
"difficulty": "Medium",
"time_complexity": "O(2^N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def combinationSum2(self, candidates: list[int], target: int) -> list[list[int]]:\n pass",
"description": "Find all unique combinations in candidates where the candidate numbers sum to target, using each number once.",
"examples": [
{
"input": "candidates = [10,1,2,7,6,1,5], target = 8",
"output": "[[1,1,6],[1,2,5],[1,7],[2,6]]"
}
],
"constraints": [
"1 <= candidates.length <= 100"
],
"leetcode_url": "https://leetcode.com/problems/combination-sum-ii/",
"reference_solution": "class Solution:\n def combinationSum2(self, candidates: list[int], target: int) -> list[list[int]]:\n candidates.sort()\n res = []\n def backtrack(cur, pos, target):\n if target == 0:\n res.append(cur.copy())\n return\n if target <= 0:\n return\n prev = -1\n for i in range(pos, len(candidates)):\n if candidates[i] == prev:\n continue\n cur.append(candidates[i])\n backtrack(cur, i + 1, target - candidates[i])\n cur.pop()\n prev = candidates[i]\n backtrack([], 0, target)\n return res"
},
{
"id": "nc-46",
"problem_number": 46,
"name": "Permutations",
"pattern": "Backtracking",
"difficulty": "Medium",
"time_complexity": "O(N! * N)",
"space_complexity": "O(N!)",
"starter_code": "class Solution:\n def permute(self, nums: list[int]) -> list[list[int]]:\n pass",
"description": "Given an array nums of distinct integers, return all the possible permutations.",
"examples": [
{
"input": "nums = [1,2,3]",
"output": "[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]"
}
],
"constraints": [
"1 <= nums.length <= 6"
],
"leetcode_url": "https://leetcode.com/problems/permutations/",
"reference_solution": "class Solution:\n def permute(self, nums: list[int]) -> list[list[int]]:\n res = []\n if len(nums) == 1: return [nums[:]]\n for i in range(len(nums)):\n n = nums.pop(0)\n perms = self.permute(nums)\n for perm in perms: perm.append(n)\n res.extend(perms)\n nums.append(n)\n return res"
},
{
"id": "nc-90",
"problem_number": 90,
"name": "Subsets II",
"pattern": "Backtracking",
"difficulty": "Medium",
"time_complexity": "O(N * 2^N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def subsetsWithDup(self, nums: list[int]) -> list[list[int]]:\n pass",
"description": "Given an integer array nums that may contain duplicates, return all possible subsets (the power set).",
"examples": [
{
"input": "nums = [1,2,2]",
"output": "[[],[1],[1,2],[1,2,2],[2],[2,2]]"
}
],
"constraints": [
"1 <= nums.length <= 10"
],
"leetcode_url": "https://leetcode.com/problems/subsets-ii/",
"reference_solution": "class Solution:\n def subsetsWithDup(self, nums: list[int]) -> list[list[int]]:\n res = []\n nums.sort()\n def backtrack(i, subset):\n if i == len(nums):\n res.append(subset[::])\n return\n subset.append(nums[i])\n backtrack(i + 1, subset)\n subset.pop()\n while i + 1 < len(nums) and nums[i] == nums[i + 1]: i += 1\n backtrack(i + 1, subset)\n backtrack(0, [])\n return res"
},
{
"id": "nc-22",
"problem_number": 22,
"name": "Generate Parentheses",
"pattern": "Backtracking",
"difficulty": "Medium",
"time_complexity": "O(4^N / sqrt(N))",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def generateParenthesis(self, n: int) -> list[str]:\n pass",
"description": "Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.",
"examples": [
{
"input": "n = 3",
"output": "[\"((()))\",\"(()())\",\"(())()\",\"()(())\",\"()()()\"]"
}
],
"constraints": [
"1 <= n <= 8"
],
"leetcode_url": "https://leetcode.com/problems/generate-parentheses/",
"reference_solution": "class Solution:\n def generateParenthesis(self, n: int) -> list[str]:\n stack, res = [], []\n def backtrack(openN, closedN):\n if openN == closedN == n:\n res.append(\"\".join(stack))\n return\n if openN < n:\n stack.append(\"(\")\n backtrack(openN + 1, closedN)\n stack.pop()\n if closedN < openN:\n stack.append(\")\")\n backtrack(openN, closedN + 1)\n stack.pop()\n backtrack(0, 0)\n return res"
},
{
"id": "nc-79",
"problem_number": 79,
"name": "Word Search",
"pattern": "Backtracking",
"difficulty": "Medium",
"time_complexity": "O(M * N * 4^L)",
"space_complexity": "O(L)",
"starter_code": "class Solution:\n def exist(self, board: list[list[str]], word: str) -> bool:\n pass",
"description": "Given an m x n grid of characters board and a string word, return true if word exists in the grid.",
"examples": [
{
"input": "board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCCED\"",
"output": "true"
}
],
"constraints": [
"m == board.length",
"n = board[i].length",
"1 <= word.length <= 15"
],
"leetcode_url": "https://leetcode.com/problems/word-search/",
"reference_solution": "class Solution:\n def exist(self, board: list[list[str]], word: str) -> bool:\n ROWS, COLS = len(board), len(board[0])\n path = set()\n def dfs(r, c, i):\n if i == len(word): return True\n if (r < 0 or c < 0 or r >= ROWS or c >= COLS or word[i] != board[r][c] or (r, c) in path): return False\n path.add((r, c))\n res = (dfs(r + 1, c, i + 1) or dfs(r - 1, c, i + 1) or dfs(r, c + 1, i + 1) or dfs(r, c - 1, i + 1))\n path.remove((r, c))\n return res\n for r in range(ROWS):\n for c in range(COLS):\n if dfs(r, c, 0): return True\n return False"
},
{
"id": "nc-131",
"problem_number": 131,
"name": "Palindrome Partitioning",
"pattern": "Backtracking",
"difficulty": "Medium",
"time_complexity": "O(N * 2^N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def partition(self, s: str) -> list[list[str]]:\n pass",
"description": "Partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitionings.",
"examples": [
{
"input": "s = \"aab\"",
"output": "[[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]"
}
],
"constraints": [
"1 <= s.length <= 16"
],
"leetcode_url": "https://leetcode.com/problems/palindrome-partitioning/",
"reference_solution": "class Solution:\n def partition(self, s: str) -> list[list[str]]:\n res, part = [], []\n def dfs(i):\n if i >= len(s):\n res.append(part.copy())\n return\n for j in range(i, len(s)):\n if self.isPali(s, i, j):\n part.append(s[i : j + 1])\n dfs(j + 1)\n part.pop()\n dfs(0)\n return res\n def isPali(self, s, l, r):\n while l < r:\n if s[l] != s[r]: return False\n l, r = l + 1, r - 1\n return True"
},
{
"id": "nc-17",
"problem_number": 17,
"name": "Letter Combinations of a Phone Number",
"pattern": "Backtracking",
"difficulty": "Medium",
"time_complexity": "O(N * 4^N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def letterCombinations(self, digits: str) -> list[str]:\n pass",
"description": "Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.",
"examples": [
{
"input": "digits = \"23\"",
"output": "[\"ad\",\"ae\",\"af\",\"bd\",\"be\",\"bf\",\"cd\",\"ce\",\"cf\"]"
}
],
"constraints": [
"0 <= digits.length <= 4"
],
"leetcode_url": "https://leetcode.com/problems/letter-combinations-of-a-phone-number/",
"reference_solution": "class Solution:\n def letterCombinations(self, digits: str) -> list[str]:\n res = []\n digitToChar = {\"2\": \"abc\", \"3\": \"def\", \"4\": \"ghi\", \"5\": \"jkl\", \"6\": \"mno\", \"7\": \"qprs\", \"8\": \"tuv\", \"9\": \"wxyz\"}\n def backtrack(i, curStr):\n if len(curStr) == len(digits):\n res.append(curStr)\n return\n for c in digitToChar[digits[i]]:\n backtrack(i + 1, curStr + c)\n if digits: backtrack(0, \"\")\n return res"
},
{
"id": "nc-51",
"problem_number": 51,
"name": "N-Queens",
"pattern": "Backtracking",
"difficulty": "Hard",
"time_complexity": "O(N!)",
"space_complexity": "O(N^2)",
"starter_code": "class Solution:\n def solveNQueens(self, n: int) -> list[list[str]]:\n pass",
"description": "Place n queens on an n x n chessboard such that no two queens attack each other.",
"examples": [
{
"input": "n = 4",
"output": "[[\".Q..\",\"...Q\",\"Q...\",\"..Q.\"],[\"..Q.\",\"Q...\",\"...Q\",\".Q..\"]]"
}
],
"constraints": [
"1 <= n <= 9"
],
"leetcode_url": "https://leetcode.com/problems/n-queens/",
"reference_solution": "class Solution:\n def solveNQueens(self, n: int) -> list[list[str]]:\n col, posDiag, negDiag = set(), set(), set()\n res = []\n board = [[\".\"] * n for _ in range(n)]\n def backtrack(r):\n if r == n:\n copy = [\"\".join(row) for row in board]\n res.append(copy)\n return\n for c in range(n):\n if c in col or (r + c) in posDiag or (r - c) in negDiag: continue\n col.add(c); posDiag.add(r + c); negDiag.add(r - c); board[r][c] = \"Q\"\n backtrack(r + 1)\n col.remove(c); posDiag.remove(r + c); negDiag.remove(r - c); board[r][c] = \".\"\n backtrack(0)\n return res"
},
{
"id": "nc-208",
"problem_number": 208,
"name": "Implement Trie (Prefix Tree)",
"pattern": "Tries",
"difficulty": "Medium",
"time_complexity": "O(L)",
"space_complexity": "O(N * L)",
"starter_code": "class Trie:\n def __init__(self):\n pass\n def insert(self, word: str) -> None:\n pass\n def search(self, word: str) -> bool:\n pass\n def startsWith(self, prefix: str) -> bool:\n pass",
"description": "Implement a trie with insert, search, and startsWith methods.",
"examples": [
{
"input": "[\"Trie\",\"insert\",\"search\",\"search\",\"startsWith\",\"insert\",\"search\"]",
"output": "[null,null,true,false,true,null,true]"
}
],
"constraints": [
"1 <= word.length, prefix.length <= 2000"
],
"leetcode_url": "https://leetcode.com/problems/implement-trie-prefix-tree/",
"reference_solution": "class TrieNode:\n def __init__(self):\n self.children = {}\n self.end = False\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n def insert(self, word: str) -> None:\n curr = self.root\n for c in word:\n if c not in curr.children:\n curr.children[c] = TrieNode()\n curr = curr.children[c]\n curr.end = True\n def search(self, word: str) -> bool:\n curr = self.root\n for c in word:\n if c not in curr.children: return False\n curr = curr.children[c]\n return curr.end\n def startsWith(self, prefix: str) -> bool:\n curr = self.root\n for c in prefix:\n if c not in curr.children: return False\n curr = curr.children[c]\n return True"
},
{
"id": "nc-211",
"problem_number": 211,
"name": "Design Add and Search Words Data Structure",
"pattern": "Tries",
"difficulty": "Medium",
"time_complexity": "O(M)",
"space_complexity": "O(N)",
"starter_code": "class WordDictionary:\n def __init__(self):\n pass\n def addWord(self, word: str) -> None:\n pass\n def search(self, word: str) -> bool:\n pass",
"description": "Design a data structure that supports adding new words and finding if a string matches any previously added string, with '.' wildcard support.",
"examples": [
{
"input": "[\"WordDictionary\",\"addWord\",\"addWord\",\"addWord\",\"search\",\"search\",\"search\",\"search\"]",
"output": "[null,null,null,null,false,true,true,true]"
}
],
"constraints": [
"1 <= word.length <= 25"
],
"leetcode_url": "https://leetcode.com/problems/design-add-and-search-words-data-structure/",
"reference_solution": "class TrieNode:\n def __init__(self):\n self.children = {}\n self.word = False\n\nclass WordDictionary:\n def __init__(self):\n self.root = TrieNode()\n def addWord(self, word: str) -> None:\n cur = self.root\n for c in word:\n if c not in cur.children: cur.children[c] = TrieNode()\n cur = cur.children[c]\n cur.word = True\n def search(self, word: str) -> bool:\n def dfs(j, root):\n cur = root\n for i in range(j, len(word)):\n c = word[i]\n if c == \".\":\n for child in cur.children.values():\n if dfs(i + 1, child): return True\n return False\n else:\n if c not in cur.children: return False\n cur = cur.children[c]\n return cur.word\n return dfs(0, self.root)"
},
{
"id": "nc-212",
"problem_number": 212,
"name": "Word Search II",
"pattern": "Tries",
"difficulty": "Hard",
"time_complexity": "O(M * N * 4^L)",
"space_complexity": "O(W * L)",
"starter_code": "class Solution:\n def findWords(self, board: list[list[str]], words: list[str]) -> list[str]:\n pass",
"description": "Given an m x n board of characters and a list of strings words, return all words on the board.",
"examples": [
{
"input": "board = [[\"o\",\"a\",\"a\",\"n\"],[\"e\",\"t\",\"a\",\"e\"],[\"i\",\"h\",\"k\",\"r\"],[\"i\",\"f\",\"l\",\"v\"]], words = [\"oath\",\"pea\",\"eat\",\"rain\"]",
"output": "[\"eat\",\"oath\"]"
}
],
"constraints": [
"m == board.length",
"n == board[i].length",
"1 <= words.length <= 3 * 10^4"
],
"leetcode_url": "https://leetcode.com/problems/word-search-ii/",
"reference_solution": "class TrieNode:\n def __init__(self):\n self.children = {}\n self.isWord = False\n def addWord(self, word):\n cur = self\n for c in word:\n if c not in cur.children: cur.children[c] = TrieNode()\n cur = cur.children[c]\n cur.isWord = True\n\nclass Solution:\n def findWords(self, board: list[list[str]], words: list[str]) -> list[str]:\n root = TrieNode()\n for w in words: root.addWord(w)\n ROWS, COLS = len(board), len(board[0])\n res, visit = set(), set()\n def dfs(r, c, node, word):\n if (r < 0 or c < 0 or r == ROWS or c == COLS or (r, c) in visit or board[r][c] not in node.children):\n return\n visit.add((r, c))\n node = node.children[board[r][c]]\n word += board[r][c]\n if node.isWord: res.add(word)\n dfs(r + 1, c, node, word)\n dfs(r - 1, c, node, word)\n dfs(r, c + 1, node, word)\n dfs(r, c - 1, node, word)\n visit.remove((r, c))\n for r in range(ROWS):\n for c in range(COLS):\n dfs(r, c, root, \"\")\n return list(res)"
},
{
"id": "nc-200",
"problem_number": 200,
"name": "Number of Islands",
"pattern": "Graphs",
"difficulty": "Medium",
"time_complexity": "O(M * N)",
"space_complexity": "O(M * N)",
"starter_code": "class Solution:\n def numIslands(self, grid: list[list[str]]) -> int:\n pass",
"description": "Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.",
"examples": [
{
"input": "grid = [[\"1\",\"1\",\"1\",\"1\",\"0\"],[\"1\",\"1\",\"0\",\"1\",\"0\"],[\"1\",\"1\",\"0\",\"0\",\"0\"],[\"0\",\"0\",\"0\",\"0\",\"0\"]]",
"output": "1"
}
],
"constraints": [
"m == grid.length",
"n == grid[i].length"
],
"leetcode_url": "https://leetcode.com/problems/number-of-islands/",
"reference_solution": "class Solution:\n def numIslands(self, grid: list[list[str]]) -> int:\n if not grid: return 0\n rows, cols = len(grid), len(grid[0])\n islands = 0\n def dfs(r, c):\n if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] != \"1\": return\n grid[r][c] = \"0\"\n dfs(r + 1, c); dfs(r - 1, c); dfs(r, c + 1); dfs(r, c - 1)\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == \"1\":\n dfs(r, c)\n islands += 1\n return islands"
},
{
"id": "nc-695",
"problem_number": 695,
"name": "Max Area of Island",
"pattern": "Graphs",
"difficulty": "Medium",
"time_complexity": "O(M * N)",
"space_complexity": "O(M * N)",
"starter_code": "class Solution:\n def maxAreaOfIsland(self, grid: list[list[int]]) -> int:\n pass",
"description": "Return the maximum area of an island in grid. If there is no island, return 0.",
"examples": [
{
"input": "grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]",
"output": "6"
}
],
"constraints": [
"m == grid.length",
"n == grid[i].length"
],
"leetcode_url": "https://leetcode.com/problems/max-area-of-island/",
"reference_solution": "class Solution:\n def maxAreaOfIsland(self, grid: list[list[int]]) -> int:\n ROWS, COLS = len(grid), len(grid[0])\n visit = set()\n def dfs(r, c):\n if r < 0 or r == ROWS or c < 0 or c == COLS or grid[r][c] == 0 or (r, c) in visit: return 0\n visit.add((r, c))\n return 1 + dfs(r + 1, c) + dfs(r - 1, c) + dfs(r, c + 1) + dfs(r, c - 1)\n area = 0\n for r in range(ROWS):\n for c in range(COLS):\n area = max(area, dfs(r, c))\n return area"
},
{
"id": "nc-133",
"problem_number": 133,
"name": "Clone Graph",
"pattern": "Graphs",
"difficulty": "Medium",
"time_complexity": "O(V + E)",
"space_complexity": "O(V)",
"starter_code": "class Solution:\n def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:\n pass",
"description": "Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph.",
"examples": [
{
"input": "adjList = [[2,4],[1,3],[2,4],[1,3]]",
"output": "[[2,4],[1,3],[2,4],[1,3]]"
}
],
"constraints": [
"The number of nodes in the graph is in range [0, 100]."
],
"leetcode_url": "https://leetcode.com/problems/clone-graph/",
"reference_solution": "class Solution:\n def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:\n oldToNew = {}\n def dfs(node):\n if node in oldToNew: return oldToNew[node]\n copy = Node(node.val)\n oldToNew[node] = copy\n for nei in node.neighbors: copy.neighbors.append(dfs(nei))\n return copy\n return dfs(node) if node else None"
},
{
"id": "nc-286",
"problem_number": 286,
"name": "Walls and Gates",
"pattern": "Graphs",
"difficulty": "Medium",
"time_complexity": "O(M * N)",
"space_complexity": "O(M * N)",
"starter_code": "class Solution:\n def wallsAndGates(self, rooms: list[list[int]]) -> None:\n pass",
"description": "Fill each empty room with the distance to its nearest gate. A gate is 0, a wall is -1, an empty room is 2147483647.",
"examples": [
{
"input": "rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]",
"output": "[[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]"
}
],
"constraints": [
"m == rooms.length",
"n == rooms[i].length"
],
"leetcode_url": "https://leetcode.com/problems/walls-and-gates/",
"reference_solution": "from collections import deque\n\nclass Solution:\n def wallsAndGates(self, rooms: list[list[int]]) -> None:\n ROWS, COLS = len(rooms), len(rooms[0])\n q = deque()\n for r in range(ROWS):\n for c in range(COLS):\n if rooms[r][c] == 0: q.append((r, c))\n while q:\n r, c = q.popleft()\n for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n nr, nc = r + dr, c + dc\n if 0 <= nr < ROWS and 0 <= nc < COLS and rooms[nr][nc] == 2147483647:\n rooms[nr][nc] = rooms[r][c] + 1\n q.append((nr, nc))"
},
{
"id": "nc-994",
"problem_number": 994,
"name": "Rotting Oranges",
"pattern": "Graphs",
"difficulty": "Medium",
"time_complexity": "O(M * N)",
"space_complexity": "O(M * N)",
"starter_code": "class Solution:\n def orangesRotting(self, grid: list[list[int]]) -> int:\n pass",
"description": "Return the minimum number of minutes that must elapse until no cell has a fresh orange.",
"examples": [
{
"input": "grid = [[2,1,1],[1,1,0],[0,1,1]]",
"output": "4"
}
],
"constraints": [
"m == grid.length",
"n == grid[i].length"
],
"leetcode_url": "https://leetcode.com/problems/rotting-oranges/",
"reference_solution": "from collections import deque\n\nclass Solution:\n def orangesRotting(self, grid: list[list[int]]) -> int:\n q = deque()\n fresh = time = 0\n ROWS, COLS = len(grid), len(grid[0])\n for r in range(ROWS):\n for c in range(COLS):\n if grid[r][c] == 1: fresh += 1\n if grid[r][c] == 2: q.append((r, c))\n directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n while fresh > 0 and q:\n for _ in range(len(q)):\n r, c = q.popleft()\n for dr, dc in directions:\n row, col = r + dr, c + dc\n if row in range(ROWS) and col in range(COLS) and grid[row][col] == 1:\n grid[row][col] = 2\n q.append((row, col))\n fresh -= 1\n time += 1\n return time if fresh == 0 else -1"
},
{
"id": "nc-417",
"problem_number": 417,
"name": "Pacific Atlantic Water Flow",
"pattern": "Graphs",
"difficulty": "Medium",
"time_complexity": "O(M * N)",
"space_complexity": "O(M * N)",
"starter_code": "class Solution:\n def pacificAtlantic(self, heights: list[list[int]]) -> list[list[int]]:\n pass",
"description": "Return a list of grid coordinates where water can flow to both the Pacific and Atlantic oceans.",
"examples": [
{
"input": "heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]",
"output": "[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]"
}
],
"constraints": [
"m == heights.length",
"n == heights[r].length"
],
"leetcode_url": "https://leetcode.com/problems/pacific-atlantic-water-flow/",
"reference_solution": "class Solution:\n def pacificAtlantic(self, heights: list[list[int]]) -> list[list[int]]:\n ROWS, COLS = len(heights), len(heights[0])\n pac, atl = set(), set()\n def dfs(r, c, visit, prevHeight):\n if (r, c) in visit or r < 0 or c < 0 or r == ROWS or c == COLS or heights[r][c] < prevHeight: return\n visit.add((r, c))\n dfs(r + 1, c, visit, heights[r][c]); dfs(r - 1, c, visit, heights[r][c])\n dfs(r, c + 1, visit, heights[r][c]); dfs(r, c - 1, visit, heights[r][c])\n for c in range(COLS):\n dfs(0, c, pac, heights[0][c]); dfs(ROWS - 1, c, atl, heights[ROWS - 1][c])\n for r in range(ROWS):\n dfs(r, 0, pac, heights[r][0]); dfs(r, COLS - 1, atl, heights[r][COLS - 1])\n res = []\n for r in range(ROWS):\n for c in range(COLS):\n if (r, c) in pac and (r, c) in atl: res.append([r, c])\n return res"
},
{
"id": "nc-130",
"problem_number": 130,
"name": "Surrounded Regions",
"pattern": "Graphs",
"difficulty": "Medium",
"time_complexity": "O(M * N)",
"space_complexity": "O(M * N)",
"starter_code": "class Solution:\n def solve(self, board: list[list[str]]) -> None:\n pass",
"description": "Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.",
"examples": [
{
"input": "board = [[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"O\",\"X\"],[\"X\",\"X\",\"O\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]",
"output": "[[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]"
}
],
"constraints": [
"m == board.length",
"n == board[i].length"
],
"leetcode_url": "https://leetcode.com/problems/surrounded-regions/",
"reference_solution": "class Solution:\n def solve(self, board: list[list[str]]) -> None:\n ROWS, COLS = len(board), len(board[0])\n def capture(r, c):\n if r < 0 or c < 0 or r == ROWS or c == COLS or board[r][c] != \"O\": return\n board[r][c] = \"T\"\n capture(r + 1, c); capture(r - 1, c); capture(r, c + 1); capture(r, c - 1)\n for r in range(ROWS):\n for c in range(COLS):\n if board[r][c] == \"O\" and (r in [0, ROWS - 1] or c in [0, COLS - 1]): capture(r, c)\n for r in range(ROWS):\n for c in range(COLS):\n if board[r][c] == \"O\": board[r][c] = \"X\"\n elif board[r][c] == \"T\": board[r][c] = \"O\""
},
{
"id": "nc-207",
"problem_number": 207,
"name": "Course Schedule",
"pattern": "Graphs",
"difficulty": "Medium",
"time_complexity": "O(V + E)",
"space_complexity": "O(V + E)",
"starter_code": "class Solution:\n def canFinish(self, numCourses: int, prerequisites: list[list[int]]) -> bool:\n pass",
"description": "Return true if you can finish all courses given prerequisite pairs, or false otherwise.",
"examples": [
{
"input": "numCourses = 2, prerequisites = [[1,0]]",
"output": "true"
}
],
"constraints": [
"1 <= numCourses <= 2000"
],
"leetcode_url": "https://leetcode.com/problems/course-schedule/",
"reference_solution": "class Solution:\n def canFinish(self, numCourses: int, prerequisites: list[list[int]]) -> bool:\n preMap = {i: [] for i in range(numCourses)}\n for crs, pre in prerequisites: preMap[crs].append(pre)\n visiting = set()\n def dfs(crs):\n if crs in visiting: return False\n if preMap[crs] == []: return True\n visiting.add(crs)\n for pre in preMap[crs]:\n if not dfs(pre): return False\n visiting.remove(crs)\n preMap[crs] = []\n return True\n for c in range(numCourses):\n if not dfs(c): return False\n return True"
},
{
"id": "nc-210",
"problem_number": 210,
"name": "Course Schedule II",
"pattern": "Graphs",
"difficulty": "Medium",
"time_complexity": "O(V + E)",
"space_complexity": "O(V + E)",
"starter_code": "class Solution:\n def findOrder(self, numCourses: int, prerequisites: list[list[int]]) -> list[int]:\n pass",
"description": "Return the ordering of courses you should take to finish all courses.",
"examples": [
{
"input": "numCourses = 2, prerequisites = [[1,0]]",
"output": "[0,1]"
}
],
"constraints": [
"1 <= numCourses <= 2000"
],
"leetcode_url": "https://leetcode.com/problems/course-schedule-ii/",
"reference_solution": "class Solution:\n def findOrder(self, numCourses: int, prerequisites: list[list[int]]) -> list[int]:\n prereq = {c: [] for c in range(numCourses)}\n for crs, pre in prerequisites: prereq[crs].append(pre)\n output = []\n visit, cycle = set(), set()\n def dfs(crs):\n if crs in cycle: return False\n if crs in visit: return True\n cycle.add(crs)\n for pre in prereq[crs]:\n if not dfs(pre): return False\n cycle.remove(crs)\n visit.add(crs)\n output.append(crs)\n return True\n for c in range(numCourses):\n if not dfs(c): return []\n return output"
},
{
"id": "nc-261",
"problem_number": 261,
"name": "Graph Valid Tree",
"pattern": "Graphs",
"difficulty": "Medium",
"time_complexity": "O(V + E)",
"space_complexity": "O(V + E)",
"starter_code": "class Solution:\n def validTree(self, n: int, edges: list[list[int]]) -> bool:\n pass",
"description": "Given n nodes labeled from 0 to n - 1 and a list of undirected edges, return true if these edges form a valid tree.",
"examples": [
{
"input": "n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]",
"output": "true"
}
],
"constraints": [
"1 <= n <= 2000"
],
"leetcode_url": "https://leetcode.com/problems/graph-valid-tree/",
"reference_solution": "class Solution:\n def validTree(self, n: int, edges: list[list[int]]) -> bool:\n if not n: return True\n adj = {i: [] for i in range(n)}\n for n1, n2 in edges:\n adj[n1].append(n2)\n adj[n2].append(n1)\n visit = set()\n def dfs(i, prev):\n if i in visit: return False\n visit.add(i)\n for j in adj[i]:\n if j == prev: continue\n if not dfs(j, i): return False\n return True\n return dfs(0, -1) and len(visit) == n"
},
{
"id": "nc-323",
"problem_number": 323,
"name": "Number of Connected Components in an Undirected Graph",
"pattern": "Graphs",
"difficulty": "Medium",
"time_complexity": "O(V + E)",
"space_complexity": "O(V)",
"starter_code": "class Solution:\n def countComponents(self, n: int, edges: list[list[int]]) -> int:\n pass",
"description": "Find the number of connected components in an undirected graph.",
"examples": [
{
"input": "n = 5, edges = [[0,1],[1,2],[3,4]]",
"output": "2"
}
],
"constraints": [
"1 <= n <= 2000"
],
"leetcode_url": "https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/",
"reference_solution": "class Solution:\n def countComponents(self, n: int, edges: list[list[int]]) -> int:\n par = [i for i in range(n)]\n rank = [1] * n\n def find(n1):\n res = n1\n while res != par[res]:\n par[res] = par[par[res]]\n res = par[res]\n return res\n def union(n1, n2):\n p1, p2 = find(n1), find(n2)\n if p1 == p2: return 0\n if rank[p2] > rank[p1]: par[p1] = p2; rank[p2] += rank[p1]\n else: par[p2] = p1; rank[p1] += rank[p2]\n return 1\n res = n\n for n1, n2 in edges: res -= union(n1, n2)\n return res"
},
{
"id": "nc-684",
"problem_number": 684,
"name": "Redundant Connection",
"pattern": "Graphs",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def findRedundantConnection(self, edges: list[list[int]]) -> list[int]:\n pass",
"description": "Return an edge that can be removed so that the resulting graph is a tree of n nodes.",
"examples": [
{
"input": "edges = [[1,2],[1,3],[2,3]]",
"output": "[2,3]"
}
],
"constraints": [
"n == edges.length",
"3 <= n <= 1000"
],
"leetcode_url": "https://leetcode.com/problems/redundant-connection/",
"reference_solution": "class Solution:\n def findRedundantConnection(self, edges: list[list[int]]) -> list[int]:\n par = [i for i in range(len(edges) + 1)]\n rank = [1] * (len(edges) + 1)\n def find(n):\n p = par[n]\n while p != par[p]:\n par[p] = par[par[p]]\n p = par[p]\n return p\n def union(n1, n2):\n p1, p2 = find(n1), find(n2)\n if p1 == p2: return False\n if rank[p1] > rank[p2]: par[p2] = p1; rank[p1] += rank[p2]\n else: par[p1] = p2; rank[p2] += rank[p1]\n return True\n for n1, n2 in edges:\n if not union(n1, n2): return [n1, n2]"
},
{
"id": "nc-127",
"problem_number": 127,
"name": "Word Ladder",
"pattern": "Graphs",
"difficulty": "Hard",
"time_complexity": "O(M^2 * N)",
"space_complexity": "O(M^2 * N)",
"starter_code": "class Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: list[str]) -> int:\n pass",
"description": "Return the number of words in the shortest transformation sequence from beginWord to endWord.",
"examples": [
{
"input": "beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]",
"output": "5"
}
],
"constraints": [
"1 <= beginWord.length <= 10"
],
"leetcode_url": "https://leetcode.com/problems/word-ladder/",
"reference_solution": "from collections import defaultdict, deque\n\nclass Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: list[str]) -> int:\n if endWord not in wordList: return 0\n nei = defaultdict(list)\n wordList.append(beginWord)\n for word in wordList:\n for j in range(len(word)):\n pattern = word[:j] + \"*\" + word[j + 1 :]\n nei[pattern].append(word)\n visit = set([beginWord])\n q = deque([beginWord])\n res = 1\n while q:\n for _ in range(len(q)):\n word = q.popleft()\n if word == endWord: return res\n for j in range(len(word)):\n pattern = word[:j] + \"*\" + word[j + 1 :]\n for neiWord in nei[pattern]:\n if neiWord not in visit:\n visit.add(neiWord)\n q.append(neiWord)\n res += 1\n return 0"
},
{
"id": "nc-743",
"problem_number": 743,
"name": "Network Delay Time",
"pattern": "Advanced Graphs",
"difficulty": "Medium",
"time_complexity": "O(E log V)",
"space_complexity": "O(V + E)",
"starter_code": "class Solution:\n def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:\n pass",
"description": "Given network times, return the minimum time it takes for all n nodes to receive the signal from node k.",
"examples": [
{
"input": "times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2",
"output": "2"
}
],
"constraints": [
"1 <= k <= n <= 100",
"1 <= times.length <= 6000"
],
"leetcode_url": "https://leetcode.com/problems/network-delay-time/",
"reference_solution": "from collections import defaultdict\nimport heapq\n\nclass Solution:\n def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:\n edges = defaultdict(list)\n for u, v, w in times:\n edges[u].append((v, w))\n minHeap = [(0, k)]\n visit = set()\n t = 0\n while minHeap:\n w1, n1 = heapq.heappop(minHeap)\n if n1 in visit: continue\n visit.add(n1)\n t = max(t, w1)\n for n2, w2 in edges[n1]:\n if n2 not in visit:\n heapq.heappush(minHeap, (w1 + w2, n2))\n return t if len(visit) == n else -1"
},
{
"id": "nc-332",
"problem_number": 332,
"name": "Reconstruct Itinerary",
"pattern": "Advanced Graphs",
"difficulty": "Hard",
"time_complexity": "O(E log E)",
"space_complexity": "O(E)",
"starter_code": "class Solution:\n def findItinerary(self, tickets: list[list[str]]) -> list[str]:\n pass",
"description": "Find the itinerary that begins with 'JFK' using all tickets exactly once in lexical order.",
"examples": [
{
"input": "tickets = [[\"MUC\",\"LHR\"],[\"JFK\",\"MUC\"],[\"SFO\",\"SJC\"],[\"LHR\",\"SFO\"]]",
"output": "[\"JFK\",\"MUC\",\"LHR\",\"SFO\",\"SJC\"]"
}
],
"constraints": [
"1 <= tickets.length <= 300"
],
"leetcode_url": "https://leetcode.com/problems/reconstruct-itinerary/",
"reference_solution": "from collections import defaultdict\n\nclass Solution:\n def findItinerary(self, tickets: list[list[str]]) -> list[str]:\n adj = defaultdict(list)\n for src, dst in sorted(tickets, reverse=True):\n adj[src].append(dst)\n res = []\n def dfs(src):\n while adj[src]:\n dfs(adj[src].pop())\n res.append(src)\n dfs(\"JFK\")\n return res[::-1]"
},
{
"id": "nc-1584",
"problem_number": 1584,
"name": "Min Cost to Connect All Points",
"pattern": "Advanced Graphs",
"difficulty": "Medium",
"time_complexity": "O(N^2 log N)",
"space_complexity": "O(N^2)",
"starter_code": "class Solution:\n def minCostConnectPoints(self, points: list[list[int]]) -> int:\n pass",
"description": "Return the minimum cost to make all points connected using Manhattan distance (Prim's or Kruskal's).",
"examples": [
{
"input": "points = [[0,0],[2,2],[3,10],[5,2],[7,0]]",
"output": "20"
}
],
"constraints": [
"1 <= points.length <= 1000"
],
"leetcode_url": "https://leetcode.com/problems/min-cost-to-connect-all-points/",
"reference_solution": "from collections import defaultdict\nimport heapq\n\nclass Solution:\n def minCostConnectPoints(self, points: list[list[int]]) -> int:\n N = len(points)\n adj = defaultdict(list)\n for i in range(N):\n x1, y1 = points[i]\n for j in range(i + 1, N):\n x2, y2 = points[j]\n dist = abs(x1 - x2) + abs(y1 - y2)\n adj[i].append((dist, j))\n adj[j].append((dist, i))\n res = 0\n visit = set()\n minH = [[0, 0]]\n while len(visit) < N:\n cost, i = heapq.heappop(minH)\n if i in visit: continue\n res += cost\n visit.add(i)\n for neiCost, nei in adj[i]:\n if nei not in visit:\n heapq.heappush(minH, [neiCost, nei])\n return res"
},
{
"id": "nc-778",
"problem_number": 778,
"name": "Swim in Rising Water",
"pattern": "Advanced Graphs",
"difficulty": "Hard",
"time_complexity": "O(N^2 log N)",
"space_complexity": "O(N^2)",
"starter_code": "class Solution:\n def swimInWater(self, grid: list[list[int]]) -> int:\n pass",
"description": "Return the minimum time until you can reach the bottom right square from top left square.",
"examples": [
{
"input": "grid = [[0,2],[1,3]]",
"output": "3"
}
],
"constraints": [
"n == grid.length == grid[i].length",
"1 <= n <= 50"
],
"leetcode_url": "https://leetcode.com/problems/swim-in-rising-water/",
"reference_solution": "import heapq\n\nclass Solution:\n def swimInWater(self, grid: list[list[int]]) -> int:\n N = len(grid)\n visit = set()\n minH = [[grid[0][0], 0, 0]]\n directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n visit.add((0, 0))\n while minH:\n t, r, c = heapq.heappop(minH)\n if r == N - 1 and c == N - 1:\n return t\n for dr, dc in directions:\n nr, nc = r + dr, c + dc\n if 0 <= nr < N and 0 <= nc < N and (nr, nc) not in visit:\n visit.add((nr, nc))\n heapq.heappush(minH, [max(t, grid[nr][nc]), nr, nc])"
},
{
"id": "nc-269",
"problem_number": 269,
"name": "Alien Dictionary",
"pattern": "Advanced Graphs",
"difficulty": "Hard",
"time_complexity": "O(C)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def alienOrder(self, words: list[str]) -> str:\n pass",
"description": "Derive the alphabetical order of characters in a foreign language given sorted words.",
"examples": [
{
"input": "words = [\"wrt\",\"wrf\",\"er\",\"ett\",\"rftt\"]",
"output": "\"wertf\""
}
],
"constraints": [
"1 <= words.length <= 100",
"1 <= words[i].length <= 100"
],
"leetcode_url": "https://leetcode.com/problems/alien-dictionary/",
"reference_solution": "class Solution:\n def alienOrder(self, words: list[str]) -> str:\n adj = {c: set() for w in words for c in w}\n for i in range(len(words) - 1):\n w1, w2 = words[i], words[i + 1]\n minLen = min(len(w1), len(w2))\n if len(w1) > len(w2) and w1[:minLen] == w2[:minLen]: return \"\"\n for j in range(minLen):\n if w1[j] != w2[j]:\n adj[w1[j]].add(w2[j])\n break\n visited = {} # False = visited, True = in current path\n res = []\n def dfs(c):\n if c in visited: return visited[c]\n visited[c] = True\n for nei in adj[c]:\n if dfs(nei): return True\n visited[c] = False\n res.append(c)\n for c in adj:\n if dfs(c): return \"\"\n return \"\".join(res[::-1])"
},
{
"id": "nc-787",
"problem_number": 787,
"name": "Cheapest Flights Within K Stops",
"pattern": "Advanced Graphs",
"difficulty": "Medium",
"time_complexity": "O(K * E)",
"space_complexity": "O(V)",
"starter_code": "class Solution:\n def findCheapestPrice(self, n: int, flights: list[list[int]], src: int, dst: int, k: int) -> int:\n pass",
"description": "Find the cheapest price from src to dst with at most k stops (Bellman-Ford).",
"examples": [
{
"input": "n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1",
"output": "700"
}
],
"constraints": [
"1 <= n <= 100",
"0 <= k < n"
],
"leetcode_url": "https://leetcode.com/problems/cheapest-flights-within-k-stops/",
"reference_solution": "class Solution:\n def findCheapestPrice(self, n: int, flights: list[list[int]], src: int, dst: int, k: int) -> int:\n prices = [float(\"inf\")] * n\n prices[src] = 0\n for _ in range(k + 1):\n tmp = prices.copy()\n for s, d, p in flights:\n if prices[s] == float(\"inf\"): continue\n if prices[s] + p < tmp[d]: tmp[d] = prices[s] + p\n prices = tmp\n return -1 if prices[dst] == float(\"inf\") else prices[dst]"
},
{
"id": "nc-70",
"problem_number": 70,
"name": "Climbing Stairs",
"pattern": "1-D DP",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def climbStairs(self, n: int) -> int:\n pass",
"description": "You are climbing a staircase. It takes n steps to reach the top. Each time you can climb 1 or 2 steps. In how many distinct ways can you climb to the top?",
"examples": [
{
"input": "n = 3",
"output": "3"
}
],
"constraints": [
"1 <= n <= 45"
],
"leetcode_url": "https://leetcode.com/problems/climbing-stairs/",
"reference_solution": "class Solution:\n def climbStairs(self, n: int) -> int:\n one, two = 1, 1\n for _ in range(n - 1):\n one, two = one + two, one\n return one"
},
{
"id": "nc-746",
"problem_number": 746,
"name": "Min Cost Climbing Stairs",
"pattern": "1-D DP",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def minCostClimbingStairs(self, cost: list[int]) -> int:\n pass",
"description": "Return the minimum cost to reach the top of the floor after starting from step 0 or 1.",
"examples": [
{
"input": "cost = [10,15,20]",
"output": "15"
}
],
"constraints": [
"2 <= cost.length <= 1000"
],
"leetcode_url": "https://leetcode.com/problems/min-cost-climbing-stairs/",
"reference_solution": "class Solution:\n def minCostClimbingStairs(self, cost: list[int]) -> int:\n cost.append(0)\n for i in range(len(cost) - 3, -1, -1):\n cost[i] += min(cost[i + 1], cost[i + 2])\n return min(cost[0], cost[1])"
},
{
"id": "nc-198",
"problem_number": 198,
"name": "House Robber",
"pattern": "1-D DP",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def rob(self, nums: list[int]) -> int:\n pass",
"description": "Determine the maximum amount of money you can rob tonight without alerting the police (cannot rob adjacent houses).",
"examples": [
{
"input": "nums = [1,2,3,1]",
"output": "4"
}
],
"constraints": [
"1 <= nums.length <= 100",
"0 <= nums[i] <= 400"
],
"leetcode_url": "https://leetcode.com/problems/house-robber/",
"reference_solution": "class Solution:\n def rob(self, nums: list[int]) -> int:\n rob1, rob2 = 0, 0\n for n in nums:\n rob1, rob2 = rob2, max(n + rob1, rob2)\n return rob2"
},
{
"id": "nc-213",
"problem_number": 213,
"name": "House Robber II",
"pattern": "1-D DP",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def rob(self, nums: list[int]) -> int:\n pass",
"description": "All houses at this place are arranged in a circle. Rob the maximum money without triggering the alarm.",
"examples": [
{
"input": "nums = [2,3,2]",
"output": "3"
}
],
"constraints": [
"1 <= nums.length <= 100"
],
"leetcode_url": "https://leetcode.com/problems/house-robber-ii/",
"reference_solution": "class Solution:\n def rob(self, nums: list[int]) -> int:\n def helper(arr):\n r1, r2 = 0, 0\n for n in arr:\n r1, r2 = r2, max(n + r1, r2)\n return r2\n return max(nums[0], helper(nums[1:]), helper(nums[:-1]))"
},
{
"id": "nc-5",
"problem_number": 5,
"name": "Longest Palindromic Substring",
"pattern": "1-D DP",
"difficulty": "Medium",
"time_complexity": "O(N^2)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def longestPalindrome(self, s: str) -> str:\n pass",
"description": "Given a string s, return the longest palindromic substring in s.",
"examples": [
{
"input": "s = \"babad\"",
"output": "\"bab\""
}
],
"constraints": [
"1 <= s.length <= 1000"
],
"leetcode_url": "https://leetcode.com/problems/longest-palindromic-substring/",
"reference_solution": "class Solution:\n def longestPalindrome(self, s: str) -> str:\n res = \"\"\n for i in range(len(s)):\n # odd length\n l, r = i, i\n while l >= 0 and r < len(s) and s[l] == s[r]:\n if (r - l + 1) > len(res): res = s[l:r + 1]\n l -= 1\n r += 1\n # even length\n l, r = i, i + 1\n while l >= 0 and r < len(s) and s[l] == s[r]:\n if (r - l + 1) > len(res): res = s[l:r + 1]\n l -= 1\n r += 1\n return res"
},
{
"id": "nc-647",
"problem_number": 647,
"name": "Palindromic Substrings",
"pattern": "1-D DP",
"difficulty": "Medium",
"time_complexity": "O(N^2)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def countSubstrings(self, s: str) -> int:\n pass",
"description": "Given a string s, return the number of palindromic substrings in it.",
"examples": [
{
"input": "s = \"aaa\"",
"output": "6"
}
],
"constraints": [
"1 <= s.length <= 1000"
],
"leetcode_url": "https://leetcode.com/problems/palindromic-substring/",
"reference_solution": "class Solution:\n def countSubstrings(self, s: str) -> int:\n res = 0\n for i in range(len(s)):\n for l, r in ((i, i), (i, i + 1)):\n while l >= 0 and r < len(s) and s[l] == s[r]:\n res += 1\n l -= 1\n r += 1\n return res"
},
{
"id": "nc-91",
"problem_number": 91,
"name": "Decode Ways",
"pattern": "1-D DP",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def numDecodings(self, s: str) -> int:\n pass",
"description": "Return the number of ways to decode an encoded message containing digits mapping to 'A'-'Z'.",
"examples": [
{
"input": "s = \"226\"",
"output": "3"
}
],
"constraints": [
"1 <= s.length <= 100"
],
"leetcode_url": "https://leetcode.com/problems/decode-ways/",
"reference_solution": "class Solution:\n def numDecodings(self, s: str) -> int:\n dp = {len(s): 1}\n for i in range(len(s) - 1, -1, -1):\n if s[i] == \"0\":\n dp[i] = 0\n else:\n dp[i] = dp[i + 1]\n if i + 1 < len(s) and (s[i] == \"1\" or (s[i] == \"2\" and s[i + 1] in \"0123456\")):\n dp[i] += dp[i + 2]\n return dp[0]"
},
{
"id": "nc-322",
"problem_number": 322,
"name": "Coin Change",
"pattern": "1-D DP",
"difficulty": "Medium",
"time_complexity": "O(amount * len(coins))",
"space_complexity": "O(amount)",
"starter_code": "class Solution:\n def coinChange(self, coins: list[int], amount: int) -> int:\n pass",
"description": "Return the fewest number of coins needed to make up the given amount. If impossible, return -1.",
"examples": [
{
"input": "coins = [1,2,5], amount = 11",
"output": "3"
}
],
"constraints": [
"1 <= coins.length <= 12",
"0 <= amount <= 10^4"
],
"leetcode_url": "https://leetcode.com/problems/coin-change/",
"reference_solution": "class Solution:\n def coinChange(self, coins: list[int], amount: int) -> int:\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n for a in range(1, amount + 1):\n for c in coins:\n if a - c >= 0:\n dp[a] = min(dp[a], 1 + dp[a - c])\n return dp[amount] if dp[amount] != amount + 1 else -1"
},
{
"id": "nc-152",
"problem_number": 152,
"name": "Maximum Product Subarray",
"pattern": "1-D DP",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def maxProduct(self, nums: list[int]) -> int:\n pass",
"description": "Find a contiguous non-empty subarray within a numerical array that has the largest product.",
"examples": [
{
"input": "nums = [2,3,-2,4]",
"output": "6"
}
],
"constraints": [
"1 <= nums.length <= 2 * 10^4"
],
"leetcode_url": "https://leetcode.com/problems/maximum-product-subarray/",
"reference_solution": "class Solution:\n def maxProduct(self, nums: list[int]) -> int:\n res = max(nums)\n curMin, curMax = 1, 1\n for n in nums:\n if n == 0:\n curMin, curMax = 1, 1\n continue\n tmp = curMax * n\n curMax = max(n * curMax, n * curMin, n)\n curMin = min(tmp, n * curMin, n)\n res = max(res, curMax)\n return res"
},
{
"id": "nc-139",
"problem_number": 139,
"name": "Word Break",
"pattern": "1-D DP",
"difficulty": "Medium",
"time_complexity": "O(N * M * K)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def wordBreak(self, s: str, wordDict: list[str]) -> bool:\n pass",
"description": "Return true if s can be segmented into a space-separated sequence of one or more dictionary words.",
"examples": [
{
"input": "s = \"leetcode\", wordDict = [\"leet\",\"code\"]",
"output": "true"
}
],
"constraints": [
"1 <= s.length <= 300"
],
"leetcode_url": "https://leetcode.com/problems/word-break/",
"reference_solution": "class Solution:\n def wordBreak(self, s: str, wordDict: list[str]) -> bool:\n dp = [False] * (len(s) + 1)\n dp[len(s)] = True\n for i in range(len(s) - 1, -1, -1):\n for w in wordDict:\n if (i + len(w)) <= len(s) and s[i:i + len(w)] == w:\n dp[i] = dp[i + len(w)]\n if dp[i]: break\n return dp[0]"
},
{
"id": "nc-300",
"problem_number": 300,
"name": "Longest Increasing Subsequence",
"pattern": "1-D DP",
"difficulty": "Medium",
"time_complexity": "O(N log N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def lengthOfLIS(self, nums: list[int]) -> int:\n pass",
"description": "Given an integer array nums, return the length of the longest strictly increasing subsequence.",
"examples": [
{
"input": "nums = [10,9,2,5,3,7,101,18]",
"output": "4"
}
],
"constraints": [
"1 <= nums.length <= 2500"
],
"leetcode_url": "https://leetcode.com/problems/longest-increasing-subsequence/",
"reference_solution": "import bisect\n\nclass Solution:\n def lengthOfLIS(self, nums: list[int]) -> int:\n sub = []\n for x in nums:\n idx = bisect.bisect_left(sub, x)\n if idx == len(sub): sub.append(x)\n else: sub[idx] = x\n return len(sub)"
},
{
"id": "nc-416",
"problem_number": 416,
"name": "Partition Equal Subset Sum",
"pattern": "1-D DP",
"difficulty": "Medium",
"time_complexity": "O(N * sum)",
"space_complexity": "O(sum)",
"starter_code": "class Solution:\n def canPartition(self, nums: list[int]) -> bool:\n pass",
"description": "Determine if nums can be partitioned into two subsets such that the sum of elements in both subsets is equal.",
"examples": [
{
"input": "nums = [1,5,11,5]",
"output": "true"
}
],
"constraints": [
"1 <= nums.length <= 200",
"1 <= nums[i] <= 100"
],
"leetcode_url": "https://leetcode.com/problems/partition-equal-subset-sum/",
"reference_solution": "class Solution:\n def canPartition(self, nums: list[int]) -> bool:\n total = sum(nums)\n if total % 2 != 0: return False\n target = total // 2\n dp = {0}\n for n in nums:\n nextDp = set()\n for t in dp:\n if t + n == target: return True\n nextDp.add(t + n)\n nextDp.add(t)\n dp = nextDp\n return target in dp"
},
{
"id": "nc-62",
"problem_number": 62,
"name": "Unique Paths",
"pattern": "2-D DP",
"difficulty": "Medium",
"time_complexity": "O(M * N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n pass",
"description": "A robot is located at the top-left corner of a m x n grid. How many possible unique paths are there to the bottom-right corner?",
"examples": [
{
"input": "m = 3, n = 7",
"output": "28"
}
],
"constraints": [
"1 <= m, n <= 100"
],
"leetcode_url": "https://leetcode.com/problems/unique-paths/",
"reference_solution": "class Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n row = [1] * n\n for _ in range(m - 1):\n newRow = [1] * n\n for j in range(n - 2, -1, -1):\n newRow[j] = newRow[j + 1] + row[j]\n row = newRow\n return row[0]"
},
{
"id": "nc-1143",
"problem_number": 1143,
"name": "Longest Common Subsequence",
"pattern": "2-D DP",
"difficulty": "Medium",
"time_complexity": "O(M * N)",
"space_complexity": "O(M * N)",
"starter_code": "class Solution:\n def longestCommonSubsequence(self, text1: str, text2: str) -> int:\n pass",
"description": "Given two strings text1 and text2, return the length of their longest common subsequence.",
"examples": [
{
"input": "text1 = \"abcde\", text2 = \"ace\"",
"output": "3"
}
],
"constraints": [
"1 <= text1.length, text2.length <= 1000"
],
"leetcode_url": "https://leetcode.com/problems/longest-common-subsequence/",
"reference_solution": "class Solution:\n def longestCommonSubsequence(self, text1: str, text2: str) -> int:\n dp = [[0 for _ in range(len(text2) + 1)] for _ in range(len(text1) + 1)]\n for i in range(len(text1) - 1, -1, -1):\n for j in range(len(text2) - 1, -1, -1):\n if text1[i] == text2[j]:\n dp[i][j] = 1 + dp[i + 1][j + 1]\n else:\n dp[i][j] = max(dp[i + 1][j], dp[i][j + 1])\n return dp[0][0]"
},
{
"id": "nc-309",
"problem_number": 309,
"name": "Best Time to Buy and Sell Stock with Cooldown",
"pattern": "2-D DP",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def maxProfit(self, prices: list[int]) -> int:\n pass",
"description": "Find the maximum profit you can achieve with stock trading with a 1-day cooldown after selling.",
"examples": [
{
"input": "prices = [1,2,3,0,2]",
"output": "3"
}
],
"constraints": [
"1 <= prices.length <= 5000"
],
"leetcode_url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/",
"reference_solution": "class Solution:\n def maxProfit(self, prices: list[int]) -> int:\n dp = {}\n def dfs(i, buying):\n if i >= len(prices): return 0\n if (i, buying) in dp: return dp[(i, buying)]\n cooldown = dfs(i + 1, buying)\n if buying:\n buy = dfs(i + 1, not buying) - prices[i]\n dp[(i, buying)] = max(buy, cooldown)\n else:\n sell = dfs(i + 2, not buying) + prices[i]\n dp[(i, buying)] = max(sell, cooldown)\n return dp[(i, buying)]\n return dfs(0, True)"
},
{
"id": "nc-518",
"problem_number": 518,
"name": "Coin Change II",
"pattern": "2-D DP",
"difficulty": "Medium",
"time_complexity": "O(N * amount)",
"space_complexity": "O(amount)",
"starter_code": "class Solution:\n def change(self, amount: int, coins: list[int]) -> int:\n pass",
"description": "Return the number of combinations that make up the given amount using infinite coins of each denomination.",
"examples": [
{
"input": "amount = 5, coins = [1,2,5]",
"output": "4"
}
],
"constraints": [
"1 <= coins.length <= 300",
"0 <= amount <= 5000"
],
"leetcode_url": "https://leetcode.com/problems/coin-change-ii/",
"reference_solution": "class Solution:\n def change(self, amount: int, coins: list[int]) -> int:\n dp = [0] * (amount + 1)\n dp[0] = 1\n for c in coins:\n for a in range(c, amount + 1):\n dp[a] += dp[a - c]\n return dp[amount]"
},
{
"id": "nc-494",
"problem_number": 494,
"name": "Target Sum",
"pattern": "2-D DP",
"difficulty": "Medium",
"time_complexity": "O(N * total)",
"space_complexity": "O(total)",
"starter_code": "class Solution:\n def findTargetSumWays(self, nums: list[int], target: int) -> int:\n pass",
"description": "Assign '+' or '-' before each integer in nums so that the resulting expression evaluates to target.",
"examples": [
{
"input": "nums = [1,1,1,1,1], target = 3",
"output": "5"
}
],
"constraints": [
"1 <= nums.length <= 20",
"0 <= sum(nums[i]) <= 1000"
],
"leetcode_url": "https://leetcode.com/problems/target-sum/",
"reference_solution": "from collections import defaultdict\n\nclass Solution:\n def findTargetSumWays(self, nums: list[int], target: int) -> int:\n dp = defaultdict(int)\n dp[0] = 1\n for n in nums:\n nextDp = defaultdict(int)\n for cur, count in dp.items():\n nextDp[cur + n] += count\n nextDp[cur - n] += count\n dp = nextDp\n return dp[target]"
},
{
"id": "nc-97",
"problem_number": 97,
"name": "Interleaving String",
"pattern": "2-D DP",
"difficulty": "Medium",
"time_complexity": "O(M * N)",
"space_complexity": "O(M * N)",
"starter_code": "class Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n pass",
"description": "Given s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2.",
"examples": [
{
"input": "s1 = \"aabcc\", s2 = \"dbbca\", s3 = \"aadbbcbcac\"",
"output": "true"
}
],
"constraints": [
"0 <= s1.length, s2.length <= 100",
"0 <= s3.length <= 200"
],
"leetcode_url": "https://leetcode.com/problems/interleaving-string/",
"reference_solution": "class Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n if len(s1) + len(s2) != len(s3): return False\n dp = [[False] * (len(s2) + 1) for _ in range(len(s1) + 1)]\n dp[len(s1)][len(s2)] = True\n for i in range(len(s1), -1, -1):\n for j in range(len(s2), -1, -1):\n if i < len(s1) and s1[i] == s3[i + j] and dp[i + 1][j]:\n dp[i][j] = True\n if j < len(s2) and s2[j] == s3[i + j] and dp[i][j + 1]:\n dp[i][j] = True\n return dp[0][0]"
},
{
"id": "nc-329",
"problem_number": 329,
"name": "Longest Increasing Path in a Matrix",
"pattern": "2-D DP",
"difficulty": "Hard",
"time_complexity": "O(M * N)",
"space_complexity": "O(M * N)",
"starter_code": "class Solution:\n def longestIncreasingPath(self, matrix: list[list[int]]) -> int:\n pass",
"description": "Given an m x n integers matrix, return the length of the longest increasing path.",
"examples": [
{
"input": "matrix = [[9,9,4],[6,6,8],[2,1,1]]",
"output": "4"
}
],
"constraints": [
"m == matrix.length",
"n == matrix[i].length",
"1 <= m, n <= 200"
],
"leetcode_url": "https://leetcode.com/problems/longest-increasing-path-in-a-matrix/",
"reference_solution": "class Solution:\n def longestIncreasingPath(self, matrix: list[list[int]]) -> int:\n ROWS, COLS = len(matrix), len(matrix[0])\n dp = {}\n def dfs(r, c, prevVal):\n if r < 0 or r == ROWS or c < 0 or c == COLS or matrix[r][c] <= prevVal:\n return 0\n if (r, c) in dp: return dp[(r, c)]\n res = 1\n for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:\n res = max(res, 1 + dfs(r + dr, c + dc, matrix[r][c]))\n dp[(r, c)] = res\n return res\n for r in range(ROWS):\n for c in range(COLS): dfs(r, c, -1)\n return max(dp.values())"
},
{
"id": "nc-115",
"problem_number": 115,
"name": "Distinct Subsequences",
"pattern": "2-D DP",
"difficulty": "Hard",
"time_complexity": "O(M * N)",
"space_complexity": "O(M * N)",
"starter_code": "class Solution:\n def numDistinct(self, s: str, t: str) -> int:\n pass",
"description": "Given two strings s and t, return the number of distinct subsequences of s which equals t.",
"examples": [
{
"input": "s = \"rabbbit\", t = \"rabbit\"",
"output": "3"
}
],
"constraints": [
"1 <= s.length, t.length <= 1000"
],
"leetcode_url": "https://leetcode.com/problems/distinct-subsequences/",
"reference_solution": "class Solution:\n def numDistinct(self, s: str, t: str) -> int:\n cache = {}\n def dfs(i, j):\n if j == len(t): return 1\n if i == len(s): return 0\n if (i, j) in cache: return cache[(i, j)]\n if s[i] == t[j]:\n cache[(i, j)] = dfs(i + 1, j + 1) + dfs(i + 1, j)\n else:\n cache[(i, j)] = dfs(i + 1, j)\n return cache[(i, j)]\n return dfs(0, 0)"
},
{
"id": "nc-72",
"problem_number": 72,
"name": "Edit Distance",
"pattern": "2-D DP",
"difficulty": "Medium",
"time_complexity": "O(M * N)",
"space_complexity": "O(M * N)",
"starter_code": "class Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n pass",
"description": "Return minimum operations to convert word1 to word2 (insert, delete, or replace a character).",
"examples": [
{
"input": "word1 = \"horse\", word2 = \"ros\"",
"output": "3"
}
],
"constraints": [
"0 <= word1.length, word2.length <= 500"
],
"leetcode_url": "https://leetcode.com/problems/edit-distance/",
"reference_solution": "class Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n dp = [[float(\"inf\")] * (len(word2) + 1) for _ in range(len(word1) + 1)]\n for j in range(len(word2) + 1): dp[len(word1)][j] = len(word2) - j\n for i in range(len(word1) + 1): dp[i][len(word2)] = len(word1) - i\n for i in range(len(word1) - 1, -1, -1):\n for j in range(len(word2) - 1, -1, -1):\n if word1[i] == word2[j]:\n dp[i][j] = dp[i + 1][j + 1]\n else:\n dp[i][j] = 1 + min(dp[i + 1][j], dp[i][j + 1], dp[i + 1][j + 1])\n return dp[0][0]"
},
{
"id": "nc-312",
"problem_number": 312,
"name": "Burst Balloons",
"pattern": "2-D DP",
"difficulty": "Hard",
"time_complexity": "O(N^3)",
"space_complexity": "O(N^2)",
"starter_code": "class Solution:\n def maxCoins(self, nums: list[int]) -> int:\n pass",
"description": "Burst balloon i to get nums[i - 1] * nums[i] * nums[i + 1] coins. Return the maximum coins you can collect.",
"examples": [
{
"input": "nums = [3,1,5,8]",
"output": "167"
}
],
"constraints": [
"n == nums.length",
"1 <= n <= 300"
],
"leetcode_url": "https://leetcode.com/problems/burst-balloons/",
"reference_solution": "class Solution:\n def maxCoins(self, nums: list[int]) -> int:\n nums = [1] + [n for n in nums if n > 0] + [1]\n n = len(nums)\n dp = [[0] * n for _ in range(n)]\n for length in range(1, n - 1):\n for left in range(0, n - length - 1):\n right = left + length + 1\n for i in range(left + 1, right):\n dp[left][right] = max(dp[left][right], nums[left] * nums[i] * nums[right] + dp[left][i] + dp[i][right])\n return dp[0][n - 1]"
},
{
"id": "nc-10",
"problem_number": 10,
"name": "Regular Expression Matching",
"pattern": "2-D DP",
"difficulty": "Hard",
"time_complexity": "O(M * N)",
"space_complexity": "O(M * N)",
"starter_code": "class Solution:\n def isMatch(self, s: str, p: str) -> bool:\n pass",
"description": "Implement regular expression matching with support for '.' and '*'.",
"examples": [
{
"input": "s = \"aa\", p = \"a*\"",
"output": "true"
}
],
"constraints": [
"1 <= s.length <= 20",
"1 <= p.length <= 20"
],
"leetcode_url": "https://leetcode.com/problems/regular-expression-matching/",
"reference_solution": "class Solution:\n def isMatch(self, s: str, p: str) -> bool:\n cache = {}\n def dfs(i, j):\n if (i, j) in cache: return cache[(i, j)]\n if i >= len(s) and j >= len(p): return True\n if j >= len(p): return False\n match = i < len(s) and (s[i] == p[j] or p[j] == \".\")\n if (j + 1) < len(p) and p[j + 1] == \"*\":\n cache[(i, j)] = dfs(i, j + 2) or (match and dfs(i + 1, j))\n return cache[(i, j)]\n if match:\n cache[(i, j)] = dfs(i + 1, j + 1)\n return cache[(i, j)]\n cache[(i, j)] = False\n return False\n return dfs(0, 0)"
},
{
"id": "nc-53",
"problem_number": 53,
"name": "Maximum Subarray",
"pattern": "Greedy",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def maxSubArray(self, nums: list[int]) -> int:\n pass",
"description": "Given an integer array nums, find the subarray with the largest sum, and return its sum (Kadane's Algorithm).",
"examples": [
{
"input": "nums = [-2,1,-3,4,-1,2,1,-5,4]",
"output": "6"
}
],
"constraints": [
"1 <= nums.length <= 10^5"
],
"leetcode_url": "https://leetcode.com/problems/maximum-subarray/",
"reference_solution": "class Solution:\n def maxSubArray(self, nums: list[int]) -> int:\n maxSub = nums[0]\n curSum = 0\n for n in nums:\n if curSum < 0: curSum = 0\n curSum += n\n maxSub = max(maxSub, curSum)\n return maxSub"
},
{
"id": "nc-55",
"problem_number": 55,
"name": "Jump Game",
"pattern": "Greedy",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def canJump(self, nums: list[int]) -> bool:\n pass",
"description": "Determine if you are able to reach the last index starting at index 0.",
"examples": [
{
"input": "nums = [2,3,1,1,4]",
"output": "true"
}
],
"constraints": [
"1 <= nums.length <= 10^4"
],
"leetcode_url": "https://leetcode.com/problems/jump-game/",
"reference_solution": "class Solution:\n def canJump(self, nums: list[int]) -> bool:\n goal = len(nums) - 1\n for i in range(len(nums) - 2, -1, -1):\n if i + nums[i] >= goal: goal = i\n return goal == 0"
},
{
"id": "nc-45",
"problem_number": 45,
"name": "Jump Game II",
"pattern": "Greedy",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def jump(self, nums: list[int]) -> int:\n pass",
"description": "Return the minimum number of jumps to reach the last index.",
"examples": [
{
"input": "nums = [2,3,1,1,4]",
"output": "2"
}
],
"constraints": [
"1 <= nums.length <= 10^4"
],
"leetcode_url": "https://leetcode.com/problems/jump-game-ii/",
"reference_solution": "class Solution:\n def jump(self, nums: list[int]) -> int:\n res = 0\n l = r = 0\n while r < len(nums) - 1:\n farthest = 0\n for i in range(l, r + 1):\n farthest = max(farthest, i + nums[i])\n l = r + 1\n r = farthest\n res += 1\n return res"
},
{
"id": "nc-134",
"problem_number": 134,
"name": "Gas Station",
"pattern": "Greedy",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def canCompleteCircuit(self, gas: list[int], cost: list[int]) -> int:\n pass",
"description": "Return the starting gas station's index if you can travel around the circuit once, or -1 otherwise.",
"examples": [
{
"input": "gas = [1,2,3,4,5], cost = [3,4,5,1,2]",
"output": "3"
}
],
"constraints": [
"n == gas.length == cost.length",
"1 <= n <= 10^5"
],
"leetcode_url": "https://leetcode.com/problems/gas-station/",
"reference_solution": "class Solution:\n def canCompleteCircuit(self, gas: list[int], cost: list[int]) -> int:\n if sum(gas) < sum(cost): return -1\n total = 0\n res = 0\n for i in range(len(gas)):\n total += (gas[i] - cost[i])\n if total < 0:\n total = 0\n res = i + 1\n return res"
},
{
"id": "nc-846",
"problem_number": 846,
"name": "Hand of Straights",
"pattern": "Greedy",
"difficulty": "Medium",
"time_complexity": "O(N log N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def isNStraightHand(self, hand: list[int], groupSize: int) -> bool:\n pass",
"description": "Determine if Alice can rearrange hand into groups of groupSize consecutive cards.",
"examples": [
{
"input": "hand = [1,2,3,6,2,3,4,7,8], groupSize = 3",
"output": "true"
}
],
"constraints": [
"1 <= hand.length <= 10^4",
"1 <= groupSize <= hand.length"
],
"leetcode_url": "https://leetcode.com/problems/hand-of-straights/",
"reference_solution": "from collections import Counter\nimport heapq\n\nclass Solution:\n def isNStraightHand(self, hand: list[int], groupSize: int) -> bool:\n if len(hand) % groupSize != 0: return False\n count = Counter(hand)\n minH = list(count.keys())\n heapq.heapify(minH)\n while minH:\n first = minH[0]\n for i in range(first, first + groupSize):\n if i not in count: return False\n count[i] -= 1\n if count[i] == 0:\n if i != minH[0]: return False\n heapq.heappop(minH)\n return True"
},
{
"id": "nc-1899",
"problem_number": 1899,
"name": "Merge Triplets to Form Target Triplet",
"pattern": "Greedy",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def mergeTriplets(self, triplets: list[list[int]], target: list[int]) -> bool:\n pass",
"description": "Return true if you can obtain target by merging triplets using component-wise maximum.",
"examples": [
{
"input": "triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]",
"output": "true"
}
],
"constraints": [
"1 <= triplets.length <= 10^5"
],
"leetcode_url": "https://leetcode.com/problems/merge-triplets-to-form-target-triplet/",
"reference_solution": "class Solution:\n def mergeTriplets(self, triplets: list[list[int]], target: list[int]) -> bool:\n good = set()\n for t in triplets:\n if t[0] > target[0] or t[1] > target[1] or t[2] > target[2]: continue\n for i, v in enumerate(t):\n if v == target[i]: good.add(i)\n return len(good) == 3"
},
{
"id": "nc-763",
"problem_number": 763,
"name": "Partition Labels",
"pattern": "Greedy",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def partitionLabels(self, s: str) -> list[int]:\n pass",
"description": "Partition s into as many parts as possible so that each letter appears in at most one part.",
"examples": [
{
"input": "s = \"ababcbacadefegdehijhklij\"",
"output": "[9,7,8]"
}
],
"constraints": [
"1 <= s.length <= 500"
],
"leetcode_url": "https://leetcode.com/problems/partition-labels/",
"reference_solution": "class Solution:\n def partitionLabels(self, s: str) -> list[int]:\n lastIndex = {c: i for i, c in enumerate(s)}\n res = []\n size, end = 0, 0\n for i, c in enumerate(s):\n size += 1\n end = max(end, lastIndex[c])\n if i == end:\n res.append(size)\n size = 0\n return res"
},
{
"id": "nc-678",
"problem_number": 678,
"name": "Valid Parenthesis String",
"pattern": "Greedy",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def checkValidString(self, s: str) -> bool:\n pass",
"description": "Given a string s containing '(', ')' and '*', return true if s is valid (where '*' can be '(', ')' or empty).",
"examples": [
{
"input": "s = \"(*))\"",
"output": "true"
}
],
"constraints": [
"1 <= s.length <= 100"
],
"leetcode_url": "https://leetcode.com/problems/valid-parenthesis-string/",
"reference_solution": "class Solution:\n def checkValidString(self, s: str) -> bool:\n leftMin, leftMax = 0, 0\n for c in s:\n if c == \"(\":\n leftMin, leftMax = leftMin + 1, leftMax + 1\n elif c == \")\":\n leftMin, leftMax = leftMin - 1, leftMax - 1\n else:\n leftMin, leftMax = leftMin - 1, leftMax + 1\n if leftMax < 0: return False\n if leftMin < 0: leftMin = 0\n return leftMin == 0"
},
{
"id": "nc-57",
"problem_number": 57,
"name": "Insert Interval",
"pattern": "Intervals",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n pass",
"description": "Insert newInterval into intervals (sorted by start) and merge overlapping intervals.",
"examples": [
{
"input": "intervals = [[1,3],[6,9]], newInterval = [2,5]",
"output": "[[1,5],[6,9]]"
}
],
"constraints": [
"0 <= intervals.length <= 10^4"
],
"leetcode_url": "https://leetcode.com/problems/insert-interval/",
"reference_solution": "class Solution:\n def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n res = []\n for i in range(len(intervals)):\n if newInterval[1] < intervals[i][0]:\n res.append(newInterval)\n return res + intervals[i:]\n elif newInterval[0] > intervals[i][1]:\n res.append(intervals[i])\n else:\n newInterval = [min(newInterval[0], intervals[i][0]), max(newInterval[1], intervals[i][1])]\n res.append(newInterval)\n return res"
},
{
"id": "nc-56",
"problem_number": 56,
"name": "Merge Intervals",
"pattern": "Intervals",
"difficulty": "Medium",
"time_complexity": "O(N log N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def merge(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:\n pass",
"description": "Merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals.",
"examples": [
{
"input": "intervals = [[1,3],[2,6],[8,10],[15,18]]",
"output": "[[1,6],[8,10],[15,18]]"
}
],
"constraints": [
"1 <= intervals.length <= 10^4"
],
"leetcode_url": "https://leetcode.com/problems/merge-intervals/",
"reference_solution": "class Solution:\n def merge(self, intervals: list[list[int]]) -> list[list[int]]:\n intervals.sort(key=lambda i: i[0])\n output = [intervals[0]]\n for start, end in intervals[1:]:\n lastEnd = output[-1][1]\n if start <= lastEnd:\n output[-1][1] = max(lastEnd, end)\n else:\n output.append([start, end])\n return output"
},
{
"id": "nc-435",
"problem_number": 435,
"name": "Non-overlapping Intervals",
"pattern": "Intervals",
"difficulty": "Medium",
"time_complexity": "O(N log N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def eraseOverlapIntervals(self, intervals: list[list[int]]) -> int:\n pass",
"description": "Return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.",
"examples": [
{
"input": "intervals = [[1,2],[2,3],[3,4],[1,3]]",
"output": "1"
}
],
"constraints": [
"1 <= intervals.length <= 10^5"
],
"leetcode_url": "https://leetcode.com/problems/non-overlapping-intervals/",
"reference_solution": "class Solution:\n def eraseOverlapIntervals(self, intervals: list[list[int]]) -> int:\n intervals.sort()\n res = 0\n prevEnd = intervals[0][1]\n for start, end in intervals[1:]:\n if start >= prevEnd:\n prevEnd = end\n else:\n res += 1\n prevEnd = min(end, prevEnd)\n return res"
},
{
"id": "nc-252",
"problem_number": 252,
"name": "Meeting Rooms",
"pattern": "Intervals",
"difficulty": "Easy",
"time_complexity": "O(N log N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def canAttendMeetings(self, intervals: list[list[int]]) -> bool:\n pass",
"description": "Given an array of meeting time intervals, determine if a person could attend all meetings.",
"examples": [
{
"input": "intervals = [[0,30],[5,10],[15,20]]",
"output": "false"
}
],
"constraints": [
"0 <= intervals.length <= 10^4"
],
"leetcode_url": "https://leetcode.com/problems/meeting-rooms/",
"reference_solution": "class Solution:\n def canAttendMeetings(self, intervals: list[list[int]]) -> bool:\n intervals.sort(key=lambda i: i[0])\n for i in range(1, len(intervals)):\n if intervals[i][0] < intervals[i - 1][1]: return False\n return True"
},
{
"id": "nc-253",
"problem_number": 253,
"name": "Meeting Rooms II",
"pattern": "Intervals",
"difficulty": "Medium",
"time_complexity": "O(N log N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def minMeetingRooms(self, intervals: list[list[int]]) -> int:\n pass",
"description": "Given an array of meeting time intervals, find the minimum number of conference rooms required.",
"examples": [
{
"input": "intervals = [[0,30],[5,10],[15,20]]",
"output": "2"
}
],
"constraints": [
"1 <= intervals.length <= 10^4"
],
"leetcode_url": "https://leetcode.com/problems/meeting-rooms-ii/",
"reference_solution": "class Solution:\n def minMeetingRooms(self, intervals: list[list[int]]) -> int:\n start = sorted([i[0] for i in intervals])\n end = sorted([i[1] for i in intervals])\n res, count = 0, 0\n s, e = 0, 0\n while s < len(intervals):\n if start[s] < end[e]:\n count += 1\n s += 1\n else:\n count -= 1\n e += 1\n res = max(res, count)\n return res"
},
{
"id": "nc-1851",
"problem_number": 1851,
"name": "Minimum Interval to Include Each Query",
"pattern": "Intervals",
"difficulty": "Hard",
"time_complexity": "O(N log N + Q log Q)",
"space_complexity": "O(N + Q)",
"starter_code": "class Solution:\n def minInterval(self, intervals: list[list[int]], queries: list[int]) -> list[int]:\n pass",
"description": "For each query, find the size of the smallest interval that contains that query value.",
"examples": [
{
"input": "intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]",
"output": "[3,3,1,4]"
}
],
"constraints": [
"1 <= intervals.length <= 10^5",
"1 <= queries.length <= 10^5"
],
"leetcode_url": "https://leetcode.com/problems/minimum-interval-to-include-each-query/",
"reference_solution": "import heapq\n\nclass Solution:\n def minInterval(self, intervals: list[list[int]], queries: list[int]) -> list[int]:\n intervals.sort()\n minHeap = []\n res = {}\n i = 0\n for q in sorted(queries):\n while i < len(intervals) and intervals[i][0] <= q:\n l, r = intervals[i]\n heapq.heappush(minHeap, (r - l + 1, r))\n i += 1\n while minHeap and minHeap[0][1] < q:\n heapq.heappop(minHeap)\n res[q] = minHeap[0][0] if minHeap else -1\n return [res[q] for q in queries]"
},
{
"id": "nc-48",
"problem_number": 48,
"name": "Rotate Image",
"pattern": "Math & Geometry",
"difficulty": "Medium",
"time_complexity": "O(N^2)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def rotate(self, matrix: list[list[int]]) -> None:\n pass",
"description": "Rotate the n x n 2D matrix clockwise by 90 degrees in-place.",
"examples": [
{
"input": "matrix = [[1,2,3],[4,5,6],[7,8,9]]",
"output": "[[7,4,1],[8,5,2],[9,6,3]]"
}
],
"constraints": [
"n == matrix.length == matrix[i].length",
"1 <= n <= 20"
],
"leetcode_url": "https://leetcode.com/problems/rotate-image/",
"reference_solution": "class Solution:\n def rotate(self, matrix: list[list[int]]) -> None:\n l, r = 0, len(matrix) - 1\n while l < r:\n for i in range(r - l):\n top, bottom = l, r\n topLeft = matrix[top][l + i]\n matrix[top][l + i] = matrix[bottom - i][l]\n matrix[bottom - i][l] = matrix[bottom][r - i]\n matrix[bottom][r - i] = matrix[top + i][r]\n matrix[top + i][r] = topLeft\n r -= 1\n l += 1"
},
{
"id": "nc-54",
"problem_number": 54,
"name": "Spiral Matrix",
"pattern": "Math & Geometry",
"difficulty": "Medium",
"time_complexity": "O(M * N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def spiralOrder(self, matrix: list[list[int]]) -> list[int]:\n pass",
"description": "Return all elements of the m x n matrix in spiral order.",
"examples": [
{
"input": "matrix = [[1,2,3],[4,5,6],[7,8,9]]",
"output": "[1,2,3,6,9,8,7,4,5]"
}
],
"constraints": [
"m == matrix.length",
"n == matrix[i].length",
"1 <= m, n <= 10"
],
"leetcode_url": "https://leetcode.com/problems/spiral-matrix/",
"reference_solution": "class Solution:\n def spiralOrder(self, matrix: list[list[int]]) -> list[int]:\n res = []\n left, right = 0, len(matrix[0])\n top, bottom = 0, len(matrix)\n while left < right and top < bottom:\n for i in range(left, right): res.append(matrix[top][i])\n top += 1\n for i in range(top, bottom): res.append(matrix[i][right - 1])\n right -= 1\n if not (left < right and top < bottom): break\n for i in range(right - 1, left - 1, -1): res.append(matrix[bottom - 1][i])\n bottom -= 1\n for i in range(bottom - 1, top - 1, -1): res.append(matrix[i][left])\n left += 1\n return res"
},
{
"id": "nc-73",
"problem_number": 73,
"name": "Set Matrix Zeroes",
"pattern": "Math & Geometry",
"difficulty": "Medium",
"time_complexity": "O(M * N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def setZeroes(self, matrix: list[list[int]]) -> None:\n pass",
"description": "Given an m x n integer matrix, if an element is 0, set its entire row and column to 0's in place.",
"examples": [
{
"input": "matrix = [[1,1,1],[1,0,1],[1,1,1]]",
"output": "[[1,0,1],[0,0,0],[1,0,1]]"
}
],
"constraints": [
"m == matrix.length",
"n == matrix[0].length",
"1 <= m, n <= 200"
],
"leetcode_url": "https://leetcode.com/problems/set-matrix-zeroes/",
"reference_solution": "class Solution:\n def setZeroes(self, matrix: list[list[int]]) -> None:\n ROWS, COLS = len(matrix), len(matrix[0])\n rowZero = False\n for r in range(ROWS):\n for c in range(COLS):\n if matrix[r][c] == 0:\n matrix[0][c] = 0\n if r > 0: matrix[r][0] = 0\n else: rowZero = True\n for r in range(1, ROWS):\n for c in range(1, COLS):\n if matrix[0][c] == 0 or matrix[r][0] == 0:\n matrix[r][c] = 0\n if matrix[0][0] == 0:\n for r in range(ROWS): matrix[r][0] = 0\n if rowZero:\n for c in range(COLS): matrix[0][c] = 0"
},
{
"id": "nc-202",
"problem_number": 202,
"name": "Happy Number",
"pattern": "Math & Geometry",
"difficulty": "Easy",
"time_complexity": "O(log N)",
"space_complexity": "O(log N)",
"starter_code": "class Solution:\n def isHappy(self, n: int) -> bool:\n pass",
"description": "Determine if a number n is happy by continually replacing it with the sum of the squares of its digits.",
"examples": [
{
"input": "n = 19",
"output": "true"
}
],
"constraints": [
"1 <= n <= 2^31 - 1"
],
"leetcode_url": "https://leetcode.com/problems/happy-number/",
"reference_solution": "class Solution:\n def isHappy(self, n: int) -> bool:\n visit = set()\n while n not in visit:\n visit.add(n)\n n = sum(int(digit) ** 2 for digit in str(n))\n if n == 1: return True\n return False"
},
{
"id": "nc-66",
"problem_number": 66,
"name": "Plus One",
"pattern": "Math & Geometry",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def plusOne(self, digits: list[int]) -> list[int]:\n pass",
"description": "Increment the large integer represented by an array of digits by one.",
"examples": [
{
"input": "digits = [1,2,3]",
"output": "[1,2,4]"
}
],
"constraints": [
"1 <= digits.length <= 100"
],
"leetcode_url": "https://leetcode.com/problems/plus-one/",
"reference_solution": "class Solution:\n def plusOne(self, digits: list[int]) -> list[int]:\n for i in reversed(range(len(digits))):\n if digits[i] == 9: digits[i] = 0\n else:\n digits[i] += 1\n return digits\n return [1] + digits"
},
{
"id": "nc-50",
"problem_number": 50,
"name": "Pow(x, n)",
"pattern": "Math & Geometry",
"difficulty": "Medium",
"time_complexity": "O(log N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def myPow(self, x: float, n: int) -> float:\n pass",
"description": "Implement pow(x, n), which calculates x raised to the power n.",
"examples": [
{
"input": "x = 2.00000, n = 10",
"output": "1024.00000"
}
],
"constraints": [
"-100.0 < x < 100.0",
"-2^31 <= n <= 2^31-1"
],
"leetcode_url": "https://leetcode.com/problems/powx-n/",
"reference_solution": "class Solution:\n def myPow(self, x: float, n: int) -> float:\n def helper(x, n):\n if x == 0: return 0\n if n == 0: return 1\n res = helper(x * x, n // 2)\n return x * res if n % 2 else res\n res = helper(x, abs(n))\n return res if n >= 0 else 1 / res"
},
{
"id": "nc-43",
"problem_number": 43,
"name": "Multiply Strings",
"pattern": "Math & Geometry",
"difficulty": "Medium",
"time_complexity": "O(M * N)",
"space_complexity": "O(M + N)",
"starter_code": "class Solution:\n def multiply(self, num1: str, num2: str) -> str:\n pass",
"description": "Given two non-negative integers num1 and num2 represented as strings, return their product as a string.",
"examples": [
{
"input": "num1 = \"2\", num2 = \"3\"",
"output": "\"6\""
}
],
"constraints": [
"1 <= num1.length, num2.length <= 200"
],
"leetcode_url": "https://leetcode.com/problems/multiply-strings/",
"reference_solution": "class Solution:\n def multiply(self, num1: str, num2: str) -> str:\n if \"0\" in [num1, num2]: return \"0\"\n res = [0] * (len(num1) + len(num2))\n num1, num2 = num1[::-1], num2[::-1]\n for i1 in range(len(num1)):\n for i2 in range(len(num2)):\n digit = int(num1[i1]) * int(num2[i2])\n res[i1 + i2] += digit\n res[i1 + i2 + 1] += res[i1 + i2] // 10\n res[i1 + i2] = res[i1 + i2] % 10\n res, beg = res[::-1], 0\n while beg < len(res) and res[beg] == 0: beg += 1\n return \"\".join(map(str, res[beg:]))"
},
{
"id": "nc-2013",
"problem_number": 2013,
"name": "Detect Squares",
"pattern": "Math & Geometry",
"difficulty": "Medium",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class DetectSquares:\n def __init__(self):\n pass\n def add(self, point: list[int]) -> None:\n pass\n def count(self, point: list[int]) -> int:\n pass",
"description": "Design a data structure that adds points and counts axis-aligned squares with a given query point.",
"examples": [
{
"input": "[\"DetectSquares\",\"add\",\"add\",\"add\",\"count\",\"count\",\"add\",\"count\"]",
"output": "[null,null,null,null,1,0,null,2]"
}
],
"constraints": [
"point.length == 2",
"0 <= x, y <= 1000"
],
"leetcode_url": "https://leetcode.com/problems/detect-squares/",
"reference_solution": "from collections import defaultdict\n\nclass DetectSquares:\n def __init__(self):\n self.ptsCount = defaultdict(int)\n self.pts = []\n def add(self, point: list[int]) -> None:\n self.ptsCount[tuple(point)] += 1\n self.pts.append(point)\n def count(self, point: list[int]) -> int:\n res = 0\n px, py = point\n for x, y in self.pts:\n if (abs(py - y) != abs(px - x)) or x == px or y == py: continue\n res += self.ptsCount[(x, py)] * self.ptsCount[(px, y)]\n return res"
},
{
"id": "nc-136",
"problem_number": 136,
"name": "Single Number",
"pattern": "Bit Manipulation",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def singleNumber(self, nums: list[int]) -> int:\n pass",
"description": "Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.",
"examples": [
{
"input": "nums = [2,2,1]",
"output": "1"
}
],
"constraints": [
"1 <= nums.length <= 3 * 10^4"
],
"leetcode_url": "https://leetcode.com/problems/single-number/",
"reference_solution": "class Solution:\n def singleNumber(self, nums: list[int]) -> int:\n res = 0\n for n in nums: res ^= n\n return res"
},
{
"id": "nc-191",
"problem_number": 191,
"name": "Number of 1 Bits",
"pattern": "Bit Manipulation",
"difficulty": "Easy",
"time_complexity": "O(1)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def hammingWeight(self, n: int) -> int:\n pass",
"description": "Return the number of set bits (Hamming weight) that the integer n has.",
"examples": [
{
"input": "n = 11",
"output": "3"
}
],
"constraints": [
"1 <= n <= 2^31 - 1"
],
"leetcode_url": "https://leetcode.com/problems/number-of-1-bits/",
"reference_solution": "class Solution:\n def hammingWeight(self, n: int) -> int:\n res = 0\n while n:\n n &= (n - 1)\n res += 1\n return res"
},
{
"id": "nc-338",
"problem_number": 338,
"name": "Counting Bits",
"pattern": "Bit Manipulation",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(N)",
"starter_code": "class Solution:\n def countBits(self, n: int) -> list[int]:\n pass",
"description": "Given an integer n, return an array ans of length n + 1 such that ans[i] is the number of 1's in the binary representation of i.",
"examples": [
{
"input": "n = 5",
"output": "[0,1,1,2,1,2]"
}
],
"constraints": [
"0 <= n <= 10^5"
],
"leetcode_url": "https://leetcode.com/problems/counting-bits/",
"reference_solution": "class Solution:\n def countBits(self, n: int) -> list[int]:\n dp = [0] * (n + 1)\n offset = 1\n for i in range(1, n + 1):\n if offset * 2 == i: offset = i\n dp[i] = 1 + dp[i - offset]\n return dp"
},
{
"id": "nc-190",
"problem_number": 190,
"name": "Reverse Bits",
"pattern": "Bit Manipulation",
"difficulty": "Easy",
"time_complexity": "O(1)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def reverseBits(self, n: int) -> int:\n pass",
"description": "Reverse bits of a given 32 bits unsigned integer.",
"examples": [
{
"input": "n = 00000010100101000001111010011100",
"output": "964176192 (00111001011110000010100101000000)"
}
],
"constraints": [
"The input must be a binary string of length 32"
],
"leetcode_url": "https://leetcode.com/problems/reverse-bits/",
"reference_solution": "class Solution:\n def reverseBits(self, n: int) -> int:\n res = 0\n for i in range(32):\n bit = (n >> i) & 1\n res |= (bit << (31 - i))\n return res"
},
{
"id": "nc-268",
"problem_number": 268,
"name": "Missing Number",
"pattern": "Bit Manipulation",
"difficulty": "Easy",
"time_complexity": "O(N)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def missingNumber(self, nums: list[int]) -> int:\n pass",
"description": "Given an array nums containing n distinct numbers in range [0, n], return the only number in the range that is missing.",
"examples": [
{
"input": "nums = [3,0,1]",
"output": "2"
}
],
"constraints": [
"n == nums.length",
"1 <= n <= 10^4"
],
"leetcode_url": "https://leetcode.com/problems/missing-number/",
"reference_solution": "class Solution:\n def missingNumber(self, nums: list[int]) -> int:\n res = len(nums)\n for i in range(len(nums)):\n res += (i - nums[i])\n return res"
},
{
"id": "nc-371",
"problem_number": 371,
"name": "Sum of Two Integers",
"pattern": "Bit Manipulation",
"difficulty": "Medium",
"time_complexity": "O(1)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def getSum(self, a: int, b: int) -> int:\n pass",
"description": "Given two integers a and b, return the sum of the two integers without using the operators + and -.",
"examples": [
{
"input": "a = 1, b = 2",
"output": "3"
}
],
"constraints": [
"-1000 <= a, b <= 1000"
],
"leetcode_url": "https://leetcode.com/problems/sum-of-two-integers/",
"reference_solution": "class Solution:\n def getSum(self, a: int, b: int) -> int:\n mask = 0xFFFFFFFF\n while (b & mask) != 0:\n carry = (a & b) << 1\n a = a ^ b\n b = carry\n return (a & mask) if b > 0 else a"
},
{
"id": "nc-7",
"problem_number": 7,
"name": "Reverse Integer",
"pattern": "Bit Manipulation",
"difficulty": "Medium",
"time_complexity": "O(log X)",
"space_complexity": "O(1)",
"starter_code": "class Solution:\n def reverse(self, x: int) -> int:\n pass",
"description": "Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes overflow, return 0.",
"examples": [
{
"input": "x = 123",
"output": "321"
}
],
"constraints": [
"-2^31 <= x <= 2^31 - 1"
],
"leetcode_url": "https://leetcode.com/problems/reverse-integer/",
"reference_solution": "class Solution:\n def reverse(self, x: int) -> int:\n sign = -1 if x < 0 else 1\n x = abs(x)\n res = int(str(x)[::-1]) * sign\n return res if -2**31 <= res <= 2**31 - 1 else 0"
}
];
|