File size: 67,981 Bytes
8938d1b |
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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 0]"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from typing import List\n",
"# best solution according to LEETCODE\n",
"class Solution:\n",
" def twoSum(self, nums: List[int], target: int) -> List[int]:\n",
" hashmap = {}\n",
" for i in range(len(nums)):\n",
" complement = target - nums[i]\n",
" if complement in hashmap:\n",
" return [i, hashmap[complement]]\n",
" hashmap[nums[i]] = i\n",
" \n",
"Solution().twoSum(case_1, 9)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 0]"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"case_1 = [2,7,11,15]\n",
"\n",
"Solution().twoSum(case_1, 9)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[0, 1]"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class Solution:\n",
" def twoSum(self, nums: List[int], target: int) -> List[int]:\n",
" for i in range(len(nums)):\n",
" for j in range(i + 1, len(nums)):\n",
" if nums[j] == target - nums[i]:\n",
" return [i, j]\n",
"\n",
"\n",
"Solution().twoSum(case_1, 9)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[2, 7, 11, 15]\n",
"7\n",
"2\n"
]
},
{
"data": {
"text/plain": [
"[0, 1]"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class Solution:\n",
" def twoSum(self, nums, target):\n",
" \"\"\"\n",
" :type nums: List[int]\n",
" :type target: int\n",
" :rtype: List[int]\n",
" \"\"\"\n",
" print(nums)\n",
" hashmap = {}\n",
" for i, num in enumerate(nums):\n",
" n = target - num\n",
" print(n)\n",
" if n not in hashmap:\n",
" hashmap[num] = i\n",
" else:\n",
" return [hashmap[n], i]\n",
"\n",
"Solution().twoSum(case_1, 9)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" 1\n",
" 1 1\n",
" 1 2 1\n",
" 1 3 3 1\n",
" 1 4 6 4 1\n",
" 1 6 1 0 5 1\n"
]
}
],
"source": [
"# Print Pascal's Triangle in Python\n",
"\n",
"# input n\n",
"n = 6\n",
"\n",
"# iterarte upto n\n",
"for i in range(n):\n",
"\t# adjust space\n",
"\tprint(' '*(n-i), end='')\n",
"\n",
"\t# compute power of 11\n",
"\tprint(' '.join(map(str, str(11**i))))\n"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1, 5, 10, 10, 5, 1"
]
}
],
"source": [
"# Python3 program to implement the above approach\n",
"\n",
"# Print the N-th row of the\n",
"# Pascal's Triangle\n",
"def generateNthRow (N):\n",
"\n",
"\t# nC0 = 1\n",
"\tprev = 1\n",
"\tprint(prev, end = '')\n",
"\n",
"\tfor i in range(1, N + 1):\n",
"\n",
"\t\t# nCr = (nCr-1 * (n - r + 1))/r\n",
"\t\tcurr = (prev * (N - i + 1)) // i\n",
"\t\tprint(\",\", curr, end = '')\n",
"\t\tprev = curr\n",
"\n",
"# Driver code\n",
"N = 5\n",
"\n",
"# Function calling\n",
"generateNthRow(N)\n",
"\n",
"# This code is contributed by himanshu77\n"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"22"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"\"foo\".__hash__()\n",
"\n",
"bar = 22.0\n",
"\n",
"bar.__hash__()"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[][][][][][][][][][][][][][][][][][][][][][][][][][('gfg@example.com', 'some value')][][][][][][][][][][][][][][][][][][][][][][][][]\n",
"\n",
"[][][][][][][][][][][][][][][][][][('portal@example.com', 'some other value')][][][][][][][][('gfg@example.com', 'some value')][][][][][][][][][][][][][][][][][][][][][][][][]\n",
"\n",
"some other value\n",
"\n",
"[][][][][][][][][][][][][][][][][][][][][][][][][][('gfg@example.com', 'some value')][][][][][][][][][][][][][][][][][][][][][][][][]\n"
]
}
],
"source": [
"class HashTable:\n",
"\n",
"\t# Create empty bucket list of given size\n",
"\tdef __init__(self, size):\n",
"\t\tself.size = size\n",
"\t\tself.hash_table = self.create_buckets()\n",
"\n",
"\tdef create_buckets(self):\n",
"\t\treturn [[] for _ in range(self.size)]\n",
"\n",
"\t# Insert values into hash map\n",
"\tdef set_val(self, key, val):\n",
"\t\t\n",
"\t\t# Get the index from the key\n",
"\t\t# using hash function\n",
"\t\thashed_key = hash(key) % self.size\n",
"\t\t\n",
"\t\t# Get the bucket corresponding to index\n",
"\t\tbucket = self.hash_table[hashed_key]\n",
"\n",
"\t\tfound_key = False\n",
"\t\tfor index, record in enumerate(bucket):\n",
"\t\t\trecord_key, record_val = record\n",
"\t\t\t\n",
"\t\t\t# check if the bucket has same key as\n",
"\t\t\t# the key to be inserted\n",
"\t\t\tif record_key == key:\n",
"\t\t\t\tfound_key = True\n",
"\t\t\t\tbreak\n",
"\n",
"\t\t# If the bucket has same key as the key to be inserted,\n",
"\t\t# Update the key value\n",
"\t\t# Otherwise append the new key-value pair to the bucket\n",
"\t\tif found_key:\n",
"\t\t\tbucket[index] = (key, val)\n",
"\t\telse:\n",
"\t\t\tbucket.append((key, val))\n",
"\n",
"\t# Return searched value with specific key\n",
"\tdef get_val(self, key):\n",
"\t\t\n",
"\t\t# Get the index from the key using\n",
"\t\t# hash function\n",
"\t\thashed_key = hash(key) % self.size\n",
"\t\t\n",
"\t\t# Get the bucket corresponding to index\n",
"\t\tbucket = self.hash_table[hashed_key]\n",
"\n",
"\t\tfound_key = False\n",
"\t\tfor index, record in enumerate(bucket):\n",
"\t\t\trecord_key, record_val = record\n",
"\t\t\t\n",
"\t\t\t# check if the bucket has same key as\n",
"\t\t\t# the key being searched\n",
"\t\t\tif record_key == key:\n",
"\t\t\t\tfound_key = True\n",
"\t\t\t\tbreak\n",
"\n",
"\t\t# If the bucket has same key as the key being searched,\n",
"\t\t# Return the value found\n",
"\t\t# Otherwise indicate there was no record found\n",
"\t\tif found_key:\n",
"\t\t\treturn record_val\n",
"\t\telse:\n",
"\t\t\treturn \"No record found\"\n",
"\n",
"\t# Remove a value with specific key\n",
"\tdef delete_val(self, key):\n",
"\t\t\n",
"\t\t# Get the index from the key using\n",
"\t\t# hash function\n",
"\t\thashed_key = hash(key) % self.size\n",
"\t\t\n",
"\t\t# Get the bucket corresponding to index\n",
"\t\tbucket = self.hash_table[hashed_key]\n",
"\n",
"\t\tfound_key = False\n",
"\t\tfor index, record in enumerate(bucket):\n",
"\t\t\trecord_key, record_val = record\n",
"\t\t\t\n",
"\t\t\t# check if the bucket has same key as\n",
"\t\t\t# the key to be deleted\n",
"\t\t\tif record_key == key:\n",
"\t\t\t\tfound_key = True\n",
"\t\t\t\tbreak\n",
"\t\tif found_key:\n",
"\t\t\tbucket.pop(index)\n",
"\t\treturn\n",
"\n",
"\t# To print the items of hash map\n",
"\tdef __str__(self):\n",
"\t\treturn \"\".join(str(item) for item in self.hash_table)\n",
"\n",
"\n",
"hash_table = HashTable(50)\n",
"\n",
"# insert some values\n",
"hash_table.set_val('gfg@example.com', 'some value')\n",
"print(hash_table)\n",
"print()\n",
"\n",
"hash_table.set_val('portal@example.com', 'some other value')\n",
"print(hash_table)\n",
"print()\n",
"\n",
"# search/access a record with key\n",
"print(hash_table.get_val('portal@example.com'))\n",
"print()\n",
"\n",
"# delete or remove a value\n",
"hash_table.delete_val('portal@example.com')\n",
"print(hash_table)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Longest Substring Without Repeating Characters (medium) -- blind 75 \n",
"\n",
"Given a string s, find the length of the longest\n",
"substring\n",
"without repeating characters.\n",
"\n",
"Input: s = \"abcabcbb\"\n",
"Output: 3\n",
"Explanation: The answer is \"abc\", with the length of 3."
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class Solution:\n",
" def lengthOfLongestSubstring(self, s: str) -> int:\n",
" def check(start, end):\n",
" chars = set()\n",
" for i in range(start, end + 1):\n",
" c = s[i]\n",
" if c in chars:\n",
" return False\n",
" chars.add(c)\n",
" return True\n",
"\n",
" n = len(s)\n",
"\n",
" res = 0\n",
" for i in range(n):\n",
" for j in range(i, n):\n",
" if check(i, j):\n",
" res = max(res, j - i + 1)\n",
" return res\n",
"\n",
"s = \"abcabcbb\"\n",
"\n",
"Solution().lengthOfLongestSubstring(s)"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class Solution:\n",
" def lengthOfLongestSubstring(self, s: str) -> int:\n",
" n = len(s)\n",
" ans = 0\n",
" # mp stores the current index of a character\n",
" mp = {}\n",
"\n",
" i = 0\n",
" # try to extend the range [i, j]\n",
" for j in range(n):\n",
" if s[j] in mp:\n",
" i = max(mp[s[j]], i)\n",
"\n",
" ans = max(ans, j - i + 1)\n",
" mp[s[j]] = j + 1\n",
"\n",
" return ans\n",
"\n",
"s = \"abcabcbb\"\n",
"\n",
"Solution().lengthOfLongestSubstring(s)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 5. Longest Palindromic Substring\n",
"\n",
"Given a string s, return the longest palindromic substring in s.\n",
"\n",
"Input: s = \"babad\"\n",
"Output: \"bab\"\n",
"Explanation: \"aba\" is also a valid answer."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class Solution:\n",
" def longestPalindrome(self, s: str) -> str:\n",
" m = '' # Memory to remember a palindrome\n",
" for i in range(len(s)): # i = start, O = n\n",
" for j in range(len(s), i, -1): # j = end, O = n^2\n",
" if len(m) >= j-i: # To reduce time\n",
" break\n",
" elif s[i:j] == s[i:j][::-1]:\n",
" m = s[i:j]\n",
" break\n",
" return m"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 11. Container With Most Water \n",
"\n",
"You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).\n",
"\n",
"Find two lines that together with the x-axis form a container, such that the container contains the most water.\n",
"\n",
"Return the maximum amount of water a container can store.\n",
"\n",
"Notice that you may not slant the container.\n"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"49"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class Solution:\n",
" def maxArea(self, height: List[int]) -> int:\n",
" maxarea = 0\n",
" left = 0\n",
" right = len(height) - 1\n",
" \n",
" while left < right:\n",
" width = right - left\n",
" maxarea = max(maxarea, min(height[left], height[right]) * width)\n",
" if height[left] <= height[right]:\n",
" left += 1\n",
" else:\n",
" right -= 1\n",
" \n",
" return maxarea\n",
"\n",
"height = [1,8,6,2,5,4,8,3,7]\n",
"\n",
"Solution().maxArea(height)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 15. 3Sum \n",
"\n",
"Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.\n",
"\n",
"Notice that the solution set must not contain duplicate triplets.\n"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(-1, -1, 2), (-1, 0, 1)]"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class Solution:\n",
" def threeSum(self, nums):\n",
" res = []\n",
" nums.sort()\n",
" for i in range(len(nums)-2):\n",
" if i > 0 and nums[i] == nums[i-1]:\n",
" continue\n",
" l, r = i+1, len(nums)-1\n",
" while l < r:\n",
" s = nums[i] + nums[l] + nums[r]\n",
" if s < 0:\n",
" l +=1 \n",
" elif s > 0:\n",
" r -= 1\n",
" else:\n",
" res.append((nums[i], nums[l], nums[r]))\n",
" while l < r and nums[l] == nums[l+1]:\n",
" l += 1\n",
" while l < r and nums[r] == nums[r-1]:\n",
" r -= 1\n",
" l += 1; r -= 1\n",
" return res\n",
"\n",
"nums = [-1,0,1,2,-1,-4]\n",
"\n",
"Solution().threeSum(nums)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 20. Valid Parenthesis \n",
"\n",
"Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.\n",
"\n",
"An input string is valid if:\n",
"\n",
" Open brackets must be closed by the same type of brackets.\n",
" Open brackets must be closed in the correct order.\n",
" Every close bracket has a corresponding open bracket of the same type.\n"
]
},
{
"cell_type": "code",
"execution_count": 118,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 118,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class Solution:\n",
" # @return a boolean\n",
" def isValid(self, s):\n",
" stack = []\n",
" dict = {\"]\":\"[\", \"}\":\"{\", \")\":\"(\"}\n",
" for char in s:\n",
" if char in dict.values():\n",
" stack.append(char)\n",
" elif char in dict.keys():\n",
" if stack == [] or dict[char] != stack.pop():\n",
" return False\n",
" else:\n",
" return False\n",
" return stack == []\n",
"\n",
"\n",
"s = \"()[]{}\"\n",
"s = \"()[]{}\"\n",
"Solution().isValid(s)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 21. Merge Two Sorted List \n",
"\n",
"You are given the heads of two sorted linked lists list1 and list2.\n",
"\n",
"Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.\n",
"\n",
"Return the head of the merged linked list."
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [],
"source": [
"from typing import Optional\n",
"\n",
"class ListNode(object):\n",
" def __init__(self, x):\n",
" self.val = x\n",
" self.next = None\n",
"\n",
"\n",
"class Solution:\n",
" def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n",
" cur = dummy = ListNode()\n",
" while list1 and list2: \n",
" if list1.val < list2.val:\n",
" cur.next = list1\n",
" list1, cur = list1.next, list1\n",
" else:\n",
" cur.next = list2\n",
" list2, cur = list2.next, list2\n",
" \n",
" if list1 or list2:\n",
" cur.next = list1 if list1 else list2\n",
" \n",
" return dummy.next"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 23. Merge k Sorted Lists (hard)\n",
"\n",
"You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.\n",
"\n",
"Merge all the linked-lists into one sorted linked-list and return it.\n"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [],
"source": [
"# brute force \n",
"\n",
"class Solution(object):\n",
" def mergeKLists(self, lists):\n",
" \"\"\"\n",
" :type lists: List[ListNode]\n",
" :rtype: ListNode\n",
" \"\"\"\n",
" self.nodes = []\n",
" head = point = ListNode(0)\n",
" for l in lists:\n",
" while l:\n",
" self.nodes.append(l.val)\n",
" l = l.next\n",
" for x in sorted(self.nodes):\n",
" point.next = ListNode(x)\n",
" point = point.next\n",
" return head.next"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"ename": "ModuleNotFoundError",
"evalue": "No module named 'Queue'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[38], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39mQueue\u001b[39;00m \u001b[39mimport\u001b[39;00m PriorityQueue\n\u001b[1;32m 3\u001b[0m \u001b[39mclass\u001b[39;00m \u001b[39mSolution\u001b[39;00m(\u001b[39mobject\u001b[39m):\n\u001b[1;32m 4\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39mmergeKLists\u001b[39m(\u001b[39mself\u001b[39m, lists):\n",
"\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'Queue'"
]
}
],
"source": [
"from Queue import PriorityQueue\n",
"\n",
"class Solution(object):\n",
" def mergeKLists(self, lists):\n",
" \"\"\"\n",
" :type lists: List[ListNode]\n",
" :rtype: ListNode\n",
" \"\"\"\n",
" head = point = ListNode(0)\n",
" q = PriorityQueue()\n",
" for l in lists:\n",
" if l:\n",
" q.put((l.val, l))\n",
" while not q.empty():\n",
" val, node = q.get()\n",
" point.next = ListNode(val)\n",
" point = point.next\n",
" node = node.next\n",
" if node:\n",
" q.put((node.val, node))\n",
" return head.next\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 33. Search in Rotated Sorted Array (medium)\n",
"\n",
"There is an integer array nums sorted in ascending order (with distinct values).\n",
"\n",
"Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].\n",
"\n",
"Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.\n",
"\n",
"You must write an algorithm with O(log n) runtime complexity."
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"4"
]
},
"execution_count": 41,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class Solution:\n",
" def search(self, A: List[int], target: int) -> int:\n",
" n = len(A)\n",
" left, right = 0, n - 1\n",
" if n == 0: return -1\n",
" \n",
" while left <= right:\n",
" mid = left + (right - left) // 2\n",
" if A[mid] == target: return mid\n",
" \n",
" # inflection point to the right. Left is strictly increasing\n",
" if A[mid] >= A[left]:\n",
" if A[left] <= target < A[mid]:\n",
" right = mid - 1\n",
" else:\n",
" left = mid + 1\n",
" \n",
" # inflection point to the left of me. Right is strictly increasing\n",
" else:\n",
" if A[mid] < target <= A[right]:\n",
" left = mid + 1\n",
" else:\n",
" right = mid - 1\n",
" \n",
" return -1\n",
"\n",
"A = [4,5,6,7,0,1,2]\n",
"target = 0 \n",
"\n",
"# return index of pivot \n",
"Solution().search(A, target)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 39. Combination Sum (medium)\n",
"\n",
"Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.\n",
"\n",
"The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the\n",
"frequency\n",
"of at least one of the chosen numbers is different.\n",
"\n",
"The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.\n"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[[2, 2, 3], [7]]"
]
},
"execution_count": 42,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class Solution(object):\n",
" def combinationSum(self, candidates, target):\n",
" ret = []\n",
" self.dfs(candidates, target, [], ret)\n",
" return ret\n",
" \n",
" def dfs(self, nums, target, path, ret):\n",
" if target < 0:\n",
" return \n",
" if target == 0:\n",
" ret.append(path)\n",
" return \n",
" for i in range(len(nums)):\n",
" self.dfs(nums[i:], target-nums[i], path+[nums[i]], ret)\n",
"\n",
"candidates = [2,3,6,7]\n",
"targets = 7 \n",
"\n",
"Solution().combinationSum(candidates, targets)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 48. Rotate Image (medium)\n",
"\n",
"You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).\n",
"\n",
"You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.\n",
"\n",
"\n",
"\n",
"**Bonus Question:** If you're not too confident with matrices and linear algebra, get some more practice by also coding a method that transposes the matrix on the other diagonal, and another that reflects from top to bottom. You can test your functions by printing out the matrix before and after each operation. Finally, use your functions to find three more solutions to this problem. Each solution uses two matrix operations.\n",
"\n",
"\n",
"**Interview Tip:** Terrified of being asked this question in an interview? Many people are: it can be intimidating due to the fiddly logic. Unfortunately, if you do a lot of interviewing, the probability of seeing it at least once is high, and some people have claimed to have seen it multiple times! This is one of the few questions where I recommend practicing until you can confidently code it and explain it without thinking too much.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class Solution:\n",
" def rotate(self, matrix: List[List[int]]) -> None:\n",
" self.transpose(matrix)\n",
" self.reflect(matrix)\n",
" \n",
" def transpose(self, matrix):\n",
" n = len(matrix)\n",
" for i in range(n):\n",
" for j in range(i + 1, n):\n",
" matrix[j][i], matrix[i][j] = matrix[i][j], matrix[j][i]\n",
"\n",
" def reflect(self, matrix):\n",
" n = len(matrix)\n",
" for i in range(n):\n",
" for j in range(n // 2):\n",
" matrix[i][j], matrix[i][-j - 1] = matrix[i][-j - 1], matrix[i][j]\n",
"\n",
"matrix = [[1,2,3],[4,5,6],[7,8,9]]\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"49. Group Anagrams\n",
"\n",
"Given an array of strings strs, group the anagrams together. You can return the answer in any order.\n",
"\n",
"An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"dict_values([['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']])"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import collections\n",
"\n",
"class Solution:\n",
" def groupAnagrams(self, strs):\n",
" ans = collections.defaultdict(list)\n",
" for s in strs:\n",
" count = [0] * 26\n",
" for c in s:\n",
" count[ord(c) - ord('a')] += 1\n",
" ans[tuple(count)].append(s)\n",
" return ans.values()\n",
"\n",
"strs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]\n",
"\n",
"Solution().groupAnagrams(strs)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 53. Maximum Subarray \n",
"iven an integer array nums, find the\n",
"subarray\n",
"which has the largest sum and return its sum.\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# kadane algo \n",
"for i in range(1, len(nums)):\n",
" if nums[i-1] > 0:\n",
" nums[i] += nums[i-1]\n",
" return max(nums)\n",
"\n",
"\n",
"from itertools import accumulate\n",
"\n",
"return max(accumulate(nums, lambda x, y: x+y if x > 0 else y))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# spiral matrix\n",
"\n",
"Given an m x n matrix, return all elements of the matrix in spiral order.\n",
"\n",
"matrix = [[1,2,3],[4,5,6],[7,8,9]]\n",
"output [1,2,3,6,9,8,7,4,5]\n"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [],
"source": [
"class Solution:\n",
" def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n",
" res = []\n",
" if len(matrix) == 0:\n",
" return res\n",
" row_begin = 0\n",
" col_begin = 0\n",
" row_end = len(matrix)-1 \n",
" col_end = len(matrix[0])-1\n",
" while (row_begin <= row_end and col_begin <= col_end):\n",
" for i in range(col_begin,col_end+1):\n",
" res.append(matrix[row_begin][i])\n",
" row_begin += 1\n",
" for i in range(row_begin,row_end+1):\n",
" res.append(matrix[i][col_end])\n",
" col_end -= 1\n",
" if (row_begin <= row_end):\n",
" for i in range(col_end,col_begin-1,-1):\n",
" res.append(matrix[row_end][i])\n",
" row_end -= 1\n",
" if (col_begin <= col_end):\n",
" for i in range(row_end,row_begin-1,-1):\n",
" res.append(matrix[i][col_begin])\n",
" col_begin += 1\n",
" return res\n",
" \n",
" \n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Jump Game (medium) \n",
"\n",
"You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.\n",
"\n",
"Return true if you can reach the last index, or false otherwise."
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 50,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class Solution:\n",
" def canJump(self, nums: List[int]) -> bool:\n",
" m = 0\n",
" for i, n in enumerate(nums):\n",
" if i > m:\n",
" return False\n",
" m = max(m, i+n)\n",
" return True\n",
"\n",
"nums = [2,3,1,1,4]\n",
"\n",
"nums = [3,2,1,0,4]\n",
"\n",
"Solution().canJump(nums)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 56. Merge Intervals\n",
"\n",
"Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.\n"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[[1, 6], [8, 10], [15, 18]]"
]
},
"execution_count": 54,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# time complexity analysis O(n log n )\n",
"class Solution:\n",
" def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
"\n",
" intervals.sort(key=lambda x: x[0])\n",
"\n",
" merged = []\n",
" for interval in intervals:\n",
" # if the list of merged intervals is empty or if the current\n",
" # interval does not overlap with the previous, simply append it.\n",
" if not merged or merged[-1][1] < interval[0]:\n",
" merged.append(interval)\n",
" else:\n",
" # otherwise, there is overlap, so we merge the current and previous\n",
" # intervals.\n",
" merged[-1][1] = max(merged[-1][1], interval[1])\n",
"\n",
" return merged\n",
"\n",
"intervals = [[1,3],[2,6],[8,10],[15,18]]\n",
"\n",
"Solution().merge(intervals)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 57. Insert Interval\n",
"\n",
"You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.\n",
"\n",
"Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).\n",
"\n",
"Return intervals after the insertion."
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[[1, 5], [6, 9]]"
]
},
"execution_count": 59,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# class Solution:\n",
"# def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n",
"# # s, e = newInterval.start, newInterval.end\n",
"# s, e = newInterval[0], newInterval[1]\n",
"# left = [i for i in intervals if i.end < s]\n",
"# right = [i for i in intervals if i.start > e]\n",
"# if left + right != intervals:\n",
"# s = min(s, intervals[len(left)].start)\n",
"# e = max(e, intervals[~len(right)].end)\n",
"# return left + [Interval(s, e)] + right\n",
"\n",
"\n",
"class Solution:\n",
" def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n",
" s, e = newInterval[0], newInterval[1]\n",
" left, right = [], []\n",
" for i in intervals:\n",
" if i[1] < s:\n",
" left += i,\n",
" elif i[0] > e:\n",
" right += i,\n",
" else:\n",
" s = min(s, i[0])\n",
" e = max(e, i[1])\n",
" return left + [[s, e]] + right\n",
"\n",
"intervals = [[1,3],[6,9]]\n",
"newInterval = [2,5]\n",
"\n",
"Solution().insert(intervals, newInterval)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 70. Climbing Stairs\n",
"\n",
"You are climbing a staircase. It takes n steps to reach the top.\n",
"\n",
"Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 60,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"class Solution:\n",
" def climbStairs(self, n: int) -> int:\n",
" a = b = 1\n",
" for _ in range(n):\n",
" a, b = b, a + b\n",
" return a\n",
"\n",
"n = 2\n",
"Solution().climbStairs(n)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 73. Set Matrix Zeros \n",
"\n",
"Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.\n",
"\n",
"You must do it in place."
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[1, 0, 1], [0, 0, 0], [1, 0, 1]]\n"
]
}
],
"source": [
"class Solution(object):\n",
" def setZeroes(self, matrix):\n",
" \"\"\"\n",
" :type matrix: List[List[int]]\n",
" :rtype: void Do not return anything, modify matrix in-place instead.\n",
" \"\"\"\n",
" is_col = False\n",
" R = len(matrix)\n",
" C = len(matrix[0])\n",
" for i in range(R):\n",
" # Since first cell for both first row and first column is the same i.e. matrix[0][0]\n",
" # We can use an additional variable for either the first row/column.\n",
" # For this solution we are using an additional variable for the first column\n",
" # and using matrix[0][0] for the first row.\n",
" if matrix[i][0] == 0:\n",
" is_col = True\n",
" for j in range(1, C):\n",
" # If an element is zero, we set the first element of the corresponding row and column to 0\n",
" if matrix[i][j] == 0:\n",
" matrix[0][j] = 0\n",
" matrix[i][0] = 0\n",
"\n",
" # Iterate over the array once again and using the first row and first column, update the elements.\n",
" for i in range(1, R):\n",
" for j in range(1, C):\n",
" if not matrix[i][0] or not matrix[0][j]:\n",
" matrix[i][j] = 0\n",
"\n",
" # See if the first row needs to be set to zero as well\n",
" if matrix[0][0] == 0:\n",
" for j in range(C):\n",
" matrix[0][j] = 0\n",
"\n",
" # See if the first column needs to be set to zero as well \n",
" if is_col:\n",
" for i in range(R):\n",
" matrix[i][0] = 0\n",
"\n",
"matrix = [[1,1,1],[1,0,1],[1,1,1]]\n",
"\n",
"Solution().setZeroes(matrix)\n",
"print(matrix)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 76. Minimum Window Substring (hard)\n",
"\n",
"Given two strings s and t of lengths m and n respectively, return the minimum window\n",
"substring\n",
"of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string \"\".\n",
"\n",
"The testcases will be generated such that the answer is unique.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# solution from leetcode \n",
"\n",
"def minWindow(self, s, t):\n",
" \"\"\"\n",
" :type s: str\n",
" :type t: str\n",
" :rtype: str\n",
" \"\"\"\n",
"\n",
" if not t or not s:\n",
" return \"\"\n",
"\n",
" # Dictionary which keeps a count of all the unique characters in t.\n",
" dict_t = Counter(t)\n",
"\n",
" # Number of unique characters in t, which need to be present in the desired window.\n",
" required = len(dict_t)\n",
"\n",
" # left and right pointer\n",
" l, r = 0, 0\n",
"\n",
" # formed is used to keep track of how many unique characters in t are present in the current window in its desired frequency.\n",
" # e.g. if t is \"AABC\" then the window must have two A's, one B and one C. Thus formed would be = 3 when all these conditions are met.\n",
" formed = 0\n",
"\n",
" # Dictionary which keeps a count of all the unique characters in the current window.\n",
" window_counts = {}\n",
"\n",
" # ans tuple of the form (window length, left, right)\n",
" ans = float(\"inf\"), None, None\n",
"\n",
" while r < len(s):\n",
"\n",
" # Add one character from the right to the window\n",
" character = s[r]\n",
" window_counts[character] = window_counts.get(character, 0) + 1\n",
"\n",
" # If the frequency of the current character added equals to the desired count in t then increment the formed count by 1.\n",
" if character in dict_t and window_counts[character] == dict_t[character]:\n",
" formed += 1\n",
"\n",
" # Try and contract the window till the point where it ceases to be 'desirable'.\n",
" while l <= r and formed == required:\n",
" character = s[l]\n",
"\n",
" # Save the smallest window until now.\n",
" if r - l + 1 < ans[0]:\n",
" ans = (r - l + 1, l, r)\n",
"\n",
" # The character at the position pointed by the `left` pointer is no longer a part of the window.\n",
" window_counts[character] -= 1\n",
" if character in dict_t and window_counts[character] < dict_t[character]:\n",
" formed -= 1\n",
"\n",
" # Move the left pointer ahead, this would help to look for a new window.\n",
" l += 1 \n",
"\n",
" # Keep expanding the window once we are done contracting.\n",
" r += 1 \n",
" return \"\" if ans[0] == float(\"inf\") else s[ans[1] : ans[2] + 1]\n",
"\n",
"s = \"ADOBECODEBANC\", t = \"ABC\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# soltuion from comments \n",
"\n",
"class Solution:\n",
" def minWindow(s, t):\n",
" need = collections.Counter(t) #hash table to store char frequency\n",
" missing = len(t) #total number of chars we care\n",
" start, end = 0, 0\n",
" i = 0\n",
" for j, char in enumerate(s, 1): #index j from 1\n",
" if need[char] > 0:\n",
" missing -= 1\n",
" need[char] -= 1\n",
" if missing == 0: #match all chars\n",
" while i < j and need[s[i]] < 0: #remove chars to find the real start\n",
" need[s[i]] += 1\n",
" i += 1\n",
" need[s[i]] += 1 #make sure the first appearing char satisfies need[char]>0\n",
" missing += 1 #we missed this first char, so add missing by 1\n",
" if end == 0 or j-i < end-start: #update window\n",
" start, end = i, j\n",
" i += 1 #update i to start+1 for next window\n",
" return s[start:end]\n",
"\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 79. Word Search\n",
"\n",
"Given an m x n grid of characters board and a string word, return true if word exists in the grid.\n",
"\n",
"The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once."
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [],
"source": [
"# depth first search \n",
"\n",
"\n",
"def exist(self, board, word):\n",
" if not board:\n",
" return False\n",
" for i in xrange(len(board)):\n",
" for j in xrange(len(board[0])):\n",
" if self.dfs(board, i, j, word):\n",
" return True\n",
" return False\n",
"\n",
"# check whether can find word, start at (i,j) position \n",
"def dfs(self, board, i, j, word):\n",
" if len(word) == 0: # all the characters are checked\n",
" return True\n",
" if i<0 or i>=len(board) or j<0 or j>=len(board[0]) or word[0]!=board[i][j]:\n",
" return False\n",
" tmp = board[i][j] # first character is found, check the remaining part\n",
" board[i][j] = \"#\" # avoid visit agian \n",
" # check whether can find \"word\" along one direction\n",
" res = self.dfs(board, i+1, j, word[1:]) or self.dfs(board, i-1, j, word[1:]) \\\n",
" or self.dfs(board, i, j+1, word[1:]) or self.dfs(board, i, j-1, word[1:])\n",
" board[i][j] = tmp\n",
" return res\n",
"\n",
"board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]]\n",
"word = \"ABCCED\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 98. Validate Binary Search Tree\n",
"\n",
"Given the root of a binary tree, determine if it is a valid binary search tree (BST).\n",
"\n",
"A valid BST is defined as follows:\n",
"\n",
"The left\n",
"subtree\n",
"of a node contains only nodes with keys less than the node's key.\n",
"The right subtree of a node contains only nodes with keys greater than the node's key.\n",
"Both the left and right subtrees must also be binary search trees.\n"
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {},
"outputs": [
{
"ename": "AttributeError",
"evalue": "'list' object has no attribute 'val'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[69], line 19\u001b[0m\n\u001b[1;32m 15\u001b[0m \u001b[39mreturn\u001b[39;00m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39misValidBST(root\u001b[39m.\u001b[39mleft, floor, root\u001b[39m.\u001b[39mval) \u001b[39mand\u001b[39;00m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39misValidBST(root\u001b[39m.\u001b[39mright, root\u001b[39m.\u001b[39mval, ceiling)\n\u001b[1;32m 17\u001b[0m root \u001b[39m=\u001b[39m [\u001b[39m2\u001b[39m,\u001b[39m1\u001b[39m,\u001b[39m3\u001b[39m]\n\u001b[0;32m---> 19\u001b[0m Solution()\u001b[39m.\u001b[39;49misValidBST(root)\n",
"Cell \u001b[0;32mIn[69], line 12\u001b[0m, in \u001b[0;36mSolution.isValidBST\u001b[0;34m(self, root, floor, ceiling)\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[39mif\u001b[39;00m \u001b[39mnot\u001b[39;00m root: \n\u001b[1;32m 11\u001b[0m \u001b[39mreturn\u001b[39;00m \u001b[39mTrue\u001b[39;00m\n\u001b[0;32m---> 12\u001b[0m \u001b[39mif\u001b[39;00m root\u001b[39m.\u001b[39;49mval \u001b[39m<\u001b[39m\u001b[39m=\u001b[39m floor \u001b[39mor\u001b[39;00m root\u001b[39m.\u001b[39mval \u001b[39m>\u001b[39m\u001b[39m=\u001b[39m ceiling:\n\u001b[1;32m 13\u001b[0m \u001b[39mreturn\u001b[39;00m \u001b[39mFalse\u001b[39;00m\n\u001b[1;32m 14\u001b[0m \u001b[39m# in the left branch, root is the new ceiling; contrarily root is the new floor in right branch\u001b[39;00m\n",
"\u001b[0;31mAttributeError\u001b[0m: 'list' object has no attribute 'val'"
]
}
],
"source": [
"# Definition for a binary tree node.\n",
"# class TreeNode:\n",
"# def __init__(self, val=0, left=None, right=None):\n",
"# self.val = val\n",
"# self.left = left\n",
"# self.right = right\n",
"\n",
"class Solution:\n",
" def isValidBST(self, root, floor=float('-inf'), ceiling=float('inf')):\n",
" if not root: \n",
" return True\n",
" if root.val <= floor or root.val >= ceiling:\n",
" return False\n",
" # in the left branch, root is the new ceiling; contrarily root is the new floor in right branch\n",
" return self.isValidBST(root.left, floor, root.val) and self.isValidBST(root.right, root.val, ceiling)\n",
"\n",
"root = [2,1,3]\n",
"\n",
"Solution().isValidBST(root)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 100. Same Tree\n",
"\n",
"Given the roots of two binary trees p and q, write a function to check if they are the same or not.\n",
"\n",
"Two binary trees are considered the same if they are structurally identical, and the nodes have the same value."
]
},
{
"cell_type": "code",
"execution_count": 70,
"metadata": {},
"outputs": [],
"source": [
"from collections import deque\n",
"class Solution:\n",
" def isSameTree(self, p, q):\n",
" \"\"\"\n",
" :type p: TreeNode\n",
" :type q: TreeNode\n",
" :rtype: bool\n",
" \"\"\" \n",
" def check(p, q):\n",
" # if both are None\n",
" if not p and not q:\n",
" return True\n",
" # one of p and q is None\n",
" if not q or not p:\n",
" return False\n",
" if p.val != q.val:\n",
" return False\n",
" return True\n",
" \n",
" deq = deque([(p, q),])\n",
" while deq:\n",
" p, q = deq.popleft()\n",
" if not check(p, q):\n",
" return False\n",
" \n",
" if p:\n",
" deq.append((p.left, q.left))\n",
" deq.append((p.right, q.right))\n",
" \n",
" return True\n",
"\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 102. Binary Tree Level Order Traversal\n",
"\n",
"Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level)."
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'null' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[71], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m root \u001b[39m=\u001b[39m [\u001b[39m3\u001b[39m,\u001b[39m9\u001b[39m,\u001b[39m20\u001b[39m,null,null,\u001b[39m15\u001b[39m,\u001b[39m7\u001b[39m]\n",
"\u001b[0;31mNameError\u001b[0m: name 'null' is not defined"
]
}
],
"source": [
"def levelOrder(self, root):\n",
" ans, level = [], [root]\n",
" while root and level:\n",
" ans.append([node.val for node in level])\n",
" LRpair = [(node.left, node.right) for node in level]\n",
" level = [leaf for LR in LRpair for leaf in LR if leaf]\n",
" return ans\n",
"\n",
"root = [3,9,20,null,null,15,7]"
]
},
{
"cell_type": "code",
"execution_count": 72,
"metadata": {},
"outputs": [],
"source": [
"from collections import deque\n",
"def levelOrder(self, root):\n",
" # traverse in order level, keeping track of (row number, current node)\n",
" queue = deque([(0, root)])\n",
" # keep track of the nodes in each row\n",
" d = {}\n",
"\n",
" while queue:\n",
" row, node = queue.popleft()\n",
" if node:\n",
" d[row] = d.get(row, []) + [node.val]\n",
" queue += (row+1, node.left), (row+1, node.right)\n",
"\n",
" # return a list of lists containing node values in increasing order with respect to the row number\n",
" return [d[row] for row in sorted(d.keys())]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 104. Maximum Depth of Binary Tree\n",
"\n",
"Given the root of a binary tree, return its maximum depth.\n",
"\n",
"A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node."
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'null' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[76], line 17\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[39mreturn\u001b[39;00m \u001b[39mmax\u001b[39m(dfs(root\u001b[39m.\u001b[39mleft, depth \u001b[39m+\u001b[39m \u001b[39m1\u001b[39m), dfs(root\u001b[39m.\u001b[39mright, depth \u001b[39m+\u001b[39m \u001b[39m1\u001b[39m))\n\u001b[1;32m 14\u001b[0m \u001b[39mreturn\u001b[39;00m dfs(root, \u001b[39m0\u001b[39m)\n\u001b[0;32m---> 17\u001b[0m root \u001b[39m=\u001b[39m [\u001b[39m3\u001b[39m,\u001b[39m9\u001b[39m,\u001b[39m20\u001b[39m,null,null,\u001b[39m15\u001b[39m,\u001b[39m7\u001b[39m]\n\u001b[1;32m 19\u001b[0m Solution()\u001b[39m.\u001b[39mmaxDepth(root)\n",
"\u001b[0;31mNameError\u001b[0m: name 'null' is not defined"
]
}
],
"source": [
"# Definition for a binary tree node.\n",
"\n",
"# https://leetcode.com/problems/maximum-depth-of-binary-tree/solutions/1769367/python3-recursive-dfs-explained/?orderBy=most_votes\n",
"class TreeNode:\n",
" def __init__(self, val=0, left=None, right=None):\n",
" self.val = val\n",
" self.left = left\n",
" self.right = right\n",
"\n",
"class Solution:\n",
" def maxDepth(self, root: Optional[TreeNode]) -> int:\n",
" def dfs(root, depth):\n",
" if not root: return depth\n",
" return max(dfs(root.left, depth + 1), dfs(root.right, depth + 1))\n",
" \n",
" return dfs(root, 0)\n",
"\n",
"\n",
"root = [3,9,20,null,null,15,7]\n",
"\n",
"Solution().maxDepth(root)\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Here, \"Object references are passed by value.\""
]
},
{
"cell_type": "code",
"execution_count": 78,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 1]\n",
"[0, 1]\n"
]
}
],
"source": [
"listA = [0]\n",
"listB = listA\n",
"listB.append(1)\n",
"print (listA)\n",
"print(listB)"
]
},
{
"cell_type": "code",
"execution_count": 83,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0]\n",
"[0, 1]\n",
"[0]\n",
"[0, 1]\n",
"[0, 1]\n"
]
}
],
"source": [
"def reassign(list):\n",
" print(list)\n",
" list = [0, 1]\n",
" print(list)\n",
"\n",
"def append(list):\n",
" print(list)\n",
" list.append(1)\n",
" print(list)\n",
"\n",
"list = [0]\n",
"reassign(list)\n",
"append(list)\n",
"\n",
"print(list)"
]
},
{
"cell_type": "code",
"execution_count": 85,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"some value\n"
]
}
],
"source": [
"def foo(x):\n",
" print(x)\n",
"\n",
"bar = 'some value'\n",
"foo(bar)"
]
},
{
"cell_type": "code",
"execution_count": 88,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"another value\n",
"some value\n"
]
}
],
"source": [
"def foo(x):\n",
" x = 'another value'\n",
" print (x)\n",
"\n",
"bar = 'some value'\n",
"foo(bar)\n",
"print(bar)"
]
},
{
"cell_type": "code",
"execution_count": 93,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0]\n",
"[0, 1]\n",
"[0, 1]\n"
]
}
],
"source": [
"def append_one(li):\n",
" print(li)\n",
" li.append(1)\n",
" print(li)\n",
" return li\n",
"\n",
"x = [0]\n",
"x = append_one(x)\n",
"print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 105. Construct Binary Tree From Preorder and Inorder Traversal \n",
"\n",
"Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree."
]
},
{
"cell_type": "code",
"execution_count": 102,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3\n"
]
}
],
"source": [
"class TreeNode:\n",
" def __init__(self, val=0, left=None, right=None):\n",
" self.val = val\n",
" self.left = left\n",
" self.right = right\n",
"\n",
"class Solution:\n",
" def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:\n",
"\n",
" def array_to_tree(left, right):\n",
" nonlocal preorder_index\n",
" # if there are no elements to construct the tree\n",
" if left > right: return None\n",
"\n",
" # select the preorder_index element as the root and increment it\n",
" root_value = preorder[preorder_index]\n",
" root = TreeNode(root_value)\n",
"\n",
"\n",
" preorder_index += 1\n",
"\n",
" # build left and right subtree\n",
" # excluding inorder_index_map[root_value] element because it's the root\n",
" root.left = array_to_tree(left, inorder_index_map[root_value] - 1)\n",
" root.right = array_to_tree(inorder_index_map[root_value] + 1, right)\n",
"\n",
" return root\n",
"\n",
" preorder_index = 0\n",
"\n",
" # build a hashmap to store value -> its index relations\n",
" inorder_index_map = {}\n",
" for index, value in enumerate(inorder):\n",
" inorder_index_map[value] = index\n",
"\n",
" return array_to_tree(0, len(preorder) - 1)\n",
"\n",
"preorder = [3,9,20,15,7]\n",
"inorder = [9,3,15,20,7]\n",
"\n",
"# preorder = [-1]\n",
"# inorder = [-1]\n",
"\n",
"foo = Solution().buildTree(preorder, inorder)\n",
"print(foo.val)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 121. Best Time to Buy and Sell Stock\n",
"\n",
"You are given an array prices where prices[i] is the price of a given stock on the ith day.\n",
"\n",
"You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.\n",
"\n",
"Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0."
]
},
{
"cell_type": "code",
"execution_count": 109,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"inf\n"
]
},
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 109,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# could brute force with O(n^2) \n",
"class Solution:\n",
" def maxProfit(self, prices: List[int]) -> int:\n",
" min_price = float('inf')\n",
" print(min_price)\n",
" max_profit = 0\n",
" # for i in range(len(prices)):\n",
" for price in prices:\n",
" diff = price - min_price\n",
"\n",
" if price < min_price:\n",
" min_price = price\n",
" elif diff > max_profit:\n",
" max_profit = diff\n",
" \n",
" return max_profit\n",
"\n",
"prices = [7,1,5,3,6,4]\n",
"\n",
"min(prices)\n",
"\n",
"Solution().maxProfit(prices)\n",
"# Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\n",
"# Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell."
]
},
{
"cell_type": "code",
"execution_count": 114,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 114,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"prices = [7,1,5,3,6,4]\n",
"\n",
"# using the builtins but doesn't really work very nicely. \n",
"min(prices)\n",
"max(prices)\n",
"prices.index(max(prices))\n",
"prices.index(min(prices))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 124. Binary Tree Maximum Path Sum (hard)\n",
"\n",
"A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.\n",
"\n",
"The path sum of a path is the sum of the node's values in the path.\n",
"\n",
"Given the root of a binary tree, return the maximum path sum of any non-empty path."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 125. Valid Palindrome (easy)\n",
"\n",
"A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.\n",
"\n",
"Given a string s, return true if it is a palindrome, or false otherwise."
]
},
{
"cell_type": "code",
"execution_count": 116,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"amanaplanacanalpanama\n",
"amanaplanacanalpanama\n"
]
},
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 116,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def isPalindrome(self, s):\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; r -= 1\n",
" return True\n",
"\n",
"# so dope bro \n",
"class Solution:\n",
" def isPalindrome(self, s):\n",
" s = ''.join(e for e in s if e.isalnum()).lower()\n",
" print(s)\n",
" print(s[::-1])\n",
" return s==s[::-1]\n",
"\n",
"s = \"A man, a plan, a canal: Panama\"\n",
"\n",
"Solution().isPalindrome(s)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"4.2"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"float(\"4.2/5\".split('/')[0].strip())\n",
"\n",
"float(\"4.2/5\".split(\"/\")[0].strip())"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Balanced sum \n",
"\n",
"Given an array of integers nums, calculate the pivot index of this array.\n",
"\n",
"The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.\n",
"\n",
"If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.\n",
"\n",
"Return the leftmost pivot index. If no such index exists, return -1."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# Time Complexity : O(n)\n",
"# Space Complexity : O(1)\n",
"class Solution(object):\n",
" def pivotIndex(self, nums):\n",
" # Initialize leftSum & rightSum to store the sum of all the numbers strictly to the index's left & right respectively...\n",
" leftSum, rightSum = 0, sum(nums)\n",
" # Traverse elements through the loop...\n",
" for idx, ele in enumerate(nums):\n",
" rightSum -= ele\n",
" # If the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right...\n",
" if leftSum == rightSum:\n",
" return idx # Return the pivot index...\n",
" leftSum += ele\n",
" return -1 # If there is no index that satisfies the conditions in the problem statement..."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"nums = [1,7,3,6,5,6]\n",
"Solution().pivotIndex(nums)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.4"
},
"orig_nbformat": 4,
"vscode": {
"interpreter": {
"hash": "b0fa6594d8f4cbf19f97940f81e996739fb7646882a419484c72d19e05852a7e"
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|