File size: 17,964 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 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 217. Contains Duplicate\n",
"\n",
"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.\n",
"\n",
"Example 1:\n",
"\n",
"Input: nums = [1,2,3,1]\n",
"Output: true\n",
"\n",
"Example 2:\n",
"\n",
"Input: nums = [1,2,3,4]\n",
"Output: false\n",
"\n",
"Example 3:\n",
"\n",
"Input: nums = [1,1,1,3,3,4,3,2,4,2]\n",
"Output: true\n",
"\n",
"Constraints:\n",
"\n",
" 1 <= nums.length <= 105\n",
" -109 <= nums[i] <= 109\n"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"from typing import List\n",
"\n",
"\n",
"class Solution:\n",
" def containsDuplicate(self, nums: List[int]) -> bool:\n",
" return not (len(set(nums)) == len(nums))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class SolutionNeetCode:\n",
" def containsDuplicate(self, nums: List[int]) -> bool:\n",
" hashset = set()\n",
"\n",
" for n in nums:\n",
" if n in hashset:\n",
" return True\n",
" hashset.add(n)\n",
" return False"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"nums = [1, 2, 3, 1]\n",
"\n",
"not (len(set(nums)) == len(nums))"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"nums = [1, 2, 3, 1]\n",
"\n",
"Solution().containsDuplicate(nums)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 242. Valid Anagram\n",
"\n",
"Given two strings s and t, return true if t is an anagram of s, and false otherwise.\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",
"Example 1:\n",
"\n",
"Input: s = \"anagram\", t = \"nagaram\"\n",
"Output: true\n",
"\n",
"Example 2:\n",
"\n",
"Input: s = \"rat\", t = \"car\"\n",
"Output: false\n",
"\n",
"Constraints:\n",
"\n",
" 1 <= s.length, t.length <= 5 * 104\n",
" s and t consist of lowercase English letters.\n",
"\n",
"Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?\n"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": [
"s = \"anagram\"\n",
"t = \"nagaramdsafhjsadlfhj\""
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'a': 3, 'n': 1, 'g': 1, 'r': 1, 'm': 1}\n",
"{'n': 1, 'a': 3, 'g': 1, 'r': 1, 'm': 1}\n"
]
},
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 47,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from itertools import zip_longest\n",
"\n",
"s = \"anagram\"\n",
"t = \"nagaram\"\n",
"\n",
"s_dict = dict()\n",
"t_dict = dict()\n",
"\n",
"for s_char, t_char in zip_longest(s, t):\n",
" s_dict[s_char] = s_dict.get(s_char, 0) + 1\n",
" t_dict[t_char] = t_dict.get(t_char, 0) + 1\n",
"\n",
"print(s_dict)\n",
"print(t_dict)\n",
"\n",
"s_dict == t_dict"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"None\n"
]
}
],
"source": [
"print(s_dict.get(None))"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'nagaramdsafhjsadlfhj'"
]
},
"execution_count": 42,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"t"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 1. Two Sum\n",
"\n",
"Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\n",
"\n",
"You may assume that each input would have exactly one solution, and you may not use the same element twice.\n",
"\n",
"You can return the answer in any order.\n",
"\n",
"Example 1:\n",
"\n",
"Input: nums = [2,7,11,15], target = 9\n",
"Output: [0,1]\n",
"Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].\n",
"\n",
"Example 2:\n",
"\n",
"Input: nums = [3,2,4], target = 6\n",
"Output: [1,2]\n",
"\n",
"Example 3:\n",
"\n",
"Input: nums = [3,3], target = 6\n",
"Output: [0,1]\n"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {},
"outputs": [],
"source": [
"from typing import List\n",
"\n",
"\n",
"class Solution:\n",
" def twoSum(self, nums: List[int], target: int) -> List[int]:\n",
" prevMap = {} # val -> index\n",
"\n",
" for i, n in enumerate(nums):\n",
" diff = target - n\n",
" if diff in prevMap:\n",
" return [prevMap[diff], i]\n",
" prevMap[n] = i"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[0, 1]"
]
},
"execution_count": 52,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"nums = [2, 7, 11, 5]\n",
"\n",
"target = 9\n",
"\n",
"Solution().twoSum(nums, target)"
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{3: 0, 2: 1, 4: 2}\n",
"[1, 2]\n"
]
}
],
"source": [
"nums_2 = [3, 2, 4]\n",
"target_2 = 6\n",
"\n",
"data = {k: v for v, k in enumerate(nums_2)}\n",
"print(data)\n",
"\n",
"\n",
"def find_two_sum(data, target):\n",
" for key, current_index in data.items():\n",
" difference = target - key\n",
" try:\n",
" found_index = data[difference]\n",
" if found_index == current_index:\n",
" # no match found -- continue looking\n",
" continue\n",
" return [current_index, found_index]\n",
" except KeyError:\n",
" # i guess uncessary because we have been told that a solution is guaranteed. \n",
" print(\"no index found\")\n",
" except Exception as e:\n",
" print(\"some other error\")\n",
"\n",
"\n",
"print(find_two_sum(data, target_2))"
]
},
{
"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",
" \n",
"\n",
"Example 1:\n",
"\n",
"Input: strs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]\n",
"Output: [[\"bat\"],[\"nat\",\"tan\"],[\"ate\",\"eat\",\"tea\"]]\n",
"\n",
"Example 2:\n",
"\n",
"Input: strs = [\"\"]\n",
"Output: [[\"\"]]\n",
"\n",
"Example 3:\n",
"\n",
"Input: strs = [\"a\"]\n",
"Output: [[\"a\"]]\n"
]
},
{
"cell_type": "code",
"execution_count": 72,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[['eat'], ['tea'], ['tan'], ['ate'], ['nat'], ['bat']]"
]
},
"execution_count": 72,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"strs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]\n",
"\n",
"output = []\n",
"for word in strs:\n",
" # check if anagram in output and if so append to that array \n",
" for \n",
" # can't think of how to do this without doing another double for loop! \n",
"\n",
" # if no anagram found then append\n",
" output.append([word])\n",
"\n",
"# [\"eat\"] in output\n",
"output"
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"dict_values([['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']])"
]
},
"execution_count": 76,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from collections import defaultdict\n",
"\n",
"class Solution:\n",
" def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n",
" ans = defaultdict(list)\n",
"\n",
" for s in strs:\n",
" count = [0] * 26\n",
" for c in s:\n",
" count[ord(c) - ord(\"a\")] += 1\n",
" # this maps the characters to values to check for anagram \n",
" ans[tuple(count)].append(s)\n",
" return ans.values()\n",
"\n",
"Solution().groupAnagrams(strs)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 347. Top K Frequent Elements\n",
"\n",
"Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.\n",
"\n",
" \n",
"\n",
"Example 1:\n",
"\n",
"Input: nums = [1,1,1,2,2,3], k = 2\n",
"Output: [1,2]\n",
"\n",
"Example 2:\n",
"\n",
"Input: nums = [1], k = 1\n",
"Output: [1]\n",
"\n",
" \n",
"\n",
"Constraints:\n",
"\n",
" 1 <= nums.length <= 105\n",
" -104 <= nums[i] <= 104\n",
" k is in the range [1, the number of unique elements in the array].\n",
" It is guaranteed that the answer is unique.\n",
"\n",
" \n",
"\n",
"Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.\n"
]
},
{
"cell_type": "code",
"execution_count": 80,
"metadata": {},
"outputs": [],
"source": [
"nums = [1,1,1,2,2,3] \n",
"k = 2\n",
"\n",
"from collections import OrderedDict\n",
"\n",
"# foo = OrderedDict()\n",
"foo = {}\n",
"\n",
"for number in nums:\n",
" foo[number] = foo.get(number, 0) + 1\n",
"\n",
"# neetcode says using a heap and popping off the top k elements would be k log(n) time too \n",
" \n"
]
},
{
"cell_type": "code",
"execution_count": 81,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{1: 3, 2: 2, 3: 1}"
]
},
"execution_count": 81,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"foo"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 238. Product of Array Except Self\n",
"\n",
"Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].\n",
"\n",
"The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.\n",
"\n",
"You must write an algorithm that runs in O(n) time and without using the division operation.\n",
"\n",
" \n",
"\n",
"Example 1:\n",
"\n",
"Input: nums = [1,2,3,4]\n",
"Output: [24,12,8,6]\n",
"\n",
"Example 2:\n",
"\n",
"Input: nums = [-1,1,0,-3,3]\n",
"Output: [0,0,9,0,0]\n",
"\n",
" \n",
"\n",
"Constraints:\n",
"\n",
" 2 <= nums.length <= 105\n",
" -30 <= nums[i] <= 30\n",
" The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.\n",
"\n",
" \n",
"\n",
"Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)\n"
]
},
{
"cell_type": "code",
"execution_count": 88,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"None\n",
"None\n",
"None\n",
"None\n"
]
},
{
"data": {
"text/plain": [
"[24, 12, 8, 6]"
]
},
"execution_count": 88,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import math \n",
"\n",
"nums = [1,2,3,4]\n",
"output = [24,12,8,6]\n",
"\n",
"math.prod(nums) \n",
"\n",
"output_2 = []\n",
"for value in nums: \n",
" print(output_2.append(int(math.prod(nums) * (1.0/value))))\n",
"\n",
"output_2"
]
},
{
"cell_type": "code",
"execution_count": 93,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 3, 4]"
]
},
"execution_count": 93,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# could concatenate arrays like this and then add them up? \n",
"nums[0:1] + nums[2:]\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# MLE Flashcards problem \n",
"\n",
"Solve fib(n) using dynamic programming of memoization and tabulation\n"
]
},
{
"cell_type": "code",
"execution_count": 111,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The 5-th Fibonacci number is: 5\n"
]
}
],
"source": [
"# def fib_memoized(n, memo={}):\n",
"# if n == 0 or n == 1:\n",
"# return n \n",
" \n",
"# if n not in memo:\n",
"# memo[n] = fib_memoized(n-1, memo) + fib_memoized(n-2, memo)\n",
"\n",
"# return memo\n",
" \n",
"# # memoization = {}\n",
"# fib_memoized(22)\n",
"# memoization\n",
"\n",
"# this shit is crazyyyy ! \n",
"def fib_n(n, memo={}):\n",
" # Check if the result is already memoized\n",
" if n in memo:\n",
" return memo[n]\n",
" \n",
" # Base cases\n",
" if n == 0:\n",
" result = 0\n",
" elif n == 1:\n",
" result = 1\n",
" else:\n",
" # Recursive calls with memoization\n",
" result = fib_n(n - 1, memo) + fib_n(n - 2, memo)\n",
" \n",
" # Memoize the result before returning\n",
" memo[n] = result\n",
" return result\n",
"\n",
"# # Example usage\n",
"n = 5\n",
"result = fib_n(n)\n",
"print(f\"The {n}-th Fibonacci number is: {result}\")\n"
]
},
{
"cell_type": "code",
"execution_count": 110,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The 5-th Fibonacci number is: 5\n"
]
}
],
"source": [
"def fib_n(n):\n",
" # Base cases\n",
" if n == 0:\n",
" return 0\n",
" elif n == 1:\n",
" return 1\n",
" \n",
" # Create a table to store Fibonacci numbers\n",
" fib_table = [0] * (n + 1)\n",
" \n",
" # Initialize the base cases\n",
" fib_table[0] = 0\n",
" fib_table[1] = 1\n",
" \n",
" # Fill in the table using bottom-up approach\n",
" for i in range(2, n + 1):\n",
" fib_table[i] = fib_table[i - 1] + fib_table[i - 2]\n",
" \n",
" # The result is the value at index n\n",
" return fib_table[n]\n",
"\n",
"# Example usage\n",
"n = 5\n",
"result = fib_n(n)\n",
"print(f\"The {n}-th Fibonacci number is: {result}\")\n"
]
},
{
"cell_type": "code",
"execution_count": 112,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"13 is a prime number.\n"
]
}
],
"source": [
"def is_prime(n):\n",
" if n <= 1:\n",
" return False\n",
" elif n == 2:\n",
" return True\n",
" elif n % 2 == 0:\n",
" return False\n",
" else:\n",
" # Check for factors up to the square root of n\n",
" for i in range(3, int(n**0.5) + 1, 2):\n",
" if n % i == 0:\n",
" return False\n",
" return True\n",
"\n",
"# Example usage\n",
"number = 13\n",
"if is_prime(number):\n",
" print(f\"{number} is a prime number.\")\n",
"else:\n",
" print(f\"{number} is not a prime number.\")\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "pytorch_m1",
"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.8.13"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
|