├── 01_Recursion ├── Recursion-1_Problems.ipynb ├── Recursion-1_Quiz.pdf ├── Recursion-2_Problems.ipynb └── Recursion_Assignment.ipynb ├── 02_OOP ├── Content_Exception-Handling.ipynb ├── Content_OOP.ipynb ├── Quiz_OOP-1.pdf ├── Quiz_OOP-2.pdf └── Quiz_OOP-3.pdf ├── 03_Complexity-Analysis ├── Problems_Applications_of_Complexity_Analysis.ipynb ├── Quiz_Space-Complexity-Analysis.pdf └── Quiz_Time-Complexity-Analysis.pdf ├── 04_Linked-List ├── Linked-List-1 │ ├── Content_Linked_List_1.ipynb │ ├── Problems_Linked_List_1.ipynb │ └── Quiz_Linked-List-1.pdf └── Linked-List-2 │ ├── Assignment_Problems_Linked_List_2.ipynb │ ├── Content_Problems_Linked_List_2.ipynb │ └── Quiz_Linked-List-2.pdf ├── 05_Stacks-Queues ├── 01_Stacks │ ├── Problems_Stacks.ipynb │ └── Quiz_Stacks.pdf └── 02_Queues │ ├── Problems_Queues.ipynb │ └── Quiz_Queues.pdf ├── 06_Binary-Trees ├── Binary-Trees-1 │ ├── Problems_Binary_Trees_1.ipynb │ └── Quiz_Binary-Trees-1.pdf └── Binary-Trees-2 │ ├── Assignment_Problems_Binary_Trees_2.ipynb │ ├── Content_Problems_Binary_Trees_2.ipynb │ └── Quiz_Binary-Trees-2.pdf ├── 07_Binary-Search-Tree ├── Binary-Search-Trees-1 │ ├── Problems_Binary_Search_Tree_1.ipynb │ └── Quiz_Binary-Search-Tree-1.pdf └── Binary-Search-Trees-2 │ ├── Problems_Binary_Search_Tree_2.ipynb │ └── Quiz_Binary-Search-Tree-2.pdf ├── README.md ├── Test-1 └── Test_1.ipynb └── Test-2 └── Test_2.ipynb /01_Recursion/Recursion-1_Problems.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "Problems_Recursion-1", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "source": [ 22 | "**CONTENT PROBLEMS**" 23 | ], 24 | "metadata": { 25 | "id": "-nXohosiAK-g" 26 | } 27 | }, 28 | { 29 | "cell_type": "code", 30 | "source": [ 31 | "'''\n", 32 | "Write a program to find x to the power n (i.e. x^n). Take x and n from the user. You need to print the answer.\n", 33 | "Note : For this question, you can assume that 0 raised to the power of 0 is 1\n", 34 | "\n", 35 | "Input format :\n", 36 | "Two integers x and n (separated by space)\n", 37 | "\n", 38 | "Output Format :\n", 39 | "x^n (i.e. x raise to the power n)\n", 40 | "'''\n", 41 | "\n", 42 | "def pow(x,n):\n", 43 | " if n==0:\n", 44 | " return 1\n", 45 | " return x * pow(x,n-1)\n", 46 | "\n", 47 | "x, n = input().split()\n", 48 | "x = int(x)\n", 49 | "n = int(n)\n", 50 | "print(x, 'power', n, '=', pow(x,n))" 51 | ], 52 | "metadata": { 53 | "colab": { 54 | "base_uri": "https://localhost:8080/" 55 | }, 56 | "id": "IwHB44s1-Zwt", 57 | "outputId": "a226fde5-b290-4a3a-9dc6-3e92a89e162c" 58 | }, 59 | "execution_count": null, 60 | "outputs": [ 61 | { 62 | "output_type": "stream", 63 | "name": "stdout", 64 | "text": [ 65 | "2 5\n", 66 | "2 power 5 = 32\n" 67 | ] 68 | } 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "source": [ 74 | "'''\n", 75 | "Given an array of length N, you need to find and return the sum of all elements of the array.Do this recursively.\n", 76 | "\n", 77 | "Input Format :\n", 78 | "Line 1 : An Integer N i.e. size of array\n", 79 | "Line 2 : N integers which are elements of the array, separated by spaces\n", 80 | "\n", 81 | "Output Format :\n", 82 | "Sum\n", 83 | "\n", 84 | "Sample Input 1 :\n", 85 | "3\n", 86 | "9 8 9\n", 87 | "\n", 88 | "Sample Output 1 :\n", 89 | "26\n", 90 | "'''\n", 91 | "\n", 92 | "\n", 93 | "def sumArray(arr, start_index):\n", 94 | " length = len(arr)\n", 95 | " if start_index==length-1:\n", 96 | " return arr[start_index] \n", 97 | " return arr[start_index] + sumArray(arr,start_index+1)\n", 98 | "\n", 99 | "\n", 100 | "from sys import setrecursionlimit\n", 101 | "setrecursionlimit(11000)\n", 102 | "n=int(input())\n", 103 | "arr=list(int(i) for i in input().strip().split(' '))\n", 104 | "start_index = 0\n", 105 | "print(sumArray(arr, start_index))\n" 106 | ], 107 | "metadata": { 108 | "colab": { 109 | "base_uri": "https://localhost:8080/" 110 | }, 111 | "id": "bH-IMvhBIRQd", 112 | "outputId": "2d3e427e-9643-4cdc-b21a-c4566acde00a" 113 | }, 114 | "execution_count": null, 115 | "outputs": [ 116 | { 117 | "output_type": "stream", 118 | "name": "stdout", 119 | "text": [ 120 | "5\n", 121 | "1 2 1 3 1\n", 122 | "8\n" 123 | ] 124 | } 125 | ] 126 | }, 127 | { 128 | "cell_type": "code", 129 | "source": [ 130 | "'''\n", 131 | "Given an array of length N and an integer x, you need to find if x is present in the array or not. Return true or false. Do this recursively.\n", 132 | "\n", 133 | "Input Format :\n", 134 | "Line 1 : An Integer N i.e. size of array\n", 135 | "Line 2 : N integers which are elements of the array, separated by spaces\n", 136 | "Line 3 : Integer x\n", 137 | "\n", 138 | "Output Format :\n", 139 | "'true' or 'false'\n", 140 | "'''\n", 141 | "\n", 142 | "def checkNumber(arr,x,index):\n", 143 | " length = len(arr)\n", 144 | " if arr[index]==x:\n", 145 | " return True\n", 146 | " elif index == length-1:\n", 147 | " return False\n", 148 | " else:\n", 149 | " \treturn checkNumber(arr,x,index+1)\n", 150 | "\n", 151 | "from sys import setrecursionlimit\n", 152 | "setrecursionlimit(11000)\n", 153 | "n=int(input())\n", 154 | "arr=list(int(i) for i in input().strip().split(' '))\n", 155 | "x=int(input())\n", 156 | "index = 0\n", 157 | "if checkNumber(arr,x,index):\n", 158 | " print('true')\n", 159 | "else:\n", 160 | " print('false')" 161 | ], 162 | "metadata": { 163 | "colab": { 164 | "base_uri": "https://localhost:8080/" 165 | }, 166 | "id": "DD8vhlGbJJvE", 167 | "outputId": "33e0269b-e0b1-49e6-bb37-06fe2d78ecfd" 168 | }, 169 | "execution_count": null, 170 | "outputs": [ 171 | { 172 | "output_type": "stream", 173 | "name": "stdout", 174 | "text": [ 175 | "5\n", 176 | "1 5 6 8 9\n", 177 | "6\n", 178 | "true\n" 179 | ] 180 | } 181 | ] 182 | }, 183 | { 184 | "cell_type": "code", 185 | "source": [ 186 | "'''\n", 187 | "First Index of Number \n", 188 | "\n", 189 | "Given an array of length N and an integer x, you need to find and return the first index of integer x present in the array. Return -1 if it is not present in the array.\n", 190 | "First index means, the index of first occurrence of x in the input array. Do this recursively. Indexing in the array starts from 0.\n", 191 | "\n", 192 | "Input Format :\n", 193 | "Line 1 : An Integer N i.e. size of array\n", 194 | "Line 2 : N integers which are elements of the array, separated by spaces\n", 195 | "Line 3 : Integer x\n", 196 | "\n", 197 | "Output Format :\n", 198 | "first index or -1\n", 199 | "\n", 200 | "Sample Input :\n", 201 | "4\n", 202 | "9 8 10 8\n", 203 | "8\n", 204 | "\n", 205 | "Sample Output :\n", 206 | "1\n", 207 | "'''\n", 208 | "\n", 209 | "def firstIndex(arr, x, index):\n", 210 | " length = len(arr)\n", 211 | " \n", 212 | " if(index==length):\n", 213 | " return -1\n", 214 | "\n", 215 | " if(arr[index]==x):\n", 216 | " return index\n", 217 | "\n", 218 | " return firstIndex(arr, x, index+1)\n", 219 | " \n", 220 | "from sys import setrecursionlimit\n", 221 | "setrecursionlimit(11000)\n", 222 | "n=int(input())\n", 223 | "arr=list(int(i) for i in input().strip().split(' '))\n", 224 | "x=int(input())\n", 225 | "index = 0\n", 226 | "print(firstIndex(arr, x, index))" 227 | ], 228 | "metadata": { 229 | "colab": { 230 | "base_uri": "https://localhost:8080/" 231 | }, 232 | "id": "h615sYRuxtN4", 233 | "outputId": "07e058ac-ae60-44fc-ee9c-059fc3f6197e" 234 | }, 235 | "execution_count": null, 236 | "outputs": [ 237 | { 238 | "output_type": "stream", 239 | "name": "stdout", 240 | "text": [ 241 | "5\n", 242 | "2 5 6 3 8\n", 243 | "6\n", 244 | "2\n" 245 | ] 246 | } 247 | ] 248 | }, 249 | { 250 | "cell_type": "code", 251 | "source": [ 252 | "'''\n", 253 | "Last Index Of Number Question\n", 254 | "\n", 255 | "Given an array of length N and an integer x, you need to find and return the last index of integer x present in the array. Return -1 if it is not present in the array.\n", 256 | "Last index means - if x is present multiple times in the array, return the index at which x comes last in the array. You should start traversing your array from 0, not from (N - 1).\n", 257 | "Do this recursively. Indexing in the array starts from 0.\n", 258 | "\n", 259 | "Input Format :\n", 260 | "Line 1 : An Integer N i.e. size of array\n", 261 | "Line 2 : N integers which are elements of the array, separated by spaces\n", 262 | "Line 3 : Integer x\n", 263 | "\n", 264 | "Output Format :\n", 265 | "last index or -1\n", 266 | "\n", 267 | "Sample Input :\n", 268 | "4\n", 269 | "9 8 10 8\n", 270 | "8\n", 271 | "\n", 272 | "Sample Output :\n", 273 | "3\n", 274 | "'''\n", 275 | "\n", 276 | "def lastIndex(arr, x, index):\n", 277 | " length = len(arr)\n", 278 | " \n", 279 | " if(index==length):\n", 280 | " return -1\n", 281 | " \n", 282 | " temp = lastIndex(arr, x, index+1)\n", 283 | "\n", 284 | " if temp!=-1:\n", 285 | " return temp\n", 286 | " else:\n", 287 | " if arr[index]==x:\n", 288 | " return index\n", 289 | " else:\n", 290 | " return -1\n", 291 | " \n", 292 | "from sys import setrecursionlimit\n", 293 | "setrecursionlimit(11000)\n", 294 | "n=int(input())\n", 295 | "arr=list(int(i) for i in input().strip().split(' '))\n", 296 | "x=int(input())\n", 297 | "index = 0\n", 298 | "print(lastIndex(arr, x, index))" 299 | ], 300 | "metadata": { 301 | "colab": { 302 | "base_uri": "https://localhost:8080/" 303 | }, 304 | "id": "cqONyctb0pqi", 305 | "outputId": "d73d0d6e-9033-464c-c75c-e3d500830d62" 306 | }, 307 | "execution_count": null, 308 | "outputs": [ 309 | { 310 | "output_type": "stream", 311 | "name": "stdout", 312 | "text": [ 313 | "5\n", 314 | "1 2 3 2 5\n", 315 | "2\n", 316 | "3\n" 317 | ] 318 | } 319 | ] 320 | }, 321 | { 322 | "cell_type": "markdown", 323 | "source": [ 324 | "**CONTENT**" 325 | ], 326 | "metadata": { 327 | "id": "Ezd99hq4Awj2" 328 | } 329 | }, 330 | { 331 | "cell_type": "code", 332 | "execution_count": null, 333 | "metadata": { 334 | "colab": { 335 | "base_uri": "https://localhost:8080/" 336 | }, 337 | "id": "SbIW5wK_6krK", 338 | "outputId": "8cc026ed-ef93-4956-e4f6-258f174643ad" 339 | }, 340 | "outputs": [ 341 | { 342 | "name": "stdout", 343 | "output_type": "stream", 344 | "text": [ 345 | "5\n" 346 | ] 347 | }, 348 | { 349 | "output_type": "execute_result", 350 | "data": { 351 | "text/plain": [ 352 | "120" 353 | ] 354 | }, 355 | "metadata": {}, 356 | "execution_count": 1 357 | } 358 | ], 359 | "source": [ 360 | "# Factorial\n", 361 | "\n", 362 | "def fact(n):\n", 363 | " if n == 0:\n", 364 | " return 1\n", 365 | " return n*fact(n-1)\n", 366 | "\n", 367 | "n = int(input())\n", 368 | "fact(n)" 369 | ] 370 | }, 371 | { 372 | "cell_type": "code", 373 | "source": [ 374 | "# Sum to first N natural numbers\n", 375 | "\n", 376 | "def sum(n):\n", 377 | " if n == 0:\n", 378 | " return 0\n", 379 | " return n + sum(n-1)\n", 380 | "\n", 381 | "n = int(input())\n", 382 | "print('Sum = ', sum(n))" 383 | ], 384 | "metadata": { 385 | "colab": { 386 | "base_uri": "https://localhost:8080/" 387 | }, 388 | "id": "nLK5McXU8ecY", 389 | "outputId": "b046eb87-0524-4192-b180-c79d6d686424" 390 | }, 391 | "execution_count": null, 392 | "outputs": [ 393 | { 394 | "output_type": "stream", 395 | "name": "stdout", 396 | "text": [ 397 | "4\n", 398 | "Sum = 10\n" 399 | ] 400 | } 401 | ] 402 | }, 403 | { 404 | "cell_type": "code", 405 | "source": [ 406 | "# Print 1 to n\n", 407 | "def print_1to_n(n):\n", 408 | " if n==0 :\n", 409 | " return\n", 410 | " print_1to_n(n-1)\n", 411 | " print(n)\n", 412 | "\n", 413 | "n = int(input())\n", 414 | "print_1to_n(n)" 415 | ], 416 | "metadata": { 417 | "colab": { 418 | "base_uri": "https://localhost:8080/" 419 | }, 420 | "id": "ts_eIAq3_zSN", 421 | "outputId": "2d541ef3-769d-4f6b-c8ed-b8354d625450" 422 | }, 423 | "execution_count": null, 424 | "outputs": [ 425 | { 426 | "output_type": "stream", 427 | "name": "stdout", 428 | "text": [ 429 | "10\n", 430 | "1\n", 431 | "2\n", 432 | "3\n", 433 | "4\n", 434 | "5\n", 435 | "6\n", 436 | "7\n", 437 | "8\n", 438 | "9\n", 439 | "10\n" 440 | ] 441 | } 442 | ] 443 | }, 444 | { 445 | "cell_type": "code", 446 | "source": [ 447 | "# Print n to 1\n", 448 | "def print_nto_1(n):\n", 449 | " if n==0 :\n", 450 | " return\n", 451 | " print(n)\n", 452 | " print_nto_1(n-1)\n", 453 | "\n", 454 | "n = int(input())\n", 455 | "print_nto_1(n)" 456 | ], 457 | "metadata": { 458 | "colab": { 459 | "base_uri": "https://localhost:8080/" 460 | }, 461 | "id": "-Kmibn3RCcw8", 462 | "outputId": "c568d645-4d8f-47a5-a5da-30386607b4f0" 463 | }, 464 | "execution_count": null, 465 | "outputs": [ 466 | { 467 | "output_type": "stream", 468 | "name": "stdout", 469 | "text": [ 470 | "10\n", 471 | "10\n", 472 | "9\n", 473 | "8\n", 474 | "7\n", 475 | "6\n", 476 | "5\n", 477 | "4\n", 478 | "3\n", 479 | "2\n", 480 | "1\n" 481 | ] 482 | } 483 | ] 484 | }, 485 | { 486 | "cell_type": "code", 487 | "source": [ 488 | "# Fibonacci nth term\n", 489 | "def fibo(n):\n", 490 | " if n==1 or n==2:\n", 491 | " return 1\n", 492 | " return fibo(n-1) + fibo(n-2)\n", 493 | "\n", 494 | "n = int(input())\n", 495 | "print(fibo(n))" 496 | ], 497 | "metadata": { 498 | "colab": { 499 | "base_uri": "https://localhost:8080/" 500 | }, 501 | "id": "J_2wdl6ytiqa", 502 | "outputId": "ee369da1-2f9a-49a5-e009-01004b3400b1" 503 | }, 504 | "execution_count": null, 505 | "outputs": [ 506 | { 507 | "output_type": "stream", 508 | "name": "stdout", 509 | "text": [ 510 | "4\n", 511 | "3\n" 512 | ] 513 | } 514 | ] 515 | }, 516 | { 517 | "cell_type": "code", 518 | "source": [ 519 | "# Check if the list is sorted or not\n", 520 | "\n", 521 | "def sorted(lst, start_index):\n", 522 | " length = len(lst)\n", 523 | " if (start_index == length-1) or (start_index == length):\n", 524 | " return True\n", 525 | "\n", 526 | " if lst[start_index] > lst[start_index+1]:\n", 527 | " return False\n", 528 | " else:\n", 529 | " return sorted(lst, start_index+1)\n", 530 | "\n", 531 | "lst = [1,2,3,4,5,9]\n", 532 | "start_index = 0\n", 533 | "print(sorted(lst,start_index)) " 534 | ], 535 | "metadata": { 536 | "colab": { 537 | "base_uri": "https://localhost:8080/" 538 | }, 539 | "id": "M1ydyvsGD5b_", 540 | "outputId": "5596febd-348e-40e4-e223-599b53519856" 541 | }, 542 | "execution_count": null, 543 | "outputs": [ 544 | { 545 | "output_type": "stream", 546 | "name": "stdout", 547 | "text": [ 548 | "True\n" 549 | ] 550 | } 551 | ] 552 | } 553 | ] 554 | } -------------------------------------------------------------------------------- /01_Recursion/Recursion-1_Quiz.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddhapuraharsh/Data-Structures_Algorithms_Coding-Ninjas_Full-Course/149411eb7d59abd80d2a65f0ff1039b62558bb1b/01_Recursion/Recursion-1_Quiz.pdf -------------------------------------------------------------------------------- /01_Recursion/Recursion-2_Problems.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "Problems_Recursion-2", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "source": [ 22 | "**CONTENT PROBLEMS**" 23 | ], 24 | "metadata": { 25 | "id": "uYZBbirmBZVh" 26 | } 27 | }, 28 | { 29 | "cell_type": "code", 30 | "source": [ 31 | "'''\n", 32 | "Remove X\n", 33 | "Given a string, compute recursively a new string where all 'x' chars have been removed.\n", 34 | "\n", 35 | "Input format :\n", 36 | "String S\n", 37 | "\n", 38 | "Output format :\n", 39 | "Modified String\n", 40 | "\n", 41 | "Sample Input 1 :\n", 42 | "xaxb\n", 43 | "Sample Output 1:\n", 44 | "ab\n", 45 | "\n", 46 | "Sample Input 2 :\n", 47 | "abc\n", 48 | "Sample Output 2:\n", 49 | "abc\n", 50 | "'''\n", 51 | "\n", 52 | "def removeX(string): \n", 53 | " if len(string)==0 :\n", 54 | " return string\n", 55 | " \n", 56 | " if string[0]=='x' :\n", 57 | " return removeX(string[1:])\n", 58 | " else:\n", 59 | " return string[0] + removeX(string[1:])\n", 60 | "\n", 61 | "string = input()\n", 62 | "print(removeX(string))" 63 | ], 64 | "metadata": { 65 | "colab": { 66 | "base_uri": "https://localhost:8080/" 67 | }, 68 | "id": "LRj0ow1yIyew", 69 | "outputId": "75351b7f-9819-43af-ec01-d9bb8ea56c8b" 70 | }, 71 | "execution_count": null, 72 | "outputs": [ 73 | { 74 | "output_type": "stream", 75 | "name": "stdout", 76 | "text": [ 77 | "xghxxxxhggfxxx\n", 78 | "ghhggf\n" 79 | ] 80 | } 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "source": [ 86 | "'''\n", 87 | "Remove Duplicates Recursively\n", 88 | "\n", 89 | "Given a string S, remove consecutive duplicates from it recursively.\n", 90 | "\n", 91 | "Input Format :\n", 92 | "String S\n", 93 | "Output Format :\n", 94 | "Output string\n", 95 | "\n", 96 | "Sample Input 1 :\n", 97 | "aabccba\n", 98 | "Sample Output 1 :\n", 99 | "abcba\n", 100 | "\n", 101 | "Sample Input 2 :\n", 102 | "xxxyyyzwwzzz\n", 103 | "Sample Output 2 :\n", 104 | "xyzwz\n", 105 | "'''\n", 106 | "\n", 107 | "def removeConsecutiveDuplicates(string):\n", 108 | " if len(string)<2:\n", 109 | " return string\n", 110 | " \n", 111 | " if string[0]==string[1]:\n", 112 | " return removeConsecutiveDuplicates(string[1:])\n", 113 | " else:\n", 114 | " return string[0] + removeConsecutiveDuplicates(string[1:])\n", 115 | "\n", 116 | "string = input().strip()\n", 117 | "print(removeConsecutiveDuplicates(string))" 118 | ], 119 | "metadata": { 120 | "colab": { 121 | "base_uri": "https://localhost:8080/" 122 | }, 123 | "id": "nE4CPY_9PZAI", 124 | "outputId": "58877e12-d61c-47c1-b91f-31faa453307a" 125 | }, 126 | "execution_count": null, 127 | "outputs": [ 128 | { 129 | "output_type": "stream", 130 | "name": "stdout", 131 | "text": [ 132 | "aaaabcccdefggggghhjik\n", 133 | "abcdefghjik\n" 134 | ] 135 | } 136 | ] 137 | }, 138 | { 139 | "cell_type": "code", 140 | "source": [ 141 | "'''\n", 142 | "Merge Sort Code\n", 143 | "\n", 144 | "Sort an array A using Merge Sort.\n", 145 | "Change in the input array itself. So no need to return or print anything.\n", 146 | "\n", 147 | "Input format :\n", 148 | "Line 1 : Integer n i.e. Array size\n", 149 | "Line 2 : Array elements (separated by space)\n", 150 | "Output format :\n", 151 | "Array elements in increasing order (separated by space)\n", 152 | "\n", 153 | "Constraints :\n", 154 | "1 <= n <= 10^3\n", 155 | "\n", 156 | "Sample Input 1 :\n", 157 | "6 \n", 158 | "2 6 8 5 4 3\n", 159 | "Sample Output 1 :\n", 160 | "2 3 4 5 6 8\n", 161 | "\n", 162 | "Sample Input 2 :\n", 163 | "5\n", 164 | "2 1 5 2 3\n", 165 | "Sample Output 2 :\n", 166 | "1 2 2 3 5 \n", 167 | "'''\n", 168 | "\n", 169 | "# Merge Sort using Recursion\n", 170 | "\n", 171 | "def merge(arr1, arr2, arr):\n", 172 | " i,j,k = 0,0,0\n", 173 | " \n", 174 | " while i=pivot:\n", 282 | " j -= 1\n", 283 | " else:\n", 284 | " arr[i], arr[j] = arr[j], arr[i]\n", 285 | " i += 1\n", 286 | " j -= 1\n", 287 | " return pivot_index\n", 288 | "\n", 289 | "def quickSort(arr, start, end):\n", 290 | " if start>=end:\n", 291 | " return \n", 292 | " \n", 293 | " pivot_index = partition(arr, start, end)\n", 294 | " quickSort(arr, start, pivot_index-1)\n", 295 | " quickSort(arr, pivot_index+1, end)\n", 296 | " \n", 297 | "n=int(input())\n", 298 | "arr=list(int(i) for i in input().strip().split(' '))\n", 299 | "quickSort(arr, 0, n-1)\n", 300 | "print(*arr)" 301 | ], 302 | "metadata": { 303 | "id": "-E4oYw5i_hfn", 304 | "colab": { 305 | "base_uri": "https://localhost:8080/" 306 | }, 307 | "outputId": "11165172-52f8-4089-dc6f-98a2176ab22e" 308 | }, 309 | "execution_count": null, 310 | "outputs": [ 311 | { 312 | "output_type": "stream", 313 | "name": "stdout", 314 | "text": [ 315 | "10\n", 316 | "2 5 6 9 8 7 1 5 4 3\n", 317 | "1 2 3 4 5 5 6 7 8 9\n" 318 | ] 319 | } 320 | ] 321 | }, 322 | { 323 | "cell_type": "code", 324 | "source": [ 325 | "'''\n", 326 | "Tower Of Hanoi - Problem\n", 327 | "Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move all disks from source rod to destination rod using third rod (say auxiliary). The rules are :\n", 328 | "1) Only one disk can be moved at a time.\n", 329 | "2) A disk can be moved only if it is on the top of a rod.\n", 330 | "3) No disk can be placed on the top of a smaller disk.\n", 331 | "\n", 332 | "Print the steps required to move n disks from source rod to destination rod.\n", 333 | "Source Rod is named as 'a', auxiliary rod as 'b' and destination rod as 'c'.\n", 334 | "\n", 335 | "Input Format :\n", 336 | "Integer n\n", 337 | "Output Format :\n", 338 | "Steps in different lines (in one line print source and destination rod name separated by space)\n", 339 | "\n", 340 | "Constraints :\n", 341 | "0 <= n <= 20\n", 342 | "\n", 343 | "Sample Input 1 :\n", 344 | "2\n", 345 | "Sample Output 1 :\n", 346 | "a b\n", 347 | "a c\n", 348 | "b c\n", 349 | "\n", 350 | "Sample Input 2 :\n", 351 | "3\n", 352 | "Sample Output 2 :\n", 353 | "a c\n", 354 | "a b\n", 355 | "c b\n", 356 | "a c\n", 357 | "b a\n", 358 | "b c\n", 359 | "a c\n", 360 | "'''\n", 361 | "\n", 362 | "def towerofhanoi(n, source, aux, dest):\n", 363 | " if n==0 :\n", 364 | " return\n", 365 | " \n", 366 | " if n==1 :\n", 367 | " print(source, ' ', dest)\n", 368 | " return\n", 369 | " \n", 370 | " towerofhanoi(n-1, source, dest, aux)\n", 371 | " print(source, ' ', dest)\n", 372 | " towerofhanoi(n-1, aux, source, dest)\n", 373 | "\n", 374 | "n=int(input())\n", 375 | "towerofhanoi(n, 'a', 'b', 'c')" 376 | ], 377 | "metadata": { 378 | "colab": { 379 | "base_uri": "https://localhost:8080/" 380 | }, 381 | "id": "nOnPpO8nUsib", 382 | "outputId": "2e844129-04a9-4ef2-b09b-f6456a464f62" 383 | }, 384 | "execution_count": null, 385 | "outputs": [ 386 | { 387 | "output_type": "stream", 388 | "name": "stdout", 389 | "text": [ 390 | "4\n", 391 | "a b\n", 392 | "a c\n", 393 | "b c\n", 394 | "a b\n", 395 | "c a\n", 396 | "c b\n", 397 | "a b\n", 398 | "a c\n", 399 | "b c\n", 400 | "b a\n", 401 | "c a\n", 402 | "b c\n", 403 | "a b\n", 404 | "a c\n", 405 | "b c\n" 406 | ] 407 | } 408 | ] 409 | }, 410 | { 411 | "cell_type": "markdown", 412 | "source": [ 413 | "**CONTENT**" 414 | ], 415 | "metadata": { 416 | "id": "MYjwnL9tCYeD" 417 | } 418 | }, 419 | { 420 | "cell_type": "code", 421 | "execution_count": null, 422 | "metadata": { 423 | "colab": { 424 | "base_uri": "https://localhost:8080/" 425 | }, 426 | "id": "cTr4Hx00-EDt", 427 | "outputId": "47eb586e-7646-48cd-da89-ec8e988c113f" 428 | }, 429 | "outputs": [ 430 | { 431 | "output_type": "stream", 432 | "name": "stdout", 433 | "text": [ 434 | "gggjkiogggkijgklo\n", 435 | "g\n", 436 | "x\n", 437 | "xxxjkioxxxkijxklo\n" 438 | ] 439 | } 440 | ], 441 | "source": [ 442 | "# Replace all a by b\n", 443 | "\n", 444 | "def replaceChar(string, a ,b):\n", 445 | "\n", 446 | " if len(string)==0 :\n", 447 | " return string\n", 448 | "\n", 449 | " if string[0]==a :\n", 450 | " return b + replaceChar(string[1:], a, b)\n", 451 | " else:\n", 452 | " return string[0] + replaceChar(string[1:], a, b)\n", 453 | "\n", 454 | "string = input()\n", 455 | "a = input()\n", 456 | "b = input()\n", 457 | "print(replaceChar(string, a, b))" 458 | ] 459 | }, 460 | { 461 | "cell_type": "code", 462 | "source": [ 463 | "# Replace 'pi' with 3.14\n", 464 | "\n", 465 | "def replacePi(string):\n", 466 | " if len(string)==0 or len(string)==1 :\n", 467 | " return string\n", 468 | "\n", 469 | " if string[0]=='p' and string[1]=='i' :\n", 470 | " return '3.14' + replacePi(string[2:])\n", 471 | " else:\n", 472 | " return string[0] + replacePi(string[1:])\n", 473 | "\n", 474 | "string = input()\n", 475 | "print(replacePi(string))" 476 | ], 477 | "metadata": { 478 | "colab": { 479 | "base_uri": "https://localhost:8080/" 480 | }, 481 | "id": "DCj8PlBhKufQ", 482 | "outputId": "af9f7db3-9507-4d21-9035-1e796aea979d" 483 | }, 484 | "execution_count": null, 485 | "outputs": [ 486 | { 487 | "output_type": "stream", 488 | "name": "stdout", 489 | "text": [ 490 | "abpicdpiklppi\n", 491 | "ab3.14cd3.14klp3.14\n" 492 | ] 493 | } 494 | ] 495 | }, 496 | { 497 | "cell_type": "code", 498 | "source": [ 499 | "# Binary Search using Recursion\n", 500 | "\n", 501 | "def binarySearch(arr, x, start, end):\n", 502 | " if start>end:\n", 503 | " return -1\n", 504 | "\n", 505 | " mid = (start+end)//2\n", 506 | "\n", 507 | " if arr[mid]==x :\n", 508 | " return mid\n", 509 | " elif arr[mid]>x :\n", 510 | " return binarySearch(arr, x, start, mid-1)\n", 511 | " else:\n", 512 | " return binarySearch(arr, x, mid+1, end)\n", 513 | "\n", 514 | "arr = list(int(i) for i in input().strip().split(' '))\n", 515 | "x = int(input())\n", 516 | "print(binarySearch(arr, x, 0, len(arr)-1))" 517 | ], 518 | "metadata": { 519 | "colab": { 520 | "base_uri": "https://localhost:8080/" 521 | }, 522 | "id": "YsCoxRgHPuQ5", 523 | "outputId": "f5dacde3-5075-4202-fb5c-bb8fc76042aa" 524 | }, 525 | "execution_count": null, 526 | "outputs": [ 527 | { 528 | "output_type": "stream", 529 | "name": "stdout", 530 | "text": [ 531 | "1 5 6 7 9 54 23 69\n", 532 | "5\n", 533 | "1\n" 534 | ] 535 | } 536 | ] 537 | } 538 | ] 539 | } -------------------------------------------------------------------------------- /01_Recursion/Recursion_Assignment.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "Recursion-Assignment", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "source": [ 22 | "**ASSIGNMENT PROBLEMS**" 23 | ], 24 | "metadata": { 25 | "id": "foVv3iJ4Dlc_" 26 | } 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": null, 31 | "metadata": { 32 | "colab": { 33 | "base_uri": "https://localhost:8080/" 34 | }, 35 | "id": "B8_ceMo6CgwQ", 36 | "outputId": "2eff3838-bb73-42dc-c1bc-c2668a8c4e4e" 37 | }, 38 | "outputs": [ 39 | { 40 | "output_type": "stream", 41 | "name": "stdout", 42 | "text": [ 43 | "4\n", 44 | "1.93750\n" 45 | ] 46 | } 47 | ], 48 | "source": [ 49 | "'''\n", 50 | "Geometric Sum\n", 51 | "Given k, find the geometric sum i.e.\n", 52 | "1 + 1/2 + 1/4 + 1/8 + ... + 1/(2^k) using recursion.\n", 53 | "\n", 54 | "Input format :\n", 55 | "Integer k\n", 56 | "Output format :\n", 57 | "Geometric sum (upto 5 decimal places)\n", 58 | "\n", 59 | "Sample Input 1 :\n", 60 | "3\n", 61 | "Sample Output 1 :\n", 62 | "1.87500\n", 63 | "\n", 64 | "Sample Input 2 :\n", 65 | "4\n", 66 | "Sample Output 2 :\n", 67 | "1.93750\n", 68 | "'''\n", 69 | "\n", 70 | "def geo_sum(k):\n", 71 | " if k==0 :\n", 72 | " return 1\n", 73 | " return (1/(2**k)) + (geo_sum(k-1))\n", 74 | "\n", 75 | "k = int(input())\n", 76 | "print(\"{:.5f}\".format(geo_sum(k)))" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "source": [ 82 | "'''\n", 83 | "Check Palindrome (recursive)\n", 84 | "Check whether a given String S is a palindrome using recursion. Return true or false.\n", 85 | "\n", 86 | "Input Format :\n", 87 | "String S\n", 88 | "Output Format :\n", 89 | "'true' or 'false'\n", 90 | "\n", 91 | "Sample Input 1 :\n", 92 | "racecar\n", 93 | "Sample Output 1:\n", 94 | "true\n", 95 | "\n", 96 | "Sample Input 2 :\n", 97 | "ninja\n", 98 | "Sample Output 2:\n", 99 | "false\n", 100 | "'''\n", 101 | "\n", 102 | "def palindrome(s, start, end):\n", 103 | " if start>=end:\n", 104 | " return \"true\"\n", 105 | " \n", 106 | " if s[start]==s[end] :\n", 107 | " return palindrome(s, start+1, end-1)\n", 108 | " else:\n", 109 | " return \"false\"\n", 110 | " \n", 111 | "s = input()\n", 112 | "start = 0\n", 113 | "end = len(s)-1\n", 114 | "print(palindrome(s, start, end))" 115 | ], 116 | "metadata": { 117 | "colab": { 118 | "base_uri": "https://localhost:8080/" 119 | }, 120 | "id": "vBrn02ZLDtJ1", 121 | "outputId": "d9bb2b87-5fbb-47b4-f7a7-ab4c0c4ca587" 122 | }, 123 | "execution_count": null, 124 | "outputs": [ 125 | { 126 | "output_type": "stream", 127 | "name": "stdout", 128 | "text": [ 129 | "ninja\n", 130 | "false\n" 131 | ] 132 | } 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "source": [ 138 | "'''\n", 139 | "Sum of digits (recursive)\n", 140 | "Write a recursive function that returns the sum of the digits of a given integer.\n", 141 | "\n", 142 | "Input format :\n", 143 | "Integer N\n", 144 | "Output format :\n", 145 | "Sum of digits of N\n", 146 | "\n", 147 | "Sample Input 1 :\n", 148 | "12345\n", 149 | "Sample Output 1 :\n", 150 | "15\n", 151 | "\n", 152 | "Sample Input 2 :\n", 153 | "9\n", 154 | "Sample Output 2 :\n", 155 | "9\n", 156 | "'''\n", 157 | "\n", 158 | "def sum_digit(n):\n", 159 | " if n==0 :\n", 160 | " return 0\n", 161 | " \n", 162 | " return n%10 + sum_digit(n//10)\n", 163 | "\n", 164 | "n = int(input())\n", 165 | "print(sum_digit(n))" 166 | ], 167 | "metadata": { 168 | "colab": { 169 | "base_uri": "https://localhost:8080/" 170 | }, 171 | "id": "4qjoXb_0DxhP", 172 | "outputId": "f64a2b0d-2f18-40e8-f35f-6c214ef0991f" 173 | }, 174 | "execution_count": null, 175 | "outputs": [ 176 | { 177 | "output_type": "stream", 178 | "name": "stdout", 179 | "text": [ 180 | "12345\n", 181 | "15\n" 182 | ] 183 | } 184 | ] 185 | }, 186 | { 187 | "cell_type": "code", 188 | "source": [ 189 | "'''\n", 190 | "Multiplication (Recursive)\n", 191 | "\n", 192 | "Given two integers M & N, calculate and return their multiplication using recursion. You can only use subtraction and addition for your calculation. No other operators are allowed.\n", 193 | "\n", 194 | "Input format :\n", 195 | "Line 1 : Integer M\n", 196 | "Line 2 : Integer N\n", 197 | "Output format :\n", 198 | "M x N\n", 199 | "\n", 200 | "Constraints :\n", 201 | "0 <= M <= 1000\n", 202 | "0 <= N <= 1000\n", 203 | "\n", 204 | "Sample Input 1 :\n", 205 | "3 \n", 206 | "5\n", 207 | "Sample Output 1 :\n", 208 | "15\n", 209 | "\n", 210 | "Sample Input 2 :\n", 211 | "4 \n", 212 | "0\n", 213 | "Sample Output 2 :\n", 214 | "0\n", 215 | "'''\n", 216 | "\n", 217 | "# Multiply two numbers using recursion\n", 218 | "\n", 219 | "def multiply(m,n):\n", 220 | " \n", 221 | " if m 1 and s[1:3] == 'bb'):\n", 453 | " return checkAB(s[3:])\n", 454 | " else:\n", 455 | " return checkAB(s[1:])\n", 456 | " else:\n", 457 | " return 'false'\n", 458 | " \n", 459 | "s = input()\n", 460 | "print(checkAB(s))" 461 | ], 462 | "metadata": { 463 | "colab": { 464 | "base_uri": "https://localhost:8080/" 465 | }, 466 | "id": "A7X6cxl8Efic", 467 | "outputId": "5afba2f3-3e71-4b7e-e1d9-54b6b7c79db0" 468 | }, 469 | "execution_count": null, 470 | "outputs": [ 471 | { 472 | "output_type": "stream", 473 | "name": "stdout", 474 | "text": [ 475 | "abababa\n", 476 | "false\n" 477 | ] 478 | } 479 | ] 480 | }, 481 | { 482 | "cell_type": "code", 483 | "source": [ 484 | "'''\n", 485 | "Staircase\n", 486 | "A child is running up a staircase with N steps, and can hop either 1 step, 2 steps or 3 steps at a time. Implement a method to count how many possible ways the child can run up to the stairs. You need to return number of possible ways W.\n", 487 | "\n", 488 | "Input format :\n", 489 | "Integer N\n", 490 | "Output Format :\n", 491 | "Integer W\n", 492 | "\n", 493 | "Sample Input 1 :\n", 494 | "4\n", 495 | "Sample Output 1 :\n", 496 | "7\n", 497 | "\n", 498 | "Sample Input 2 :\n", 499 | "5\n", 500 | "Sample Output 2 :\n", 501 | "13\n", 502 | "'''\n", 503 | "\n", 504 | "def staircase(n):\n", 505 | " if n==0 :\n", 506 | " return 1\n", 507 | " \n", 508 | " elif n<0:\n", 509 | " return 0\n", 510 | " \n", 511 | " return staircase(n-1) + staircase(n-2) + staircase(n-3)\n", 512 | "\n", 513 | "n = int(input())\n", 514 | "print(staircase(n))" 515 | ], 516 | "metadata": { 517 | "colab": { 518 | "base_uri": "https://localhost:8080/" 519 | }, 520 | "id": "KbVqJ_G-EnST", 521 | "outputId": "d67252f2-3f4d-4e16-8430-7ef2acdb0014" 522 | }, 523 | "execution_count": null, 524 | "outputs": [ 525 | { 526 | "output_type": "stream", 527 | "name": "stdout", 528 | "text": [ 529 | "5\n", 530 | "13\n" 531 | ] 532 | } 533 | ] 534 | } 535 | ] 536 | } -------------------------------------------------------------------------------- /02_OOP/Content_Exception-Handling.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "Content_Exception_Handling", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": { 23 | "colab": { 24 | "base_uri": "https://localhost:8080/" 25 | }, 26 | "id": "pxDFav7cKYyM", 27 | "outputId": "65700654-3d7e-4bd0-e765-d5125c14c4c7" 28 | }, 29 | "outputs": [ 30 | { 31 | "output_type": "stream", 32 | "name": "stdout", 33 | "text": [ 34 | "Exception occured\n" 35 | ] 36 | } 37 | ], 38 | "source": [ 39 | "try:\n", 40 | " a = 10\n", 41 | " b = 0\n", 42 | " c = a/b\n", 43 | " print(c)\n", 44 | "except:\n", 45 | " print('Exception occured')" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "source": [ 51 | "class Vehicle():\n", 52 | "\n", 53 | " def __init__(self,make,model,fuel):\n", 54 | " self.make=make\n", 55 | " self.model=model\n", 56 | " self.fuel=fuel\n", 57 | "\n", 58 | " def get_value(self):\n", 59 | "\n", 60 | " try:\n", 61 | " age=2021-self.model\n", 62 | " return 1000+(1/age)\n", 63 | "\n", 64 | " except TypeError:\n", 65 | "\n", 66 | " try:\n", 67 | " age=2021-int(self.model)\n", 68 | " return 1000+(1/age)\n", 69 | "\n", 70 | " except ZeroDivisionError:\n", 71 | " age=2021-int(self.model)\n", 72 | " return 1000*(1)\n", 73 | "\n", 74 | " except:\n", 75 | " return \"You have entered Model Year in incorrect format\"\n", 76 | " \n", 77 | "myobj = Vehicle(\"Tesla\",\"2021\",\"Electric\")\n", 78 | "print(myobj.get_value())" 79 | ], 80 | "metadata": { 81 | "colab": { 82 | "base_uri": "https://localhost:8080/" 83 | }, 84 | "id": "JUgq_nauLWQR", 85 | "outputId": "3e68b429-e569-431b-d8b0-d144e219446a" 86 | }, 87 | "execution_count": null, 88 | "outputs": [ 89 | { 90 | "output_type": "stream", 91 | "name": "stdout", 92 | "text": [ 93 | "1000\n" 94 | ] 95 | } 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "source": [ 101 | "try:\n", 102 | " a = 10\n", 103 | " b = 0\n", 104 | " print(d)\n", 105 | " c = a/b\n", 106 | "\n", 107 | "except NameError:\n", 108 | " print('Name Error occured')\n", 109 | " \n", 110 | "except ZeroDivisionError:\n", 111 | " print('Zero Division Error occured')" 112 | ], 113 | "metadata": { 114 | "colab": { 115 | "base_uri": "https://localhost:8080/" 116 | }, 117 | "id": "7NLA1XNHLwFp", 118 | "outputId": "fcf065cc-d461-4eef-9dae-29aea732720f" 119 | }, 120 | "execution_count": null, 121 | "outputs": [ 122 | { 123 | "output_type": "stream", 124 | "name": "stdout", 125 | "text": [ 126 | "Name Error occured\n" 127 | ] 128 | } 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "source": [ 134 | "# Custom Exceptions\n", 135 | "\n", 136 | "class NegativeCarValue(Exception):\n", 137 | " \n", 138 | " def __init__(self,value,message=\"car value cannot be negative\"):\n", 139 | " self.value=value\n", 140 | " self.message=message\n", 141 | " super().__init__(self.message)\n", 142 | " \n", 143 | " def __str__(self):\n", 144 | " return f'{self.message}-->{self.value}'\n", 145 | "\n", 146 | "class Vehicle():\n", 147 | "\n", 148 | " def __init__(self,make,model,fuel):\n", 149 | " self.make=make\n", 150 | " self.model=model\n", 151 | " self.fuel=fuel\n", 152 | " self.current_year=2021\n", 153 | "\n", 154 | " def get_value(self):\n", 155 | " age=self.current_year-self.model\n", 156 | " if age<0:\n", 157 | " raise NegativeCarValue(age)\n", 158 | " else:\n", 159 | " return 1000*(1/age)\n", 160 | "\n", 161 | "myobj = Vehicle(\"Tesla\",2023,\"electric\")\n", 162 | "print(myobj.get_value())" 163 | ], 164 | "metadata": { 165 | "colab": { 166 | "base_uri": "https://localhost:8080/", 167 | "height": 332 168 | }, 169 | "id": "-1dTNoUNNJTP", 170 | "outputId": "7dbd6fc6-6df7-4be0-a35f-d5a2708b4a23" 171 | }, 172 | "execution_count": null, 173 | "outputs": [ 174 | { 175 | "output_type": "error", 176 | "ename": "NegativeCarValue", 177 | "evalue": "ignored", 178 | "traceback": [ 179 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 180 | "\u001b[0;31mNegativeCarValue\u001b[0m Traceback (most recent call last)", 181 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 27\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 28\u001b[0m \u001b[0mmyobj\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mVehicle\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Tesla\"\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m2023\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\"electric\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 29\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmyobj\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget_value\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 182 | "\u001b[0;32m\u001b[0m in \u001b[0;36mget_value\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 22\u001b[0m \u001b[0mage\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcurrent_year\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmodel\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 23\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mage\u001b[0m\u001b[0;34m<\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 24\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mNegativeCarValue\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mage\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 25\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 26\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0;36m1000\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0mage\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 183 | "\u001b[0;31mNegativeCarValue\u001b[0m: car value cannot be negative-->-2" 184 | ] 185 | } 186 | ] 187 | }, 188 | { 189 | "cell_type": "code", 190 | "source": [ 191 | "class ZeroDenominatorError(Exception):\n", 192 | " pass\n", 193 | "try:\n", 194 | " a = 10\n", 195 | " b = 0\n", 196 | " if(b==0):\n", 197 | " raise ZeroDenominatorError() \n", 198 | " c = a/b\n", 199 | "except ZeroDivisionError:\n", 200 | " print('Zero Division Error occured')" 201 | ], 202 | "metadata": { 203 | "colab": { 204 | "base_uri": "https://localhost:8080/", 205 | "height": 242 206 | }, 207 | "id": "QWVB_TPlNojt", 208 | "outputId": "39166c85-aa17-4b17-d785-6bd41be412c8" 209 | }, 210 | "execution_count": null, 211 | "outputs": [ 212 | { 213 | "output_type": "error", 214 | "ename": "ZeroDenominatorError", 215 | "evalue": "ignored", 216 | "traceback": [ 217 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 218 | "\u001b[0;31mZeroDenominatorError\u001b[0m Traceback (most recent call last)", 219 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mb\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;32mif\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mb\u001b[0m\u001b[0;34m==\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mZeroDenominatorError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 8\u001b[0m \u001b[0mc\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0ma\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0mb\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mZeroDivisionError\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 220 | "\u001b[0;31mZeroDenominatorError\u001b[0m: " 221 | ] 222 | } 223 | ] 224 | }, 225 | { 226 | "cell_type": "code", 227 | "source": [ 228 | "class NegativeCarValue(Exception):\n", 229 | " def __init__(self,value,message=\"car value cannot be negative\"):\n", 230 | " self.value=value\n", 231 | " self.message=message\n", 232 | " super().__init__(self.message)\n", 233 | " \n", 234 | " def __str__(self):\n", 235 | " return f'{self.message}-->{self.value}'\n", 236 | "\n", 237 | "class Vehicle():\n", 238 | " def __init__(self,make,model,fuel):\n", 239 | " self.make=make\n", 240 | " self.model=model\n", 241 | " self.fuel=fuel\n", 242 | " self.current_year=2021\n", 243 | "\n", 244 | " def get_value(self):\n", 245 | " age=self.current_year-self.model\n", 246 | " try:\n", 247 | " if age<0:\n", 248 | " raise NegativeCarValue(age)\n", 249 | " else:\n", 250 | " return 1000*(1/age)\n", 251 | " except NegativeCarValue as e:\n", 252 | " print(\"Error***\",e)\n", 253 | "\n", 254 | "myobj = Vehicle(\"Tesla\",2023,\"electric\")\n", 255 | "print(myobj.get_value())" 256 | ], 257 | "metadata": { 258 | "colab": { 259 | "base_uri": "https://localhost:8080/" 260 | }, 261 | "id": "-akaGLjoOWiM", 262 | "outputId": "94576ade-4128-4d46-e41e-77eb5a237ff7" 263 | }, 264 | "execution_count": null, 265 | "outputs": [ 266 | { 267 | "output_type": "stream", 268 | "name": "stdout", 269 | "text": [ 270 | "Error*** car value cannot be negative-->-2\n", 271 | "None\n" 272 | ] 273 | } 274 | ] 275 | }, 276 | { 277 | "cell_type": "code", 278 | "source": [ 279 | "class ZeroDenominatorError(ZeroDivisionError):\n", 280 | " pass\n", 281 | "try:\n", 282 | " a = 10\n", 283 | " b = 0\n", 284 | " if(b==0):\n", 285 | " raise ZeroDenominatorError()\n", 286 | " c = a/b\n", 287 | "except ZeroDivisionError:\n", 288 | " print('Zero Division Error occured')\n", 289 | "except ZeroDenominatorError:\n", 290 | " print('Zero Denominator Error occured')" 291 | ], 292 | "metadata": { 293 | "colab": { 294 | "base_uri": "https://localhost:8080/" 295 | }, 296 | "id": "7yH6KcZjOyYR", 297 | "outputId": "0be4b4af-b1b2-429d-c105-89229195c8a0" 298 | }, 299 | "execution_count": null, 300 | "outputs": [ 301 | { 302 | "output_type": "stream", 303 | "name": "stdout", 304 | "text": [ 305 | "Zero Division Error occured\n" 306 | ] 307 | } 308 | ] 309 | }, 310 | { 311 | "cell_type": "code", 312 | "source": [ 313 | "class NegativeZeroModelYear(Exception):\n", 314 | " def __init__(self,value,message=\"Model year cannot be equal or greater than 2021\"):\n", 315 | " self.value=value\n", 316 | " self.message=message\n", 317 | " super().__init__(self.message)\n", 318 | " \n", 319 | " def __str__(self):\n", 320 | " return f'{self.message}-->{self.value}'\n", 321 | "\n", 322 | "class CarModeYearAsString(Exception):\n", 323 | " #Exception if the car value comes as negative\n", 324 | " def __init__(self,value,message=\"Model year can not be strings.Try Passing int values\"):\n", 325 | " self.value=value\n", 326 | " self.message=message\n", 327 | " super().init__(self.message)\n", 328 | "\n", 329 | " def __str__(self):\n", 330 | " return f'{self.message}-->{self.value}'\n", 331 | "\n", 332 | "class Vehicle():\n", 333 | " def __init__(self,make,model,fuel):\n", 334 | " self.make=make\n", 335 | " self.model=model\n", 336 | " self.fuel=fuel\n", 337 | " self.current_year=2021\n", 338 | " self.value=None\n", 339 | "\n", 340 | " def get_value(self):\n", 341 | " try:\n", 342 | " if type(self.model)==str:\n", 343 | " status=\"custom\"\n", 344 | " raise CarModelYearAsString(self.model)\n", 345 | " elif self.model>=self.current_year:\n", 346 | " status=\"custom\"\n", 347 | " raise NegativeZeroModelYear(self.model)\n", 348 | " else:\n", 349 | " self.age=self.current_year-self.model\n", 350 | " self.value=1000*(1/self.age)\n", 351 | " status=\"success\"\n", 352 | " except TypeError:\n", 353 | " self.age=self.current_year-int(self.model)\n", 354 | " self.value=1000*(1/self.age)\n", 355 | " status=\"inbuilt\"\n", 356 | " else:\n", 357 | " print(\"code ran without any exceptions\")\n", 358 | " finally:\n", 359 | " if status==\"custom\":\n", 360 | " print(\"code has inbuilt exceptions\")\n", 361 | " elif status==\"inbuilt\":\n", 362 | " print(\"code has inbuilt exceptions,please rectify that\")\n", 363 | " else:\n", 364 | " print(\"The value without any exception\",self.value)\n", 365 | "\n", 366 | "myobj = Vehicle(\"Tesla\",2023,\"electric\")\n", 367 | "print(myobj.get_value())" 368 | ], 369 | "metadata": { 370 | "colab": { 371 | "base_uri": "https://localhost:8080/", 372 | "height": 351 373 | }, 374 | "id": "fWDcFdRXQR6U", 375 | "outputId": "eae606d0-d399-400e-cd51-714303216e89" 376 | }, 377 | "execution_count": null, 378 | "outputs": [ 379 | { 380 | "output_type": "stream", 381 | "name": "stdout", 382 | "text": [ 383 | "code has inbuilt exceptions\n" 384 | ] 385 | }, 386 | { 387 | "output_type": "error", 388 | "ename": "NegativeZeroModelYear", 389 | "evalue": "ignored", 390 | "traceback": [ 391 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 392 | "\u001b[0;31mNegativeZeroModelYear\u001b[0m Traceback (most recent call last)", 393 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 53\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 54\u001b[0m \u001b[0mmyobj\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mVehicle\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Tesla\"\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m2023\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\"electric\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 55\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmyobj\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget_value\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 394 | "\u001b[0;32m\u001b[0m in \u001b[0;36mget_value\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 33\u001b[0m \u001b[0;32melif\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmodel\u001b[0m\u001b[0;34m>=\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcurrent_year\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 34\u001b[0m \u001b[0mstatus\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m\"custom\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 35\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mNegativeZeroModelYear\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmodel\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 36\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 37\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mage\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcurrent_year\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmodel\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 395 | "\u001b[0;31mNegativeZeroModelYear\u001b[0m: Model year cannot be equal or greater than 2021-->2023" 396 | ] 397 | } 398 | ] 399 | }, 400 | { 401 | "cell_type": "code", 402 | "source": [ 403 | "class ZeroDenominatorError(ZeroDivisionError):\n", 404 | " pass\n", 405 | "try:\n", 406 | " a = 10\n", 407 | " b = 0\n", 408 | " if(b==0):\n", 409 | " raise ZeroDenominatorError()\n", 410 | " c = a/b\n", 411 | "except ZeroDivisionError:\n", 412 | " print('Zero Division Error occured',end= ' ')\n", 413 | "except ZeroDenominatorError:\n", 414 | " print('Zero Denominator Error occured',end = ' ')\n", 415 | "else:\n", 416 | " print('else works')" 417 | ], 418 | "metadata": { 419 | "colab": { 420 | "base_uri": "https://localhost:8080/" 421 | }, 422 | "id": "WLTihKqfQn5Z", 423 | "outputId": "70b2168f-f42a-4fd1-f1f5-ff233cb09393" 424 | }, 425 | "execution_count": null, 426 | "outputs": [ 427 | { 428 | "output_type": "stream", 429 | "name": "stdout", 430 | "text": [ 431 | "Zero Division Error occured " 432 | ] 433 | } 434 | ] 435 | }, 436 | { 437 | "cell_type": "code", 438 | "source": [ 439 | "class ZeroDenominatorError(ZeroDivisionError):\n", 440 | " pass\n", 441 | "try:\n", 442 | " a = 10\n", 443 | " b = 5\n", 444 | " if(b==0):\n", 445 | " raise ZeroDenominatorError()\n", 446 | " c = a/b\n", 447 | "except ZeroDivisionError:\n", 448 | " print('Zero Division Error occured',end= ' ')\n", 449 | "except ZeroDenominatorError:\n", 450 | " print('Zero Denominator Error occured',end = ' ')\n", 451 | "else:\n", 452 | " print('else works')\n" 453 | ], 454 | "metadata": { 455 | "colab": { 456 | "base_uri": "https://localhost:8080/" 457 | }, 458 | "id": "lUMznDnTQ6gs", 459 | "outputId": "381e9557-f271-4413-de2b-c2f581c22971" 460 | }, 461 | "execution_count": null, 462 | "outputs": [ 463 | { 464 | "output_type": "stream", 465 | "name": "stdout", 466 | "text": [ 467 | "else works\n" 468 | ] 469 | } 470 | ] 471 | }, 472 | { 473 | "cell_type": "code", 474 | "source": [ 475 | "class ZeroDenominatorError(ZeroDivisionError):\n", 476 | " pass\n", 477 | "try:\n", 478 | " a = 10\n", 479 | " b = 5\n", 480 | " if(b==0):\n", 481 | " raise ZeroDenominatorError()\n", 482 | " c = a/b\n", 483 | "except ZeroDivisionError:\n", 484 | " print('Zero Division Error occured',end= ' ')\n", 485 | "except ZeroDenominatorError:\n", 486 | " print('Zero Denominator Error occured',end = ' ')\n", 487 | "else:\n", 488 | " print('else works',end=' ')\n", 489 | "finally:\n", 490 | " print('finally works')" 491 | ], 492 | "metadata": { 493 | "colab": { 494 | "base_uri": "https://localhost:8080/" 495 | }, 496 | "id": "li2hedYRRGTP", 497 | "outputId": "c8662599-1aaf-4c0f-e647-5a8d58ded296" 498 | }, 499 | "execution_count": null, 500 | "outputs": [ 501 | { 502 | "output_type": "stream", 503 | "name": "stdout", 504 | "text": [ 505 | "else works finally works\n" 506 | ] 507 | } 508 | ] 509 | } 510 | ] 511 | } -------------------------------------------------------------------------------- /02_OOP/Quiz_OOP-1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddhapuraharsh/Data-Structures_Algorithms_Coding-Ninjas_Full-Course/149411eb7d59abd80d2a65f0ff1039b62558bb1b/02_OOP/Quiz_OOP-1.pdf -------------------------------------------------------------------------------- /02_OOP/Quiz_OOP-2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddhapuraharsh/Data-Structures_Algorithms_Coding-Ninjas_Full-Course/149411eb7d59abd80d2a65f0ff1039b62558bb1b/02_OOP/Quiz_OOP-2.pdf -------------------------------------------------------------------------------- /02_OOP/Quiz_OOP-3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddhapuraharsh/Data-Structures_Algorithms_Coding-Ninjas_Full-Course/149411eb7d59abd80d2a65f0ff1039b62558bb1b/02_OOP/Quiz_OOP-3.pdf -------------------------------------------------------------------------------- /03_Complexity-Analysis/Quiz_Space-Complexity-Analysis.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddhapuraharsh/Data-Structures_Algorithms_Coding-Ninjas_Full-Course/149411eb7d59abd80d2a65f0ff1039b62558bb1b/03_Complexity-Analysis/Quiz_Space-Complexity-Analysis.pdf -------------------------------------------------------------------------------- /03_Complexity-Analysis/Quiz_Time-Complexity-Analysis.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddhapuraharsh/Data-Structures_Algorithms_Coding-Ninjas_Full-Course/149411eb7d59abd80d2a65f0ff1039b62558bb1b/03_Complexity-Analysis/Quiz_Time-Complexity-Analysis.pdf -------------------------------------------------------------------------------- /04_Linked-List/Linked-List-1/Content_Linked_List_1.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "Content_Linked-List-1", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": { 23 | "colab": { 24 | "base_uri": "https://localhost:8080/" 25 | }, 26 | "id": "kVxVg4JlACbW", 27 | "outputId": "40989240-0b20-4ae2-b7d9-fbfd9b30545b" 28 | }, 29 | "outputs": [ 30 | { 31 | "output_type": "stream", 32 | "name": "stdout", 33 | "text": [ 34 | "1\n", 35 | "2\n", 36 | "2\n", 37 | "None\n" 38 | ] 39 | } 40 | ], 41 | "source": [ 42 | "# Creating Nodes of Linked List\n", 43 | "class Node:\n", 44 | " def __init__(self, data):\n", 45 | " self.data = data\n", 46 | " self.next = None\n", 47 | "\n", 48 | "a = Node(1)\n", 49 | "b = Node(2)\n", 50 | "a.next = b\n", 51 | "print(a.data)\n", 52 | "print(a.next.data) # data of b\n", 53 | "print(b.data)\n", 54 | "print(b.next)" 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "source": [ 60 | "class Node:\n", 61 | " def __init__(self, data):\n", 62 | " self.data = data\n", 63 | " self.next = None\n", 64 | "def printLL(head):\n", 65 | " while head is not None:\n", 66 | " print(head.data,end=\" \")\n", 67 | " head = head.next\n", 68 | "\n", 69 | "node1 = Node(10)\n", 70 | "node2 = Node(20)\n", 71 | "node2.next = node1\n", 72 | "printLL(node2)" 73 | ], 74 | "metadata": { 75 | "colab": { 76 | "base_uri": "https://localhost:8080/" 77 | }, 78 | "id": "ydZjkiNpDTKA", 79 | "outputId": "90218a80-e3ff-4ab1-c07a-0e8608bae942" 80 | }, 81 | "execution_count": null, 82 | "outputs": [ 83 | { 84 | "output_type": "stream", 85 | "name": "stdout", 86 | "text": [ 87 | "20 10 " 88 | ] 89 | } 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "source": [ 95 | "class Node:\n", 96 | " def __init__(self, data):\n", 97 | " self.data = data\n", 98 | " self.next = None\n", 99 | "def printLL(head):\n", 100 | " while head is not None:\n", 101 | " print(head.data,end=\" \")\n", 102 | " head = head.next\n", 103 | "\n", 104 | "node1 = Node(10)\n", 105 | "node2 = Node(20)\n", 106 | "node3 = Node(30)\n", 107 | "node4 = Node(40)\n", 108 | "node1.next = node2\n", 109 | "node2.next = node3\n", 110 | "node3.next = node4\n", 111 | "printLL(node2)" 112 | ], 113 | "metadata": { 114 | "id": "eZaj22W0D5hu", 115 | "outputId": "f07f686c-8ad1-408e-baa1-33ec5dd48946", 116 | "colab": { 117 | "base_uri": "https://localhost:8080/" 118 | } 119 | }, 120 | "execution_count": null, 121 | "outputs": [ 122 | { 123 | "output_type": "stream", 124 | "name": "stdout", 125 | "text": [ 126 | "20 30 40 " 127 | ] 128 | } 129 | ] 130 | }, 131 | { 132 | "cell_type": "markdown", 133 | "source": [ 134 | "**Create & Print Linked List**" 135 | ], 136 | "metadata": { 137 | "id": "ky3eeolZCf_f" 138 | } 139 | }, 140 | { 141 | "cell_type": "code", 142 | "source": [ 143 | "# Create and Print Linked List\n", 144 | "\n", 145 | "# Create Node\n", 146 | "class Node:\n", 147 | " def __init__(self,data):\n", 148 | " self.data = data\n", 149 | " self.next = None\n", 150 | "\n", 151 | "# Print Linked List\n", 152 | "def printLL(head):\n", 153 | " while head is not None:\n", 154 | " print(str(head.data)+\"->\",end='')\n", 155 | " head = head.next\n", 156 | " print(\"None\")\n", 157 | " return\n", 158 | "\n", 159 | "# Create Linked List\n", 160 | "def takeInput():\n", 161 | " inputList = [int (ele) for ele in input().split()] \n", 162 | "\n", 163 | " head = None\n", 164 | " tail = None\n", 165 | "\n", 166 | " for currData in inputList:\n", 167 | " if currData==-1:\n", 168 | " break\n", 169 | "\n", 170 | " newNode = Node(currData)\n", 171 | "\n", 172 | " if head is None:\n", 173 | " head = newNode\n", 174 | " tail = newNode\n", 175 | " else:\n", 176 | " tail.next = newNode\n", 177 | " tail = newNode\n", 178 | "\n", 179 | " return head\n", 180 | "\n", 181 | "head = takeInput()\n", 182 | "printLL(head)" 183 | ], 184 | "metadata": { 185 | "colab": { 186 | "base_uri": "https://localhost:8080/" 187 | }, 188 | "id": "YiQle4ZcxY7s", 189 | "outputId": "a2cabc98-d856-4122-ba39-e04c800791a8" 190 | }, 191 | "execution_count": null, 192 | "outputs": [ 193 | { 194 | "output_type": "stream", 195 | "name": "stdout", 196 | "text": [ 197 | "1 2 3 4 5 6 7 8 9 -1\n", 198 | "1->2->3->4->5->6->7->8->9->None\n" 199 | ] 200 | } 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "source": [ 206 | "class Node:\n", 207 | " def __init__(self, data):\n", 208 | " self.data = data\n", 209 | " self.next = None\n", 210 | "\n", 211 | "def printLL(head):\n", 212 | " while head is not None:\n", 213 | " print(head.data,end=\" \")\n", 214 | " head = head.next\n", 215 | "\n", 216 | "def increment(head):\n", 217 | " temp = head\n", 218 | " while temp is not None:\n", 219 | " temp.data +=1\n", 220 | " temp = temp.next\n", 221 | "\n", 222 | "node1 = Node(10)\n", 223 | "node2 = Node(20)\n", 224 | "node1.next = node2\n", 225 | "increment(node1)\n", 226 | "printLL(node1)" 227 | ], 228 | "metadata": { 229 | "colab": { 230 | "base_uri": "https://localhost:8080/" 231 | }, 232 | "id": "y0qYf0DMAwmk", 233 | "outputId": "7933750b-cfb4-4ff0-d3d5-5ba684befe7a" 234 | }, 235 | "execution_count": null, 236 | "outputs": [ 237 | { 238 | "output_type": "stream", 239 | "name": "stdout", 240 | "text": [ 241 | "11 21 " 242 | ] 243 | } 244 | ] 245 | }, 246 | { 247 | "cell_type": "markdown", 248 | "source": [ 249 | "**Insert Element Iteratively at ith position**\n" 250 | ], 251 | "metadata": { 252 | "id": "V-I_B1S2Ck6k" 253 | } 254 | }, 255 | { 256 | "cell_type": "code", 257 | "source": [ 258 | "class Node:\n", 259 | " def __init__(self,data):\n", 260 | " self.data=data\n", 261 | " self.next=None\n", 262 | "\n", 263 | "def printLL(head):\n", 264 | " while head is not None:\n", 265 | " print(str(head.data)+\"->\",end='')\n", 266 | " head=head.next\n", 267 | " print(\"None\")\n", 268 | " return\n", 269 | "\n", 270 | "def length(head):\n", 271 | " count=0\n", 272 | " while head is not None:\n", 273 | " count=count+1\n", 274 | " head=head.next\n", 275 | " return count\n", 276 | "\n", 277 | "\n", 278 | "def insertAtI(head,i,data):\n", 279 | "\n", 280 | " if i<0 or i>length(head):\n", 281 | " return head\n", 282 | "\n", 283 | " count=0\n", 284 | " prev=None\n", 285 | " curr=head\n", 286 | "\n", 287 | " while count2->3->4->5->None\n", 343 | "1->2->6->3->4->5->None\n", 344 | "9->1->2->6->3->4->5->None\n", 345 | "9->1->2->6->3->4->5->10->None\n" 346 | ] 347 | } 348 | ] 349 | }, 350 | { 351 | "cell_type": "markdown", 352 | "source": [ 353 | "**Insert Element Recursively at ith position**" 354 | ], 355 | "metadata": { 356 | "id": "aLqx-kejS2_b" 357 | } 358 | }, 359 | { 360 | "cell_type": "code", 361 | "source": [ 362 | "class Node:\n", 363 | " def __init__(self,data):\n", 364 | " self.data=data\n", 365 | " self.next=None\n", 366 | "\n", 367 | "\n", 368 | "def printLL(head):\n", 369 | " while head is not None:\n", 370 | " print(str(head.data)+\"->\",end='')\n", 371 | " head=head.next\n", 372 | " print(\"None\")\n", 373 | " return\n", 374 | "\n", 375 | "\n", 376 | "def insertAtIR(head,i,data):\n", 377 | " \n", 378 | " if i==0:\n", 379 | " newNode=Node(data)\n", 380 | " newNode.next=head\n", 381 | " return newNode\n", 382 | " \n", 383 | " if i<0 or head is None:\n", 384 | " return head\n", 385 | "\n", 386 | " head.next = insertAtIR(head.next,i-1,data)\n", 387 | "\n", 388 | " return head\n", 389 | "\n", 390 | "\n", 391 | "def takeInput():\n", 392 | " inputList=[int (ele) for ele in input().split()]\n", 393 | " head=None\n", 394 | " tail=None\n", 395 | " for currData in inputList:\n", 396 | " if currData==-1:\n", 397 | " break\n", 398 | " newNode=Node(currData)\n", 399 | " if head is None:\n", 400 | " head=newNode\n", 401 | " tail=newNode\n", 402 | " else:\n", 403 | " tail.next=newNode\n", 404 | " tail=newNode\n", 405 | " return head\n", 406 | "\n", 407 | "\n", 408 | "head=takeInput()\n", 409 | "printLL(head)\n", 410 | "head=insertAtIR(head,2,6)\n", 411 | "printLL(head)\n", 412 | "head=insertAtIR(head,0,9)\n", 413 | "printLL(head)\n", 414 | "head=insertAtIR(head,7,10)\n", 415 | "printLL(head)" 416 | ], 417 | "metadata": { 418 | "colab": { 419 | "base_uri": "https://localhost:8080/" 420 | }, 421 | "id": "InjtdGLMKVIj", 422 | "outputId": "445d911f-dc58-4fdf-83d7-c31c5f96ba3c" 423 | }, 424 | "execution_count": null, 425 | "outputs": [ 426 | { 427 | "output_type": "stream", 428 | "name": "stdout", 429 | "text": [ 430 | "1 2 3 4 5\n", 431 | "1->2->3->4->5->None\n", 432 | "1->2->6->3->4->5->None\n", 433 | "9->1->2->6->3->4->5->None\n", 434 | "9->1->2->6->3->4->5->10->None\n" 435 | ] 436 | } 437 | ] 438 | } 439 | ] 440 | } -------------------------------------------------------------------------------- /04_Linked-List/Linked-List-1/Quiz_Linked-List-1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddhapuraharsh/Data-Structures_Algorithms_Coding-Ninjas_Full-Course/149411eb7d59abd80d2a65f0ff1039b62558bb1b/04_Linked-List/Linked-List-1/Quiz_Linked-List-1.pdf -------------------------------------------------------------------------------- /04_Linked-List/Linked-List-2/Content_Problems_Linked_List_2.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "Content-Problems_Linked-List-2", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "source": [ 22 | "**CONTENT PROBLEMS**" 23 | ], 24 | "metadata": { 25 | "id": "TQwgVQLaqSmT" 26 | } 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": null, 31 | "metadata": { 32 | "id": "DUyO4FVa74Pu" 33 | }, 34 | "outputs": [], 35 | "source": [ 36 | "'''\n", 37 | "Reverse LL (Recursive)\n", 38 | "\n", 39 | "Given a singly linked list of integers, reverse it using recursion and return the head to the modified list. You have to do this in O(N) time complexity where N is the size of the linked list.\n", 40 | " \n", 41 | "Note :\n", 42 | "No need to print the list, it has already been taken care. Only return the new head to the list.\n", 43 | "Input format :\n", 44 | "The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.\n", 45 | "\n", 46 | "The first and the only line of each test case or query contains the elements of the singly linked list separated by a single space.\n", 47 | "\n", 48 | "Remember/Consider :\n", 49 | "While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element\n", 50 | "\n", 51 | "Output format :\n", 52 | "For each test case/query, print the elements of the updated singly linked list.\n", 53 | "\n", 54 | "Output for every test case will be printed in a seperate line.\n", 55 | " Constraints :\n", 56 | "1 <= t <= 10^2\n", 57 | "0 <= M <= 10^4\n", 58 | "Where M is the size of the singly linked list.\n", 59 | "\n", 60 | "Time Limit: 1sec\n", 61 | "Sample Input 1 :\n", 62 | "1\n", 63 | "1 2 3 4 5 6 7 8 -1\n", 64 | "Sample Output 1 :\n", 65 | "8 7 6 5 4 3 2 1\n", 66 | "\n", 67 | "Sample Input 2 :\n", 68 | "2\n", 69 | "10 -1\n", 70 | "10 20 30 40 50 -1\n", 71 | "Sample Output 2 :\n", 72 | "10 \n", 73 | "50 40 30 20 10 \n", 74 | "'''\n", 75 | "\n", 76 | "from sys import stdin, setrecursionlimit\n", 77 | "setrecursionlimit(10 ** 6)\n", 78 | "\n", 79 | "class Node :\n", 80 | " def __init__(self, data) :\n", 81 | " self.data = data\n", 82 | " self.next = None\n", 83 | "\n", 84 | "def reverseLinkedListRec(head) :\n", 85 | " if head is None:\n", 86 | " return None\n", 87 | " \n", 88 | " if head.next is None:\n", 89 | " return head\n", 90 | " \n", 91 | " tempHead = reverseLinkedListRec(head.next)\n", 92 | " tempTail = head.next\n", 93 | " tempTail.next = head\n", 94 | " head.next = None\n", 95 | " \n", 96 | " return tempHead\n", 97 | "\t\n", 98 | "#Taking Input Using Fast I/O\n", 99 | "def takeInput() :\n", 100 | " head = None\n", 101 | " tail = None\n", 102 | " datas = list(map(int, stdin.readline().rstrip().split(\" \")))\n", 103 | " i = 0\n", 104 | " while (i < len(datas)) and (datas[i] != -1) :\n", 105 | " data = datas[i]\n", 106 | " newNode = Node(data)\n", 107 | " if head is None :\n", 108 | " head = newNode\n", 109 | " tail = newNode\n", 110 | " else :\n", 111 | " tail.next = newNode\n", 112 | " tail = newNode\n", 113 | " i += 1\n", 114 | " return head\n", 115 | "\n", 116 | "def printLinkedList(head) :\n", 117 | " while head is not None :\n", 118 | " print(head.data, end = \" \")\n", 119 | " head = head.next\n", 120 | " print()\n", 121 | "\n", 122 | "#main\n", 123 | "t = int(stdin.readline().rstrip())\n", 124 | "while t > 0 : \n", 125 | " head = takeInput()\n", 126 | " newHead = reverseLinkedListRec(head)\n", 127 | " printLinkedList(newHead)\n", 128 | " t -= 1" 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "source": [ 134 | "'''\n", 135 | "Reverse LL (Iterative)\n", 136 | "\n", 137 | "Given a singly linked list of integers, reverse it iteratively and return the head to the modified list.\n", 138 | "\n", 139 | "Note :\n", 140 | "No need to print the list, it has already been taken care. Only return the new head to the list.\n", 141 | "\n", 142 | "Input format :\n", 143 | "The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.\n", 144 | "\n", 145 | "The first and the only line of each test case or query contains the elements of the singly linked list separated by a single space.\n", 146 | "\n", 147 | "Remember/Consider :\n", 148 | "While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element\n", 149 | "\n", 150 | "Output format :\n", 151 | "For each test case/query, print the elements of the updated singly linked list.\n", 152 | "\n", 153 | "Output for every test case will be printed in a separate line.\n", 154 | " \n", 155 | "Constraints :\n", 156 | "1 <= t <= 10^2\n", 157 | "0 <= N <= 10^4\n", 158 | "Where N is the size of the singly linked list.\n", 159 | "\n", 160 | "Time Limit: 1 sec\n", 161 | "\n", 162 | "Sample Input 1 :\n", 163 | "1\n", 164 | "1 2 3 4 5 6 7 8 -1\n", 165 | "Sample Output 1 :\n", 166 | "8 7 6 5 4 3 2 1\n", 167 | "\n", 168 | "Sample Input 2 :\n", 169 | "2\n", 170 | "10 -1\n", 171 | "10 20 30 40 50 -1\n", 172 | "Sample Output 2 :\n", 173 | "10 \n", 174 | "50 40 30 20 10 \n", 175 | "'''\n", 176 | "\n", 177 | "from sys import stdin , setrecursionlimit\n", 178 | "setrecursionlimit(10**6)\n", 179 | "class Node:\n", 180 | " def __init__(self, data):\n", 181 | " self.data = data\n", 182 | " self.next = None\n", 183 | "\n", 184 | "# Taking Input Using Fast I/O\n", 185 | "def takeInput() :\n", 186 | " head = None\n", 187 | " tail = None\n", 188 | " datas = list(map(int, stdin.readline().rstrip().split(\" \")))\n", 189 | " i = 0\n", 190 | " while (i < len(datas)) and (datas[i] != -1) :\n", 191 | " data = datas[i]\n", 192 | " newNode = Node(data)\n", 193 | " if head is None :\n", 194 | " head = newNode\n", 195 | " tail = newNode\n", 196 | " else :\n", 197 | " tail.next = newNode\n", 198 | " tail = newNode\n", 199 | " i += 1\n", 200 | " return head\n", 201 | "\n", 202 | "# To print the linked list \n", 203 | "def printLinkedList(head) :\n", 204 | " while head is not None :\n", 205 | " print(head.data, end = \" \")\n", 206 | " head = head.next\n", 207 | " print()\n", 208 | "\n", 209 | "def reverse(head):\n", 210 | " previousNode = None\n", 211 | " currentNode = head\n", 212 | " \n", 213 | " while currentNode is not None:\n", 214 | " nextNode = currentNode.next\n", 215 | " currentNode.next = previousNode\n", 216 | " previousNode = currentNode\n", 217 | " currentNode = nextNode\n", 218 | " \n", 219 | " return previousNode\n", 220 | " \n", 221 | "# Main\n", 222 | "t = int(stdin.readline().rstrip())\n", 223 | "while t > 0 :\n", 224 | " head = takeInput()\n", 225 | " ans=reverse(head)\n", 226 | " printLinkedList(ans)\n", 227 | " t -= 1 " 228 | ], 229 | "metadata": { 230 | "id": "Ayiu0-4T5YBF" 231 | }, 232 | "execution_count": null, 233 | "outputs": [] 234 | }, 235 | { 236 | "cell_type": "code", 237 | "source": [ 238 | "'''\n", 239 | "Midpoint of Linked list\n", 240 | "\n", 241 | "For a given singly linked list of integers, find and return the node present at the middle of the list.\n", 242 | "\n", 243 | "Note :\n", 244 | "If the length of the singly linked list is even, then return the first middle node.\n", 245 | "\n", 246 | "Example: Consider, 10 -> 20 -> 30 -> 40 is the given list, then the nodes present at the middle with respective data values are, 20 and 30. We return the first node with data 20.\n", 247 | " \n", 248 | "Input format :\n", 249 | "The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.\n", 250 | "\n", 251 | "The first and the only line of each test case or query contains the elements of the singly linked list separated by a single space. \n", 252 | "\n", 253 | "Remember/Consider :\n", 254 | "While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element\n", 255 | " \n", 256 | "Output Format :\n", 257 | "For each test case/query, print the data value of the node at the middle of the given list.\n", 258 | "\n", 259 | "Output for every test case will be printed in a seperate line.\n", 260 | "\n", 261 | "Constraints :\n", 262 | "1 <= t <= 10^2\n", 263 | "0 <= M <= 10^5 \n", 264 | "\n", 265 | "Where M is the size of the singly linked list.\n", 266 | "\n", 267 | "Time Limit: 1sec\n", 268 | "\n", 269 | "Sample Input 1 :\n", 270 | "1\n", 271 | "1 2 3 4 5 -1\n", 272 | "Sample Output 1 :\n", 273 | "3\n", 274 | "\n", 275 | "Sample Input 2 :\n", 276 | "2 \n", 277 | "-1\n", 278 | "1 2 3 4 -1\n", 279 | "Sample Output 2 :\n", 280 | "2\n", 281 | "'''\n", 282 | "\n", 283 | "from sys import stdin\n", 284 | "\n", 285 | "class Node :\n", 286 | " def __init__(self, data) :\n", 287 | " self.data = data\n", 288 | " self.next = None\n", 289 | "\n", 290 | "def midPoint(head) :\n", 291 | " if head is not None:\n", 292 | " slow = head\n", 293 | " fast = head\n", 294 | " while (fast.next != None) and (fast.next.next != None):\n", 295 | " slow = slow.next\n", 296 | " fast = fast.next.next\n", 297 | " return slow\n", 298 | " return None\n", 299 | " \n", 300 | "def takeInput() :\n", 301 | " head = None\n", 302 | " tail = None\n", 303 | " datas = list(map(int, stdin.readline().rstrip().split(\" \")))\n", 304 | " i = 0\n", 305 | " while (i < len(datas)) and (datas[i] != -1) :\n", 306 | " data = datas[i]\n", 307 | " newNode = Node(data)\n", 308 | " \n", 309 | " if head is None :\n", 310 | " head = newNode\n", 311 | " tail = newNode\n", 312 | " else :\n", 313 | " tail.next = newNode\n", 314 | " tail = newNode\n", 315 | " i += 1\n", 316 | " return head\n", 317 | "\n", 318 | "def printLinkedList(head) :\n", 319 | " while head is not None :\n", 320 | " print(head.data, end = \" \")\n", 321 | " head = head.next\n", 322 | " print()\n", 323 | "\n", 324 | "# Main\n", 325 | "t = int(stdin.readline().rstrip())\n", 326 | "while t > 0 : \n", 327 | " head = takeInput()\n", 328 | " mid = midPoint(head)\n", 329 | " if mid is not None :\n", 330 | " print(mid.data)\n", 331 | " t -= 1" 332 | ], 333 | "metadata": { 334 | "id": "PXyZvXZxdRnm" 335 | }, 336 | "execution_count": null, 337 | "outputs": [] 338 | }, 339 | { 340 | "cell_type": "code", 341 | "source": [ 342 | "'''\n", 343 | "Code : Merge two sorted LL\n", 344 | "\n", 345 | "You have been given two sorted(in ascending order) singly linked lists of integers.\n", 346 | "Write a function to merge them in such a way that the resulting singly linked list is also sorted(in ascending order) and return the new head to the list.\n", 347 | "\n", 348 | "Note :\n", 349 | "Try solving this in O(1) auxiliary space.\n", 350 | "\n", 351 | "No need to print the list, it has already been taken care.\n", 352 | "\n", 353 | "Input format :\n", 354 | "The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.\n", 355 | "\n", 356 | "The first line of each test case or query contains the elements of the first sorted singly linked list separated by a single space. \n", 357 | "\n", 358 | "The second line of the input contains the elements of the second sorted singly linked list separated by a single space. \n", 359 | "\n", 360 | "Remember/Consider :\n", 361 | "While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element\n", 362 | "\n", 363 | "Output :\n", 364 | "For each test case/query, print the resulting sorted singly linked list, separated by a single space.\n", 365 | "\n", 366 | "Output for every test case will be printed in a seperate line.\n", 367 | "\n", 368 | "Constraints :\n", 369 | "1 <= t = 10^2\n", 370 | "0 <= N <= 10 ^ 4\n", 371 | "0 <= M <= 10 ^ 4\n", 372 | "Where N and M denote the sizes of the singly linked lists. \n", 373 | "\n", 374 | "Time Limit: 1sec\n", 375 | "\n", 376 | "Sample Input 1 :\n", 377 | "1\n", 378 | "2 5 8 12 -1\n", 379 | "3 6 9 -1\n", 380 | "Sample Output 1 :\n", 381 | "2 3 5 6 8 9 12 \n", 382 | "\n", 383 | "Sample Input 2 :\n", 384 | "2\n", 385 | "2 5 8 12 -1\n", 386 | "3 6 9 -1\n", 387 | "10 40 60 60 80 -1\n", 388 | "10 20 30 40 50 60 90 100 -1\n", 389 | "Sample Output 2 :\n", 390 | "2 3 5 6 8 9 12 \n", 391 | "10 10 20 30 40 40 50 60 60 60 80 90 100\n", 392 | "'''\n", 393 | "\n", 394 | "from sys import stdin\n", 395 | "\n", 396 | "class Node :\n", 397 | " def __init__(self, data) :\n", 398 | " self.data = data\n", 399 | " self.next = None\n", 400 | "\n", 401 | "def mergeTwoSortedLinkedLists(head1, head2):\n", 402 | " if head1 is None:\n", 403 | " return head2\n", 404 | " \n", 405 | " elif head2 is None:\n", 406 | " return head1 \n", 407 | " \n", 408 | " else:\n", 409 | " if(head1.data <= head2.data):\n", 410 | " finalHead = head1\n", 411 | " finalTail = head1\n", 412 | " head1 = head1.next\n", 413 | " else:\n", 414 | " finalHead = head2\n", 415 | " finalTail = head2\n", 416 | " head2 = head2.next\n", 417 | " \n", 418 | " while(head1 and head2):\n", 419 | " if(head1.data <= head2.data):\n", 420 | " finalTail.next = head1\n", 421 | " finalTail = finalTail.next\n", 422 | " head1 = head1.next\n", 423 | " else:\n", 424 | " finalTail.next = head2\n", 425 | " finalTail = finalTail.next\n", 426 | " head2 = head2.next\n", 427 | "\n", 428 | " if head1:\n", 429 | " finalTail.next = head1\n", 430 | " if head2:\n", 431 | " finalTail.next = head2\n", 432 | "\n", 433 | " return finalHead \n", 434 | "\n", 435 | "#Taking Input Using Fast I/O\n", 436 | "def takeInput() :\n", 437 | " head = None\n", 438 | " tail = None\n", 439 | " datas = list(map(int, stdin.readline().rstrip().split(\" \")))\n", 440 | " i = 0\n", 441 | " while (i < len(datas)) and (datas[i] != -1) :\n", 442 | " data = datas[i]\n", 443 | " newNode = Node(data)\n", 444 | "\n", 445 | " if head is None :\n", 446 | " head = newNode\n", 447 | " tail = newNode\n", 448 | " else :\n", 449 | " tail.next = newNode\n", 450 | " tail = newNode\n", 451 | " i += 1\n", 452 | "\n", 453 | " return head\n", 454 | "\n", 455 | "def printLinkedList(head) :\n", 456 | " while head is not None :\n", 457 | " print(head.data, end = \" \")\n", 458 | " head = head.next\n", 459 | " print()\n", 460 | "\n", 461 | "# Main\n", 462 | "t = int(stdin.readline().rstrip())\n", 463 | "while t > 0 :\n", 464 | " head1 = takeInput()\n", 465 | " head2 = takeInput()\n", 466 | " newHead = mergeTwoSortedLinkedLists(head1, head2)\n", 467 | " printLinkedList(newHead)\n", 468 | " t -= 1" 469 | ], 470 | "metadata": { 471 | "id": "YhQ_rEX0iXPo" 472 | }, 473 | "execution_count": null, 474 | "outputs": [] 475 | }, 476 | { 477 | "cell_type": "code", 478 | "source": [ 479 | "'''\n", 480 | "Code : Merge Sort\n", 481 | "\n", 482 | "Given a singly linked list of integers, sort it using 'Merge Sort.'\n", 483 | "\n", 484 | "Note :\n", 485 | "No need to print the list, it has already been taken care. Only return the new head to the list.\n", 486 | "\n", 487 | "Input format :\n", 488 | "The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.\n", 489 | "\n", 490 | "The first and the only line of each test case or query contains the elements of the singly linked list separated by a single space.\n", 491 | "\n", 492 | "Remember/Consider :\n", 493 | "While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element\n", 494 | "\n", 495 | "Output format :\n", 496 | "For each test case/query, print the elements of the sorted singly linked list.\n", 497 | "\n", 498 | "Output for every test case will be printed in a seperate line.\n", 499 | "\n", 500 | "Constraints :\n", 501 | "1 <= t <= 10^2\n", 502 | "0 <= M <= 10^5\n", 503 | "Where M is the size of the singly linked list.\n", 504 | "\n", 505 | "Time Limit: 1sec\n", 506 | "\n", 507 | "Sample Input 1 :\n", 508 | "1\n", 509 | "10 9 8 7 6 5 4 3 -1\n", 510 | "Sample Output 1 :\n", 511 | " 3 4 5 6 7 8 9 10 \n", 512 | "\n", 513 | " Sample Output 2 :\n", 514 | "2\n", 515 | "-1\n", 516 | "10 -5 9 90 5 67 1 89 -1\n", 517 | "Sample Output 2 :\n", 518 | "-5 1 5 9 10 67 89 90 \n", 519 | "'''\n", 520 | "\n", 521 | "from sys import stdin, setrecursionlimit\n", 522 | "setrecursionlimit(10 ** 6)\n", 523 | "\n", 524 | "class Node :\n", 525 | " def __init__(self, data) :\n", 526 | " self.data = data\n", 527 | " self.next = None\n", 528 | "\n", 529 | " \n", 530 | "def midPoint(head) :\n", 531 | " if head is not None:\n", 532 | " slow = head\n", 533 | " fast = head\n", 534 | " while (fast.next != None) and (fast.next.next != None):\n", 535 | " slow = slow.next\n", 536 | " fast = fast.next.next\n", 537 | " return slow\n", 538 | " return None\n", 539 | "\n", 540 | "\n", 541 | "def mergeTwoSortedLinkedLists(head1, head2):\n", 542 | " if head1 is None:\n", 543 | " return head2\n", 544 | " \n", 545 | " elif head2 is None:\n", 546 | " return head1 \n", 547 | " \n", 548 | " else:\n", 549 | " if(head1.data <= head2.data):\n", 550 | " finalHead = head1\n", 551 | " finalTail = head1\n", 552 | " head1 = head1.next\n", 553 | " else:\n", 554 | " finalHead = head2\n", 555 | " finalTail = head2\n", 556 | " head2 = head2.next\n", 557 | " \n", 558 | " while(head1 and head2):\n", 559 | " if(head1.data <= head2.data):\n", 560 | " finalTail.next = head1\n", 561 | " finalTail = finalTail.next\n", 562 | " head1 = head1.next\n", 563 | " else:\n", 564 | " finalTail.next = head2\n", 565 | " finalTail = finalTail.next\n", 566 | " head2 = head2.next\n", 567 | "\n", 568 | " if head1:\n", 569 | " finalTail.next = head1\n", 570 | " if head2:\n", 571 | " finalTail.next = head2\n", 572 | "\n", 573 | " return finalHead \n", 574 | " \n", 575 | " \n", 576 | "def mergeSort(head) :\n", 577 | " if head is None or head.next is None:\n", 578 | " return head\n", 579 | " \n", 580 | " middleNode = midPoint(head)\n", 581 | "\n", 582 | " head1 = head\n", 583 | " head2 = middleNode.next\n", 584 | " middleNode.next = None\n", 585 | "\n", 586 | " finalHead1 = mergeSort(head1)\n", 587 | " finalHead2 = mergeSort(head2)\n", 588 | "\n", 589 | " sortedFinalHead = mergeTwoSortedLinkedLists(finalHead1,finalHead2)\n", 590 | "\n", 591 | " return sortedFinalHead\n", 592 | " \n", 593 | " \n", 594 | "#Taking Input Using Fast I/O\n", 595 | "def takeInput() :\n", 596 | " head = None\n", 597 | " tail = None\n", 598 | " datas = list(map(int, stdin.readline().rstrip().split(\" \")))\n", 599 | " i = 0\n", 600 | " while (i < len(datas)) and (datas[i] != -1) :\n", 601 | " data = datas[i]\n", 602 | " newNode = Node(data)\n", 603 | " if head is None :\n", 604 | " head = newNode\n", 605 | " tail = newNode\n", 606 | " else :\n", 607 | " tail.next = newNode\n", 608 | " tail = newNode\n", 609 | " i += 1\n", 610 | " return head\n", 611 | "\n", 612 | "def printLinkedList(head) :\n", 613 | " while head is not None :\n", 614 | " print(head.data, end = \" \")\n", 615 | " head = head.next\n", 616 | " print()\n", 617 | "\n", 618 | "#main\n", 619 | "t = int(stdin.readline().rstrip())\n", 620 | "while t > 0 :\n", 621 | " head = takeInput()\n", 622 | " newHead = mergeSort(head)\n", 623 | " printLinkedList(newHead)\n", 624 | " t -= 1" 625 | ], 626 | "metadata": { 627 | "id": "BKcJzAVe6qF0" 628 | }, 629 | "execution_count": null, 630 | "outputs": [] 631 | } 632 | ] 633 | } -------------------------------------------------------------------------------- /04_Linked-List/Linked-List-2/Quiz_Linked-List-2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddhapuraharsh/Data-Structures_Algorithms_Coding-Ninjas_Full-Course/149411eb7d59abd80d2a65f0ff1039b62558bb1b/04_Linked-List/Linked-List-2/Quiz_Linked-List-2.pdf -------------------------------------------------------------------------------- /05_Stacks-Queues/01_Stacks/Quiz_Stacks.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddhapuraharsh/Data-Structures_Algorithms_Coding-Ninjas_Full-Course/149411eb7d59abd80d2a65f0ff1039b62558bb1b/05_Stacks-Queues/01_Stacks/Quiz_Stacks.pdf -------------------------------------------------------------------------------- /05_Stacks-Queues/02_Queues/Problems_Queues.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "Problems_Queues", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "source": [ 22 | "**CONTENT**" 23 | ], 24 | "metadata": { 25 | "id": "kWrane1TyBNV" 26 | } 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": null, 31 | "metadata": { 32 | "id": "oU2iKf_H_OO2", 33 | "colab": { 34 | "base_uri": "https://localhost:8080/" 35 | }, 36 | "outputId": "a5787c06-8357-4230-ac83-e860b7cd5b99" 37 | }, 38 | "outputs": [ 39 | { 40 | "output_type": "stream", 41 | "name": "stdout", 42 | "text": [ 43 | "1\n", 44 | "2\n", 45 | "3\n", 46 | "4\n", 47 | "-1\n" 48 | ] 49 | } 50 | ], 51 | "source": [ 52 | "class QueueUsingArray:\n", 53 | "\n", 54 | " def __init__(self):\n", 55 | " self.__arr=[]\n", 56 | " self.__count=0\n", 57 | " self.__front=0\n", 58 | "\n", 59 | " def enqueue(self,data):\n", 60 | " self.__arr.append(data)\n", 61 | " self.__count += 1\n", 62 | "\n", 63 | " def dequeue(self):\n", 64 | " if self.__count==0:\n", 65 | " return -1\n", 66 | " element=self.__arr[self.__front]\n", 67 | " self.__count -= 1\n", 68 | " self.__front += 1\n", 69 | " return element \n", 70 | "\n", 71 | " def front(self):\n", 72 | " if self.__count==0:\n", 73 | " return -1\n", 74 | " return self.__arr[self.__front] \n", 75 | " \n", 76 | " def size(self):\n", 77 | " return self.__count\n", 78 | " \n", 79 | " def isEmpty(self):\n", 80 | " return self.size()==0\n", 81 | "\n", 82 | "q=QueueUsingArray()\n", 83 | "q.enqueue(1)\n", 84 | "q.enqueue(2)\n", 85 | "q.enqueue(3)\n", 86 | "q.enqueue(4)\n", 87 | "\n", 88 | "while(q.isEmpty()is False):\n", 89 | " print(q.front())\n", 90 | " q.dequeue()\n", 91 | "\n", 92 | "print(q.dequeue())" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "source": [ 98 | "#inbuilt stack as list\n", 99 | "s=[1,2,3]\n", 100 | "s.append(4)\n", 101 | "s.append(5)\n", 102 | "print(s.pop())\n", 103 | "print(s.pop())\n", 104 | "print()\n", 105 | "\n", 106 | "#inbuilt queue\n", 107 | "import queue\n", 108 | "q=queue.Queue()\n", 109 | "q.put(1)\n", 110 | "q.put(2)\n", 111 | "q.put(3)\n", 112 | "q.put(4)\n", 113 | "while not q.empty():\n", 114 | " print(q.get())\n", 115 | "print()\n", 116 | "\n", 117 | "#inbuilt stack\n", 118 | "import queue\n", 119 | "q=queue.LifoQueue()\n", 120 | "q.put(1)\n", 121 | "q.put(2)\n", 122 | "q.put(3)\n", 123 | "while not q.empty():\n", 124 | " print(q.get())\n", 125 | "print()" 126 | ], 127 | "metadata": { 128 | "colab": { 129 | "base_uri": "https://localhost:8080/" 130 | }, 131 | "id": "B0p9971DASqb", 132 | "outputId": "c959f99b-a1f7-4c90-8fb8-36cba731eed8" 133 | }, 134 | "execution_count": 2, 135 | "outputs": [ 136 | { 137 | "output_type": "stream", 138 | "name": "stdout", 139 | "text": [ 140 | "5\n", 141 | "4\n", 142 | "\n", 143 | "1\n", 144 | "2\n", 145 | "3\n", 146 | "4\n", 147 | "\n", 148 | "3\n", 149 | "2\n", 150 | "1\n", 151 | "\n" 152 | ] 153 | } 154 | ] 155 | }, 156 | { 157 | "cell_type": "markdown", 158 | "source": [ 159 | "**CONTENT PROBLEMS**" 160 | ], 161 | "metadata": { 162 | "id": "3q72RfpW0utO" 163 | } 164 | }, 165 | { 166 | "cell_type": "code", 167 | "source": [ 168 | "'''\n", 169 | "Queue Using LL\n", 170 | "\n", 171 | "Implement a Queue Data Structure specifically to store integer data using a Singly Linked List.\n", 172 | "The data members should be private.\n", 173 | "\n", 174 | "You need to implement the following public functions :\n", 175 | "1. Constructor: It initialises the data members as required.\n", 176 | "2. enqueue(data) : This function should take one argument of type integer. It enqueues the element into \n", 177 | "the queue and returns nothing.\n", 178 | "3. dequeue() : It dequeues/removes the element from the front of the queue and in turn, returns \n", 179 | "the element being dequeued or removed. In case the queue is empty, it returns -1.\n", 180 | "4. front() : It returns the element being kept at the front of the queue. In case the queue is empty, it returns -1.\n", 181 | "5. getSize() : It returns the size of the queue at any given instance of time.\n", 182 | "6. isEmpty() : It returns a boolean value indicating whether the queue is empty or not.\n", 183 | "\n", 184 | "Operations Performed on the Stack:\n", 185 | "Query-1(Denoted by an integer 1): Enqueues an integer data to the queue.\n", 186 | "Query-2(Denoted by an integer 2): Dequeues the data kept at the front of the queue and returns it to the caller.\n", 187 | "Query-3(Denoted by an integer 3): Fetches and returns the data being kept at the front of the queue but doesn't \n", 188 | "remove it, unlike the dequeue function.\n", 189 | "Query-4(Denoted by an integer 4): Returns the current size of the queue.\n", 190 | "Query-5(Denoted by an integer 5): Returns a boolean value denoting whether the queue is empty or not.\n", 191 | "\n", 192 | "Input Format:\n", 193 | "The first line contains an integer 'q' which denotes the number of queries to be run against each operation on the queue. \n", 194 | "Then the test cases follow.\n", 195 | "\n", 196 | "Every 'q' lines represent an operation that needs to be performed.\n", 197 | "\n", 198 | "For the enqueue operation, the input line will contain two integers separated by a single space, representing the type of the operation in integer and the integer data being enqueued into the queue.\n", 199 | "\n", 200 | "For the rest of the operations on the queue, the input line will contain only one integer value, representing the query being performed on the queue.\n", 201 | "\n", 202 | "Output Format:\n", 203 | "For Query-1, you do not need to return anything.\n", 204 | "For Query-2, prints the data being dequeued from the queue.\n", 205 | "For Query-3, prints the data kept on the front of the queue.\n", 206 | "For Query-4, prints the current size of the queue.\n", 207 | "For Query-5, prints 'true' or 'false'(without quotes).\n", 208 | "\n", 209 | "Output for every query will be printed in a separate line.\n", 210 | " \n", 211 | "Note:\n", 212 | "You are not required to print anything explicitly. It has already been taken care of. Just implement the functions.\n", 213 | "\n", 214 | "Constraints:\n", 215 | "1 <= q <= 10^5\n", 216 | "1 <= x <= 5\n", 217 | "-2^31 <= data <= 2^31 - 1 and data != -1\n", 218 | "\n", 219 | "Where 'q' is the total number of queries being performed on the queue, 'x' is the range for every query and data represents the integer pushed into the queue. \n", 220 | "\n", 221 | "Time Limit: 1 second\n", 222 | "\n", 223 | "Sample Input 1:\n", 224 | "7\n", 225 | "1 17\n", 226 | "1 23\n", 227 | "1 11\n", 228 | "2\n", 229 | "2\n", 230 | "2\n", 231 | "2\n", 232 | "Sample Output 1:\n", 233 | "17\n", 234 | "23\n", 235 | "11\n", 236 | "-1\n", 237 | "\n", 238 | "Sample Input 2:\n", 239 | "3\n", 240 | "2\n", 241 | "1 10\n", 242 | "4\n", 243 | "Sample Output 2:\n", 244 | "-1 \n", 245 | "1\n", 246 | "'''\n", 247 | "\n", 248 | "from sys import stdin\n", 249 | "\n", 250 | "class Node :\n", 251 | " def __init__(self, data) :\n", 252 | " self.data = data\n", 253 | " self.next = None\n", 254 | "\n", 255 | "class Queue :\n", 256 | " \n", 257 | " def __init__(self):\n", 258 | " self.__head = None\n", 259 | " self.__tail = None\n", 260 | " self.__count = 0\n", 261 | " \n", 262 | " def enqueue(self, data) :\n", 263 | " newNode = Node(data)\n", 264 | " self.__count += 1\n", 265 | " if self.__head == None :\n", 266 | " self.__head = newNode\n", 267 | " else:\n", 268 | " \tself.__tail.next = newNode\n", 269 | " self.__tail = newNode\n", 270 | " return\n", 271 | "\n", 272 | " def dequeue(self) :\n", 273 | " if self.isEmpty():\n", 274 | " return -1\n", 275 | " removedNode = self.__head.data\n", 276 | " self.__head = self.__head.next\n", 277 | " self.__count -= 1\n", 278 | " return removedNode\n", 279 | " \n", 280 | " def getSize(self) :\n", 281 | " return self.__count\n", 282 | " \n", 283 | " def isEmpty(self) :\n", 284 | " return self.__count == 0\n", 285 | "\n", 286 | " def front(self) :\n", 287 | " if self.__head == None :\n", 288 | " return -1\n", 289 | " return self.__head.data\n", 290 | " \n", 291 | "#main\n", 292 | "q = int(stdin.readline().strip())\n", 293 | "queue = Queue()\n", 294 | "while q > 0 :\n", 295 | " inputs = stdin.readline().strip().split(\" \")\n", 296 | " choice = int(inputs[0])\n", 297 | " if choice == 1 :\n", 298 | " data = int(inputs[1])\n", 299 | " queue.enqueue(data)\n", 300 | " elif choice == 2 :\n", 301 | " print(queue.dequeue())\n", 302 | " elif choice == 3 :\n", 303 | " print(queue.front())\n", 304 | " elif choice == 4 : \n", 305 | " print(queue.getSize())\n", 306 | " else :\n", 307 | " if queue.isEmpty() :\n", 308 | " print(\"true\")\n", 309 | " else :\n", 310 | " print(\"false\")\n", 311 | " q -= 1" 312 | ], 313 | "metadata": { 314 | "id": "UJJvbg_gy88I" 315 | }, 316 | "execution_count": 1, 317 | "outputs": [] 318 | }, 319 | { 320 | "cell_type": "code", 321 | "source": [ 322 | "class QueueUsingTwoStacks:\n", 323 | " def __init__(self):\n", 324 | " self.__s1=[]\n", 325 | " self.__s2=[]\n", 326 | " def enqueue(self,data):\n", 327 | " #(O(n))\n", 328 | " while(len(self.__s1)!=0):\n", 329 | " self.__s2.append(self.__s1.pop())\n", 330 | " self.__s1.append(data)\n", 331 | " \n", 332 | " while(len(self.__s2)!=0):\n", 333 | " self.__s1.append(self.__s2.pop())\n", 334 | " return\n", 335 | " \n", 336 | " def dequeue(self):\n", 337 | " #O(1)\n", 338 | " if len(self.__s1)==0:\n", 339 | " return -1\n", 340 | " return self.__s1.pop()\n", 341 | " \n", 342 | " def front(self):\n", 343 | " if len(self.__s1)==0:\n", 344 | " return -1\n", 345 | " return self.__s1[-1]\n", 346 | " \n", 347 | " def size(self):\n", 348 | " return len(self.__s1)\n", 349 | " \n", 350 | " def isEmpty(self):\n", 351 | " return self.size()==0\n", 352 | " \n", 353 | "q=QueueUsingTwoStacks()\n", 354 | "q.enqueue(1)\n", 355 | "q.enqueue(2)\n", 356 | "q.enqueue(3)\n", 357 | "q.enqueue(4)\n", 358 | "\n", 359 | "while(q.isEmpty() is False):\n", 360 | " print(q.front())\n", 361 | " q.dequeue()" 362 | ], 363 | "metadata": { 364 | "colab": { 365 | "base_uri": "https://localhost:8080/" 366 | }, 367 | "id": "vBEo3f4nCTlJ", 368 | "outputId": "97ec29fc-cf38-4b20-dbfc-8ef535382922" 369 | }, 370 | "execution_count": 3, 371 | "outputs": [ 372 | { 373 | "output_type": "stream", 374 | "name": "stdout", 375 | "text": [ 376 | "1\n", 377 | "2\n", 378 | "3\n", 379 | "4\n" 380 | ] 381 | } 382 | ] 383 | }, 384 | { 385 | "cell_type": "code", 386 | "source": [ 387 | "'''\n", 388 | "Stack Using 2 Queues\n", 389 | "\n", 390 | "Implement a Stack Data Structure specifically to store integer data using two Queues. You have to implement it \n", 391 | "in such a way that the push operation is done in O(1) time and the pop and top operations are done in O(N) time.\n", 392 | "There should be two data members, both being Queues to store the data internally. You may use the inbuilt Queue.\n", 393 | "\n", 394 | "Implement the following public functions :\n", 395 | "1. Constructor: It initialises the data members as required.\n", 396 | "2. push(data) : This function should take one argument of type integer. It pushes the element into the stack and returns nothing.\n", 397 | "3. pop() : It pops the element from the top of the stack and in turn, returns the element being popped or deleted. \n", 398 | "In case the stack is empty, it returns -1.\n", 399 | "4. top : It returns the element being kept at the top of the stack. In case the stack is empty, it returns -1.\n", 400 | "5. size() : It returns the size of the stack at any given instance of time.\n", 401 | "6. isEmpty() : It returns a boolean value indicating whether the stack is empty or not.\n", 402 | "\n", 403 | "Operations Performed on the Stack:\n", 404 | "Query-1(Denoted by an integer 1): Pushes an integer data to the stack.\n", 405 | "Query-2(Denoted by an integer 2): Pops the data kept at the top of the stack and returns it to the caller.\n", 406 | "Query-3(Denoted by an integer 3): Fetches and returns the data being kept at the top of the stack but doesn't \n", 407 | "remove it, unlike the pop function.\n", 408 | "Query-4(Denoted by an integer 4): Returns the current size of the stack.\n", 409 | "Query-5(Denoted by an integer 5): Returns a boolean value denoting whether the stack is empty or not.\n", 410 | "\n", 411 | "Input Format:\n", 412 | "The first line contains an integer 'q' which denotes the number of queries to be run against each operation in the stack. \n", 413 | "Then the test cases follow.\n", 414 | "\n", 415 | "Every 'q' lines represent an operation that needs to be performed.\n", 416 | "\n", 417 | "For the push operation, the input line will contain two integers separated by a single space, representing the type of the operation in integer and the integer data being pushed into the stack.\n", 418 | "\n", 419 | "For the rest of the operations on the stack, the input line will contain only one integer value, representing the query being performed on the stack.\n", 420 | "Output Format:\n", 421 | "For Query-1, you do not need to return anything.\n", 422 | "For Query-2, prints the data being popped from the stack.\n", 423 | "For Query-3, prints the data kept on the top of the stack.\n", 424 | "For Query-4, prints the current size of the stack.\n", 425 | "For Query-5, prints 'true' or 'false'(without quotes).\n", 426 | "\n", 427 | "Output for every query will be printed in a separate line.\n", 428 | " \n", 429 | "Note:\n", 430 | "You are not required to print anything explicitly. It has already been taken care of. Just implement the function.\n", 431 | "Constraints:\n", 432 | "1 <= q <= 100\n", 433 | "1 <= x <= 5\n", 434 | "-2^31 <= data <= 2^31 - 1 and data != -1\n", 435 | "\n", 436 | "Where 'q' is the total number of queries being performed on the stack, 'x' is the range for every query and data represents the integer pushed into the stack. \n", 437 | "\n", 438 | "Time Limit: 1 second\n", 439 | "\n", 440 | "Sample Input 1:\n", 441 | "6\n", 442 | "1 13\n", 443 | "1 47\n", 444 | "4\n", 445 | "5\n", 446 | "2\n", 447 | "3\n", 448 | "Sample Output 1:\n", 449 | "2\n", 450 | "false\n", 451 | "47\n", 452 | "13\n", 453 | "\n", 454 | "Sample Input 2:\n", 455 | "4\n", 456 | "5\n", 457 | "2\n", 458 | "1 10\n", 459 | "5\n", 460 | " Sample Output 2:\n", 461 | "true\n", 462 | "-1\n", 463 | "false\n", 464 | "'''\n", 465 | "\n", 466 | "from sys import stdin\n", 467 | "import queue\n", 468 | "\n", 469 | "class Stack :\n", 470 | " def __init__(self):\n", 471 | " self.__q1 = queue.Queue()\n", 472 | " self.__q2 = queue.Queue()\n", 473 | " \n", 474 | " def push(self, data) :\n", 475 | " self.__q2.put(data)\n", 476 | " while(self.__q1.qsize() != 0):\n", 477 | " self.__q2.put(self.__q1.get())\n", 478 | " self.__q1,self.__q2 = self.__q2,self.__q1\n", 479 | " return\n", 480 | " \n", 481 | " def pop(self) :\n", 482 | " if self.isEmpty():\n", 483 | " return -1\n", 484 | " return self.__q1.get()\n", 485 | " \n", 486 | " def getSize(self) :\n", 487 | " return self.__q1.qsize()\n", 488 | " \n", 489 | " def isEmpty(self) :\n", 490 | " return self.getSize()==0\n", 491 | " \n", 492 | " def top(self) :\n", 493 | " if self.isEmpty():\n", 494 | " return -1\n", 495 | " return self.__q1.queue[0]\n", 496 | "\n", 497 | "#main\n", 498 | "q = int(stdin.readline().strip())\n", 499 | "stack = Stack()\n", 500 | "while q > 0 :\n", 501 | "\tinputs = stdin.readline().strip().split(\" \")\n", 502 | "\tchoice = int(inputs[0])\n", 503 | "\tif choice == 1 :\n", 504 | "\t\tdata = int(inputs[1])\n", 505 | "\t\tstack.push(data)\n", 506 | "\telif choice == 2 :\n", 507 | "\t\tprint(stack.pop())\n", 508 | "\telif choice == 3 :\n", 509 | "\t\tprint(stack.top())\n", 510 | "\telif choice == 4 : \n", 511 | "\t\tprint(stack.getSize())\n", 512 | "\telse :\n", 513 | "\t\tif stack.isEmpty() :\n", 514 | "\t\t\tprint(\"true\")\n", 515 | "\t\telse :\n", 516 | "\t\t\tprint(\"false\")\n", 517 | "\tq -= 1" 518 | ], 519 | "metadata": { 520 | "id": "JOjFkf7fKSbT" 521 | }, 522 | "execution_count": null, 523 | "outputs": [] 524 | }, 525 | { 526 | "cell_type": "code", 527 | "source": [ 528 | "'''\n", 529 | "Reverse Queue\n", 530 | "\n", 531 | "You have been given a queue that can store integers as the data. You are required to write a function that reverses \n", 532 | "the populated queue itself without using any other data structures.\n", 533 | "\n", 534 | "Input Format:\n", 535 | "The first list of input contains an integer 't' denoting the number of test cases/queries to be run.\n", 536 | "Then the test cases follow.\n", 537 | "\n", 538 | "The first line input for each test case/query contains an integer N, denoting the total number of elements in the queue.\n", 539 | "\n", 540 | "The second line of input contains N integers separated by a single space, representing the order in which the elements \n", 541 | "are enqueued into the queue.\n", 542 | "\n", 543 | "Output Format:\n", 544 | "For each test case/query, the only line of output prints the order in which the queue elements are dequeued, all of \n", 545 | "them separated by a single space.\n", 546 | "\n", 547 | "Output for every test case/query will be printed on a new line. \n", 548 | "\n", 549 | "Note:\n", 550 | "You are not required to print the expected output explicitly, it has already been taken care of. Just make the \n", 551 | "changes in the input queue itself.\n", 552 | "\n", 553 | "Constraints:\n", 554 | "1 <= t <= 100\n", 555 | "1 <= N <= 10^4\n", 556 | "-2^31 <= data <= 2^31 - 1\n", 557 | "\n", 558 | "Time Limit: 1sec \n", 559 | "\n", 560 | "Sample Input 1:\n", 561 | "1\n", 562 | "6\n", 563 | "1 2 3 4 5 10\n", 564 | "\n", 565 | "Note:\n", 566 | "Here, 1 is at the front and 10 is at the rear of the queue.\n", 567 | "\n", 568 | "Sample Output 1:\n", 569 | "10 5 4 3 2 1\n", 570 | "\n", 571 | "Sample Input 2:\n", 572 | "2\n", 573 | "5\n", 574 | "2 8 15 1 10\n", 575 | "3\n", 576 | "10 20 30\n", 577 | "Sample Output 2:\n", 578 | "10 1 15 8 2 \n", 579 | "30 20 10 \n", 580 | "'''\n", 581 | "\n", 582 | "from sys import stdin, setrecursionlimit\n", 583 | "import queue\n", 584 | "\n", 585 | "setrecursionlimit(10 ** 6)\n", 586 | "\n", 587 | "def reverseQueue(inputQueue) :\n", 588 | " if inputQueue.empty():\n", 589 | " return \n", 590 | " frontElement = inputQueue.get()\n", 591 | " reverseQueue(inputQueue)\n", 592 | " inputQueue.put(frontElement)\n", 593 | "\n", 594 | "def takeInput():\n", 595 | " n = int(stdin.readline().strip())\n", 596 | " qu = queue.Queue()\n", 597 | " values = list(map(int, stdin.readline().strip().split()))\n", 598 | " for i in range(n) :\n", 599 | " qu.put(values[i])\n", 600 | " return qu\n", 601 | "\n", 602 | "#main\n", 603 | "t = int(stdin.readline().strip())\n", 604 | "while t > 0 :\n", 605 | " qu = takeInput()\n", 606 | " reverseQueue(qu)\n", 607 | " while not qu.empty() :\n", 608 | " print(qu.get(), end = \" \")\n", 609 | " print()\n", 610 | " t -= 1" 611 | ], 612 | "metadata": { 613 | "id": "UjDlybpdOdQK" 614 | }, 615 | "execution_count": null, 616 | "outputs": [] 617 | }, 618 | { 619 | "cell_type": "code", 620 | "source": [ 621 | "'''\n", 622 | "Reverse the First K Elements in the Queue\n", 623 | "\n", 624 | "For a given queue containing all integer data, reverse the first K elements.\n", 625 | "You have been required to make the desired change in the input queue itself.\n", 626 | "\n", 627 | "Input Format :\n", 628 | "The first line of input would contain two integers N and K, separated by a single space. They denote the total \n", 629 | "number of elements in the queue and the count with which the elements need to be reversed respectively.\n", 630 | "\n", 631 | "The second line of input contains N integers separated by a single space, representing the order in which the \n", 632 | "elements are enqueued into the queue.\n", 633 | "\n", 634 | "Output Format:\n", 635 | "The only line of output prints the updated order in which the queue elements are dequeued, all of them separated by a single space. \n", 636 | "\n", 637 | "Note:\n", 638 | "You are not required to print the expected output explicitly, it has already been taken care of. Just make the changes in the input queue itself.\n", 639 | "\n", 640 | "Contraints :\n", 641 | "1 <= N <= 10^6\n", 642 | "1 <= K <= N\n", 643 | "-2^31 <= data <= 2^31 - 1\n", 644 | "\n", 645 | "Time Limit: 1sec\n", 646 | "\n", 647 | "Sample Input 1:\n", 648 | "5 3\n", 649 | "1 2 3 4 5\n", 650 | "Sample Output 1:\n", 651 | "3 2 1 4 5\n", 652 | "\n", 653 | "Sample Input 2:\n", 654 | "7 7\n", 655 | "3 4 2 5 6 7 8\n", 656 | "Sample Output 2:\n", 657 | "8 7 6 5 2 4 3\n", 658 | "'''\n", 659 | "\n", 660 | "from sys import stdin\n", 661 | "import queue\n", 662 | "\n", 663 | "def reverseKElements(inputQueue, k) :\n", 664 | " if k==0:\n", 665 | " return\n", 666 | " frontElement = inputQueue.get()\n", 667 | " reverseKElements(inputQueue, k-1)\n", 668 | " inputQueue.put(frontElement)\n", 669 | " \n", 670 | " return inputQueue\n", 671 | " \n", 672 | "#Takes a list as a stack and returns whether the stack is empty or not\n", 673 | "def isEmpty(stack) :\n", 674 | " return len(stack) == 0\n", 675 | "\n", 676 | "#Takes a list as a stack and returns the element at the top\n", 677 | "def top(stack) :\n", 678 | " #assuming the stack is never empty\n", 679 | " return stack[len(stack) - 1]\n", 680 | "\n", 681 | "def takeInput():\n", 682 | " n_k = list(map(int, stdin.readline().strip().split(\" \")))\n", 683 | " n = n_k[0]\n", 684 | " k = n_k[1]\n", 685 | " qu = queue.Queue()\n", 686 | " values = list(map(int, stdin.readline().strip().split()))\n", 687 | " for i in range(n) :\n", 688 | " qu.put(values[i])\n", 689 | " return n, k, qu\n", 690 | "\n", 691 | "#main\n", 692 | "n, k, qu = takeInput()\n", 693 | "qu = reverseKElements(qu, k)\n", 694 | "for i in range(n-k):\n", 695 | " qu.put(qu.get())\n", 696 | " \n", 697 | "while not qu.empty() :\n", 698 | " print(qu.get(), end = \" \")" 699 | ], 700 | "metadata": { 701 | "id": "6kL5dOtpUjNu" 702 | }, 703 | "execution_count": null, 704 | "outputs": [] 705 | } 706 | ] 707 | } -------------------------------------------------------------------------------- /05_Stacks-Queues/02_Queues/Quiz_Queues.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddhapuraharsh/Data-Structures_Algorithms_Coding-Ninjas_Full-Course/149411eb7d59abd80d2a65f0ff1039b62558bb1b/05_Stacks-Queues/02_Queues/Quiz_Queues.pdf -------------------------------------------------------------------------------- /06_Binary-Trees/Binary-Trees-1/Quiz_Binary-Trees-1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddhapuraharsh/Data-Structures_Algorithms_Coding-Ninjas_Full-Course/149411eb7d59abd80d2a65f0ff1039b62558bb1b/06_Binary-Trees/Binary-Trees-1/Quiz_Binary-Trees-1.pdf -------------------------------------------------------------------------------- /06_Binary-Trees/Binary-Trees-2/Assignment_Problems_Binary_Trees_2.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "Assignment-Problems_Binary-Trees-2", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "source": [ 22 | "**ASSIGNMENT PROBLEMS**" 23 | ], 24 | "metadata": { 25 | "id": "3HBQiu7YCTGh" 26 | } 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": 1, 31 | "metadata": { 32 | "id": "22-rRfmJBuu3" 33 | }, 34 | "outputs": [], 35 | "source": [ 36 | "'''\n", 37 | "Create & Insert Duplicate Node\n", 38 | "\n", 39 | "For a given a Binary Tree of type integer, duplicate every node of the tree and attach it to the left of itself.\n", 40 | "The root will remain the same. So you just need to insert nodes in the given Binary Tree.\n", 41 | "\n", 42 | "You can see that every node in the input tree has been duplicated and inserted to the left of itself.\n", 43 | "\n", 44 | "Input format :\n", 45 | "The first and the only line of input will contain the node data, all separated by a single space. \n", 46 | "Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data.\n", 47 | "\n", 48 | "Output Format :\n", 49 | "The updated tree will be printed in a level order fashion where each level will be printed on a new line. \n", 50 | "Elements on every level will be printed in a linear fashion. A single space will separate them.\n", 51 | "\n", 52 | "Note:\n", 53 | "You are not required to print anything explicitly. It has already been taken care of. Just implement the \n", 54 | "function to achieve the desired structure of the tree.\n", 55 | "\n", 56 | "Constraints :\n", 57 | "1 <= N <= 10^5\n", 58 | "Where N is the total number of nodes in the binary tree.\n", 59 | "\n", 60 | "Time Limit: 1 sec\n", 61 | "\n", 62 | "Sample Input 1:\n", 63 | "10 20 30 40 50 -1 60 -1 -1 -1 -1 -1 -1\n", 64 | "Sample Output 1:\n", 65 | "10 \n", 66 | "10 30 \n", 67 | "20 30 60 \n", 68 | "20 50 60 \n", 69 | "40 50 \n", 70 | "40 \n", 71 | "\n", 72 | "Sample Input 2:\n", 73 | "8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1\n", 74 | "Sample Output 2:\n", 75 | "8 \n", 76 | "8 10 \n", 77 | "5 10 \n", 78 | "5 6 \n", 79 | "2 6 7 \n", 80 | "2 7\n", 81 | "'''\n", 82 | "\n", 83 | "from sys import stdin, setrecursionlimit\n", 84 | "import queue\n", 85 | "\n", 86 | "setrecursionlimit(10 ** 6)\n", 87 | "\n", 88 | "class BinaryTreeNode:\n", 89 | " def __init__(self, data):\n", 90 | " self.data = data\n", 91 | " self.left = None\n", 92 | " self.right = None\n", 93 | "\n", 94 | "def insertDuplicateNode(root):\n", 95 | " if root is None:\n", 96 | " return None\n", 97 | " \n", 98 | " insertDuplicateNode(root.left)\n", 99 | " insertDuplicateNode(root.right)\n", 100 | " \n", 101 | " duplicate = BinaryTreeNode(root.data)\n", 102 | " duplicate.left = root.left\n", 103 | " root.left = duplicate\n", 104 | " \n", 105 | " return root\n", 106 | " \n", 107 | "\n", 108 | "#Taking level-order input using fast I/O method\n", 109 | "def takeInput():\n", 110 | " levelOrder = list(map(int, stdin.readline().strip().split(\" \")))\n", 111 | " start = 0\n", 112 | " length = len(levelOrder)\n", 113 | " if length == 1 :\n", 114 | " return None \n", 115 | " root = BinaryTreeNode(levelOrder[start])\n", 116 | " start += 1\n", 117 | " q = queue.Queue()\n", 118 | " q.put(root)\n", 119 | " while not q.empty():\n", 120 | " currentNode = q.get()\n", 121 | " leftChild = levelOrder[start]\n", 122 | " start += 1\n", 123 | " if leftChild != -1:\n", 124 | " leftNode = BinaryTreeNode(leftChild)\n", 125 | " currentNode.left =leftNode\n", 126 | " q.put(leftNode)\n", 127 | " rightChild = levelOrder[start]\n", 128 | " start += 1\n", 129 | " if rightChild != -1:\n", 130 | " rightNode = BinaryTreeNode(rightChild)\n", 131 | " currentNode.right =rightNode\n", 132 | " q.put(rightNode)\n", 133 | " return root\n", 134 | " \n", 135 | "def printLevelWise(root):\n", 136 | " if root is None:\n", 137 | " return\n", 138 | " inputQ = queue.Queue()\n", 139 | " outputQ = queue.Queue()\n", 140 | " inputQ.put(root)\n", 141 | " while not inputQ.empty(): \n", 142 | " while not inputQ.empty(): \n", 143 | " curr = inputQ.get()\n", 144 | " print(curr.data, end=' ')\n", 145 | " if curr.left!=None:\n", 146 | " outputQ.put(curr.left)\n", 147 | " if curr.right!=None:\n", 148 | " outputQ.put(curr.right) \n", 149 | " print()\n", 150 | " inputQ, outputQ = outputQ, inputQ\n", 151 | "\n", 152 | "# Main\n", 153 | "root = takeInput()\n", 154 | "insertDuplicateNode(root)\n", 155 | "printLevelWise(root)" 156 | ] 157 | }, 158 | { 159 | "cell_type": "code", 160 | "source": [ 161 | "'''\n", 162 | "Minimum and Maximum in the Binary Tree\n", 163 | "\n", 164 | "For a given a Binary Tree of type integer, find and return the minimum and the maximum data values.\n", 165 | "Return the output as an object of Pair class, which is already created.\n", 166 | "\n", 167 | "Note:\n", 168 | "All the node data will be unique and hence there will always exist a minimum and maximum node data.\n", 169 | "\n", 170 | "Input Format:\n", 171 | "The first and the only line of input will contain the node data, all separated by a single space. \n", 172 | "Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data.\n", 173 | "\n", 174 | "Output Format:\n", 175 | "The only line of output prints two integers denoting the minimum and the maximum data values respectively. \n", 176 | "A single line will separate them both.\n", 177 | "\n", 178 | "Constraints:\n", 179 | "2 <= N <= 10^5\n", 180 | "Where N is the total number of nodes in the binary tree.\n", 181 | "\n", 182 | "Time Limit: 1 sec\n", 183 | "\n", 184 | "Sample Input 1:\n", 185 | "8 3 10 1 6 -1 14 -1 -1 4 7 13 -1 -1 -1 -1 -1 -1 -1\n", 186 | "Sample Output 1:\n", 187 | "1 14\n", 188 | "\n", 189 | "Sample Input 2:\n", 190 | "10 20 60 -1 -1 3 50 -1 -1 -1 -1 \n", 191 | "Sample Output 2:\n", 192 | "3 60\n", 193 | "'''\n", 194 | "\n", 195 | "from sys import stdin, setrecursionlimit\n", 196 | "import queue\n", 197 | "\n", 198 | "setrecursionlimit(10 ** 6)\n", 199 | "\n", 200 | "class BinaryTreeNode:\n", 201 | " def __init__(self, data):\n", 202 | " self.data = data\n", 203 | " self.left = None\n", 204 | " self.right = None\n", 205 | "\n", 206 | "class Pair :\n", 207 | " def __init__(self, minimum, maximum) :\n", 208 | " self.minimum = minimum\n", 209 | " self.maximum = maximum\n", 210 | "\n", 211 | "def getMinAndMax(root) :\n", 212 | " if root is None:\n", 213 | " return Pair(float('inf'),float('-inf'))\n", 214 | " \n", 215 | " leftMinMax = getMinAndMax(root.left)\n", 216 | " rightMinMax = getMinAndMax(root.right)\n", 217 | " \n", 218 | " return Pair(\n", 219 | " min(root.data,leftMinMax.minimum,rightMinMax.minimum),\n", 220 | " max(root.data,leftMinMax.maximum,rightMinMax.maximum)\n", 221 | " )\n", 222 | " \n", 223 | "\n", 224 | "#Taking level-order input using fast I/O method\n", 225 | "def takeInput():\n", 226 | " levelOrder = list(map(int, stdin.readline().strip().split(\" \")))\n", 227 | " start = 0\n", 228 | " length = len(levelOrder)\n", 229 | " if length == 1 :\n", 230 | " return None\n", 231 | " root = BinaryTreeNode(levelOrder[start])\n", 232 | " start += 1\n", 233 | " q = queue.Queue()\n", 234 | " q.put(root)\n", 235 | " while not q.empty():\n", 236 | " currentNode = q.get()\n", 237 | " leftChild = levelOrder[start]\n", 238 | " start += 1\n", 239 | " if leftChild != -1:\n", 240 | " leftNode = BinaryTreeNode(leftChild)\n", 241 | " currentNode.left =leftNode\n", 242 | " q.put(leftNode)\n", 243 | " rightChild = levelOrder[start]\n", 244 | " start += 1\n", 245 | " if rightChild != -1:\n", 246 | " rightNode = BinaryTreeNode(rightChild)\n", 247 | " currentNode.right =rightNode\n", 248 | " q.put(rightNode)\n", 249 | " return root\n", 250 | " \n", 251 | "def printLevelWise(root):\n", 252 | " if root is None:\n", 253 | " return\n", 254 | " inputQ = queue.Queue()\n", 255 | " outputQ = queue.Queue()\n", 256 | " inputQ.put(root)\n", 257 | " while not inputQ.empty():\n", 258 | " while not inputQ.empty():\n", 259 | " curr = inputQ.get()\n", 260 | " print(curr.data, end=' ')\n", 261 | " if curr.left!=None:\n", 262 | " outputQ.put(curr.left)\n", 263 | " if curr.right!=None:\n", 264 | " outputQ.put(curr.right)\n", 265 | " print()\n", 266 | " inputQ, outputQ = outputQ, inputQ\n", 267 | "\n", 268 | "# Main\n", 269 | "root = takeInput()\n", 270 | "pair = getMinAndMax(root)\n", 271 | "print(str(str(pair.minimum) + \" \" + str(pair.maximum)))" 272 | ], 273 | "metadata": { 274 | "id": "NDaix--xMEsN" 275 | }, 276 | "execution_count": null, 277 | "outputs": [] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "source": [ 282 | "'''\n", 283 | "Level order traversal\n", 284 | "\n", 285 | "For a given a Binary Tree of type integer, print it in a level order fashion where each level will be printed on a new line. \n", 286 | "Elements on every level will be printed in a linear fashion and a single space will separate them.\n", 287 | "\n", 288 | "Where each new line denotes the level in the tree.\n", 289 | "\n", 290 | "Input Format:\n", 291 | "The first and the only line of input will contain the node data, all separated by a single space. \n", 292 | "Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data.\n", 293 | "\n", 294 | "Output Format:\n", 295 | "The given input tree will be printed in a level order fashion where each level will be printed on a new line. \n", 296 | "Elements on every level will be printed in a linear fashion. A single space will separate them.\n", 297 | "\n", 298 | "Constraints:\n", 299 | "1 <= N <= 10^5\n", 300 | "Where N is the total number of nodes in the binary tree.\n", 301 | "\n", 302 | "Time Limit: 1 sec\n", 303 | "\n", 304 | "Sample Input 1:\n", 305 | "10 20 30 40 50 -1 60 -1 -1 -1 -1 -1 -1 \n", 306 | "Sample Output 1:\n", 307 | "10 \n", 308 | "20 30 \n", 309 | "40 50 60 \n", 310 | "\n", 311 | "Sample Input 2:\n", 312 | "8 3 10 1 6 -1 14 -1 -1 4 7 13 -1 -1 -1 -1 -1 -1 -1\n", 313 | "Sample Output 2:\n", 314 | "8 \n", 315 | "3 10 \n", 316 | "1 6 14 \n", 317 | "4 7 13 \n", 318 | "'''\n", 319 | "\n", 320 | "from sys import stdin, setrecursionlimit\n", 321 | "import queue\n", 322 | "\n", 323 | "setrecursionlimit(10 ** 6)\n", 324 | "\n", 325 | "class BinaryTreeNode:\n", 326 | " def __init__(self, data):\n", 327 | " self.data = data\n", 328 | " self.left = None\n", 329 | " self.right = None\n", 330 | "\n", 331 | " \n", 332 | "def printLevelWise(root):\n", 333 | " if root is None:\n", 334 | " return None\n", 335 | " \n", 336 | " q = queue.Queue()\n", 337 | " q.put(root)\n", 338 | " q.put(None)\n", 339 | " \n", 340 | " while(not q.empty()):\n", 341 | " currentNode = q.get()\n", 342 | " \n", 343 | " if currentNode is None:\n", 344 | " print()\n", 345 | " if(not q.empty()):\n", 346 | " \tq.put(None)\n", 347 | " \n", 348 | " else:\n", 349 | " print(currentNode.data, end=' ')\n", 350 | " \n", 351 | " if currentNode.left!=None:\n", 352 | " q.put(currentNode.left)\n", 353 | " \n", 354 | " if currentNode.right!=None:\n", 355 | " q.put(currentNode.right) \n", 356 | " return\n", 357 | " \n", 358 | "\n", 359 | "#Taking level-order input using fast I/O method\n", 360 | "def takeInput():\n", 361 | " levelOrder = list(map(int, stdin.readline().strip().split(\" \")))\n", 362 | " start = 0\n", 363 | " length = len(levelOrder)\n", 364 | " if length == 1 :\n", 365 | " return None\n", 366 | " root = BinaryTreeNode(levelOrder[start])\n", 367 | " start += 1\n", 368 | " q = queue.Queue()\n", 369 | " q.put(root)\n", 370 | " while not q.empty():\n", 371 | " currentNode = q.get()\n", 372 | " leftChild = levelOrder[start]\n", 373 | " start += 1\n", 374 | " if leftChild != -1:\n", 375 | " leftNode = BinaryTreeNode(leftChild)\n", 376 | " currentNode.left =leftNode\n", 377 | " q.put(leftNode)\n", 378 | " rightChild = levelOrder[start]\n", 379 | " start += 1\n", 380 | " if rightChild != -1:\n", 381 | " rightNode = BinaryTreeNode(rightChild)\n", 382 | " currentNode.right =rightNode\n", 383 | " q.put(rightNode)\n", 384 | " return root\n", 385 | "\n", 386 | "# Main\n", 387 | "root = takeInput()\n", 388 | "printLevelWise(root)" 389 | ], 390 | "metadata": { 391 | "id": "1TcXgZ1eoQ5I" 392 | }, 393 | "execution_count": null, 394 | "outputs": [] 395 | }, 396 | { 397 | "cell_type": "code", 398 | "source": [ 399 | "'''\n", 400 | "Path Sum Root to Leaf\n", 401 | "\n", 402 | "For a given Binary Tree of type integer and a number K, print out all root-to-leaf paths where the sum of all \n", 403 | "the node data along the path is equal to K.\n", 404 | "\n", 405 | "Input Format:\n", 406 | "The first line of input will contain the node data, all separated by a single space. Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data.\n", 407 | "\n", 408 | "The second line of input contains an integer value K.\n", 409 | "\n", 410 | "Output Format:\n", 411 | "Lines equal to the total number of paths will be printed. All the node data in every path will be printed in a linear fashion taken in the order they appear from top to down bottom in the tree. A single space will separate them all.\n", 412 | "\n", 413 | "Constriants:\n", 414 | "1 <= N <= 10^5\n", 415 | "0 <= K <= 10^8\n", 416 | "Where N is the total number of nodes in the binary tree.\n", 417 | "\n", 418 | "Time Limit: 1 second\n", 419 | "\n", 420 | "Sample Input 1:\n", 421 | "2 3 9 4 8 -1 2 4 -1 -1 -1 6 -1 -1 -1 -1 -1\n", 422 | "13\n", 423 | " Sample Output 1:\n", 424 | "2 3 4 4 \n", 425 | "2 3 8\n", 426 | "\n", 427 | "Sample Input 2:\n", 428 | "5 6 7 2 3 -1 1 -1 -1 -1 9 -1 -1 -1 -1\n", 429 | "13\n", 430 | " Sample Output 2:\n", 431 | "5 6 2\n", 432 | "5 7 1\n", 433 | "'''\n", 434 | "\n", 435 | "from sys import stdin, setrecursionlimit\n", 436 | "import queue\n", 437 | "\n", 438 | "setrecursionlimit(10 ** 6)\n", 439 | "\n", 440 | "class BinaryTreeNode:\n", 441 | " def __init__(self, data):\n", 442 | " self.data = data\n", 443 | " self.left = None\n", 444 | " self.right = None\n", 445 | "\n", 446 | "def rootToLeafPathsSumToK(root, k, answerString):\n", 447 | " if root is None:\n", 448 | " return None\n", 449 | " \n", 450 | " subSum = k-root.data\n", 451 | " answerString += str(root.data)+' '\n", 452 | " \n", 453 | " if subSum==0 and root.left is None and root.right is None:\n", 454 | " print(answerString)\n", 455 | " \n", 456 | " rootToLeafPathsSumToK(root.left, subSum, answerString)\n", 457 | " rootToLeafPathsSumToK(root.right, subSum, answerString)\n", 458 | " \n", 459 | " return\n", 460 | "\n", 461 | "\n", 462 | "#Taking level-order input using fast I/O method\n", 463 | "def takeInput():\n", 464 | " levelOrder = list(map(int, stdin.readline().strip().split(\" \")))\n", 465 | " start = 0\n", 466 | " length = len(levelOrder)\n", 467 | " if length == 1 :\n", 468 | " return None\n", 469 | " root = BinaryTreeNode(levelOrder[start])\n", 470 | " start += 1\n", 471 | " q = queue.Queue()\n", 472 | " q.put(root)\n", 473 | " while not q.empty():\n", 474 | " currentNode = q.get()\n", 475 | " leftChild = levelOrder[start]\n", 476 | " start += 1\n", 477 | " if leftChild != -1:\n", 478 | " leftNode = BinaryTreeNode(leftChild)\n", 479 | " currentNode.left =leftNode\n", 480 | " q.put(leftNode)\n", 481 | " rightChild = levelOrder[start]\n", 482 | " start += 1\n", 483 | " if rightChild != -1:\n", 484 | " rightNode = BinaryTreeNode(rightChild)\n", 485 | " currentNode.right =rightNode\n", 486 | " q.put(rightNode)\n", 487 | " return root\n", 488 | " \n", 489 | "def printLevelWise(root):\n", 490 | " if root is None:\n", 491 | " return\n", 492 | " inputQ = queue.Queue()\n", 493 | " outputQ = queue.Queue()\n", 494 | " inputQ.put(root)\n", 495 | " while not inputQ.empty(): \n", 496 | " while not inputQ.empty(): \n", 497 | " curr = inputQ.get()\n", 498 | " print(curr.data, end=' ')\n", 499 | " if curr.left!=None:\n", 500 | " outputQ.put(curr.left)\n", 501 | " if curr.right!=None:\n", 502 | " outputQ.put(curr.right) \n", 503 | " print()\n", 504 | " inputQ, outputQ = outputQ, inputQ\n", 505 | "\n", 506 | "# Main\n", 507 | "root = takeInput()\n", 508 | "k = int(stdin.readline().strip())\n", 509 | "rootToLeafPathsSumToK(root, k, \"\")" 510 | ], 511 | "metadata": { 512 | "id": "MdjaT2Uryaou" 513 | }, 514 | "execution_count": null, 515 | "outputs": [] 516 | }, 517 | { 518 | "cell_type": "code", 519 | "source": [ 520 | "'''\n", 521 | "Print nodes at distance k from node\n", 522 | "\n", 523 | "You are given a Binary Tree of type integer, a target node, and an integer value K.\n", 524 | "Print the data of all nodes that have a distance K from the target node. The order in which they would be printed will not matter.\n", 525 | "\n", 526 | "Input Format:\n", 527 | "The first line of input will contain the node data, all separated by a single space. \n", 528 | "Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data.\n", 529 | "\n", 530 | "The second line of input contains two integers separated by a single space, representing the value of the target node and K, respectively.\n", 531 | "\n", 532 | "Output Format:\n", 533 | "All the node data at distance K from the target node will be printed on a new line.\n", 534 | "\n", 535 | "The order in which the data is printed doesn't matter.\n", 536 | "\n", 537 | "Constraints:\n", 538 | "1 <= N <= 10^5\n", 539 | "Where N is the total number of nodes in the binary tree.\n", 540 | "\n", 541 | "Time Limit: 1 sec\n", 542 | "\n", 543 | "Sample Input 1:\n", 544 | "5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1\n", 545 | "3 1\n", 546 | "Sample Output 1:\n", 547 | "9\n", 548 | "6\n", 549 | "\n", 550 | "Sample Input 2:\n", 551 | "1 2 3 4 5 6 7 -1 -1 -1 -1 -1 -1 -1 -1\n", 552 | "3 3\n", 553 | "Sample Output 2:\n", 554 | "4\n", 555 | "5\n", 556 | "'''\n", 557 | "\n", 558 | "from sys import stdin, setrecursionlimit\n", 559 | "import queue\n", 560 | "\n", 561 | "setrecursionlimit(10 ** 6)\n", 562 | "\n", 563 | "class BinaryTreeNode:\n", 564 | " def __init__(self, data):\n", 565 | " self.data = data\n", 566 | " self.left = None\n", 567 | " self.right = None\n", 568 | "\n", 569 | "def nodesAtDistanceK(root, node, k) :\n", 570 | " if root is None:\n", 571 | " return -1\n", 572 | " \n", 573 | " if root.data==node:\n", 574 | " printNodesAtDistanceK(root,k)\n", 575 | " return 0\n", 576 | " \n", 577 | " leftDistanceFromRoot = nodesAtDistanceK(root.left, node, k)\n", 578 | " if leftDistanceFromRoot != -1 :\n", 579 | " if leftDistanceFromRoot+1 == k:\n", 580 | " print(root.data)\n", 581 | " else:\n", 582 | " printNodesAtDistanceK(root.right, k-leftDistanceFromRoot-2)\n", 583 | " return leftDistanceFromRoot+1\n", 584 | " \n", 585 | " rightDistanceFromRoot = nodesAtDistanceK(root.right, node, k)\n", 586 | " if rightDistanceFromRoot != -1 :\n", 587 | " if rightDistanceFromRoot+1 == k:\n", 588 | " print(root.data)\n", 589 | " else:\n", 590 | " printNodesAtDistanceK(root.left, k-rightDistanceFromRoot-2)\n", 591 | " return rightDistanceFromRoot+1\n", 592 | " \n", 593 | " return -1\n", 594 | "\n", 595 | "\n", 596 | "def printNodesAtDistanceK(root, k):\n", 597 | " if root is None:\n", 598 | " return None\n", 599 | " \n", 600 | " if k==0 :\n", 601 | " print(root.data)\n", 602 | " return\n", 603 | " \n", 604 | " printNodesAtDistanceK(root.left,k-1)\n", 605 | " printNodesAtDistanceK(root.right,k-1)\n", 606 | "\n", 607 | " \n", 608 | "#Taking level-order input using fast I/O method\n", 609 | "def takeInput():\n", 610 | " levelOrder = list(map(int, stdin.readline().strip().split(\" \")))\n", 611 | " start = 0\n", 612 | " length = len(levelOrder)\n", 613 | " if length == 1 :\n", 614 | " return None\n", 615 | " root = BinaryTreeNode(levelOrder[start])\n", 616 | " start += 1\n", 617 | " q = queue.Queue()\n", 618 | " q.put(root)\n", 619 | " while not q.empty():\n", 620 | " currentNode = q.get()\n", 621 | " leftChild = levelOrder[start]\n", 622 | " start += 1\n", 623 | " if leftChild != -1:\n", 624 | " leftNode = BinaryTreeNode(leftChild)\n", 625 | " currentNode.left =leftNode\n", 626 | " q.put(leftNode)\n", 627 | " rightChild = levelOrder[start]\n", 628 | " start += 1\n", 629 | " if rightChild != -1:\n", 630 | " rightNode = BinaryTreeNode(rightChild)\n", 631 | " currentNode.right =rightNode\n", 632 | " q.put(rightNode)\n", 633 | " return root\n", 634 | "\n", 635 | "def printLevelWise(root):\n", 636 | " if root is None:\n", 637 | " return\n", 638 | " inputQ = queue.Queue()\n", 639 | " outputQ = queue.Queue()\n", 640 | " inputQ.put(root)\n", 641 | " while not inputQ.empty():\n", 642 | " while not inputQ.empty():\n", 643 | " curr = inputQ.get()\n", 644 | " print(curr.data, end=' ')\n", 645 | " if curr.left!=None:\n", 646 | " outputQ.put(curr.left)\n", 647 | " if curr.right!=None:\n", 648 | " outputQ.put(curr.right)\n", 649 | " print()\n", 650 | " inputQ, outputQ = outputQ, inputQ\n", 651 | "\n", 652 | "# Main\n", 653 | "root = takeInput()\n", 654 | "target_k = stdin.readline().strip().split(\" \")\n", 655 | "target = int(target_k[0])\n", 656 | "k = int(target_k[1])\n", 657 | "nodesAtDistanceK(root, target, k)" 658 | ], 659 | "metadata": { 660 | "id": "MORGqQ7XyqYL" 661 | }, 662 | "execution_count": null, 663 | "outputs": [] 664 | } 665 | ] 666 | } -------------------------------------------------------------------------------- /06_Binary-Trees/Binary-Trees-2/Quiz_Binary-Trees-2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddhapuraharsh/Data-Structures_Algorithms_Coding-Ninjas_Full-Course/149411eb7d59abd80d2a65f0ff1039b62558bb1b/06_Binary-Trees/Binary-Trees-2/Quiz_Binary-Trees-2.pdf -------------------------------------------------------------------------------- /07_Binary-Search-Tree/Binary-Search-Trees-1/Problems_Binary_Search_Tree_1.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "Problems_Binary-Search-Tree-1", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "source": [ 22 | "**CONTENT**" 23 | ], 24 | "metadata": { 25 | "id": "KA8ZG3TuNedU" 26 | } 27 | }, 28 | { 29 | "cell_type": "code", 30 | "source": [ 31 | "# Check if the given tree is Binary Search Tree\n", 32 | "\n", 33 | "# Solution-1\n", 34 | "class BinaryTreeNode:\n", 35 | " def __init__(self,data):\n", 36 | " self.data=data;\n", 37 | " self.left=None\n", 38 | " self.right=None\n", 39 | "\n", 40 | "def printTreeDetailed(root):\n", 41 | " if root==None:\n", 42 | " return\n", 43 | " print(root.data,end=\":\")\n", 44 | " if root.left!=None:\n", 45 | " print(\"L\",root.left.data,end=\",\")\n", 46 | " if root.right!=None:\n", 47 | " print(\"R\",root.right.data,end=\"\")\n", 48 | " print()\n", 49 | " printTreeDetailed(root.left)\n", 50 | " printTreeDetailed(root.right)\n", 51 | "\n", 52 | "import queue\n", 53 | "def takeTreeInputLevelWise():\n", 54 | " q=queue.Queue()\n", 55 | " print(\"Enter root\")\n", 56 | " rootData=int(input())\n", 57 | " if rootData==-1:\n", 58 | " return None\n", 59 | " root=BinaryTreeNode(rootData)\n", 60 | " q.put(root)\n", 61 | " while(not(q.empty())):\n", 62 | " current_node=q.get()\n", 63 | " print(\"Enter left child of\",current_node.data)\n", 64 | " leftChildData=int(input())\n", 65 | " if leftChildData!=-1:\n", 66 | " leftChild=BinaryTreeNode(leftChildData)\n", 67 | " current_node.left=leftChild\n", 68 | " q.put(leftChild)\n", 69 | " print(\"Enter right child of\",current_node.data)\n", 70 | " rightChildData=int(input())\n", 71 | " if rightChildData!=-1:\n", 72 | " rightChild=BinaryTreeNode(rightChildData)\n", 73 | " current_node.right=rightChild\n", 74 | " q.put(rightChild)\n", 75 | " return root\n", 76 | "\n", 77 | "def minTree(root):\n", 78 | " if root==None:\n", 79 | " return 100000\n", 80 | " leftMin=minTree(root.left)\n", 81 | " rightMin=minTree(root.right)\n", 82 | " return min(leftMin,rightMin,root.data)\n", 83 | "\n", 84 | "def maxTree(root):\n", 85 | " if root==None:\n", 86 | " return -100000\n", 87 | " leftMax=maxTree(root.left)\n", 88 | " rightMax=maxTree(root.right)\n", 89 | " return max(leftMax,rightMax,root.data)\n", 90 | "\n", 91 | "def isBST(root):\n", 92 | " if root==None:\n", 93 | " return True\n", 94 | " leftMax=maxTree(root.left)\n", 95 | " rightMin=minTree(root.right)\n", 96 | " if root.data>rightMin or root.data<=leftMax:\n", 97 | " return False\n", 98 | " isLeftBST=isBST(root.left)\n", 99 | " isRightBST=isBST(root.right)\n", 100 | " return isLeftBST and isRightBST\n", 101 | "\n", 102 | "def isBST2(root):\n", 103 | " if root==None:\n", 104 | " return 100000,-100000,True\n", 105 | " leftMin,leftMax,isLeftBST=isBST2(root.left)\n", 106 | " rightMin,rightMax,isRightBST=isBST2(root.right)\n", 107 | " \n", 108 | " minimum=min(leftMin,rightMin,root.data)\n", 109 | " maximum=max(leftMax,rightMax,root.data)\n", 110 | " isTreeBST=True\n", 111 | " if root.data<=leftMax or root.data>rightMin:\n", 112 | " isTreeBST=False\n", 113 | " if not(isLeftBST) or not(isRightBST):\n", 114 | " isTreeBST=False\n", 115 | " \n", 116 | " return minimum,maximum,isTreeBST\n", 117 | "\n", 118 | "\n", 119 | "def isBST3(root,min_range,max_range):\n", 120 | " if root==None:\n", 121 | " return True\n", 122 | " if root.datamax_range:\n", 123 | " return False\n", 124 | " \n", 125 | " isLeftWithinConstraints=isBST3(root.left,min_range,root.data-1)\n", 126 | " isRightWithinConstraints=isBST3(root.right,root.data,max_range)\n", 127 | " \n", 128 | " return isLeftWithinConstraints and isRightWithinConstraints\n", 129 | "\n", 130 | "root=takeTreeInputLevelWise()\n", 131 | "printTreeDetailed(root)\n", 132 | "isBST(root)\n", 133 | "isBST2(root)\n", 134 | "isBST3(root,-100000, 100000)" 135 | ], 136 | "metadata": { 137 | "id": "vjSCPJrSNpph" 138 | }, 139 | "execution_count": null, 140 | "outputs": [] 141 | }, 142 | { 143 | "cell_type": "markdown", 144 | "source": [ 145 | "**CONTENT PROBLEMS**" 146 | ], 147 | "metadata": { 148 | "id": "ABTX3M5CWg1F" 149 | } 150 | }, 151 | { 152 | "cell_type": "code", 153 | "execution_count": null, 154 | "metadata": { 155 | "id": "ocJZ3BNbWU8o" 156 | }, 157 | "outputs": [], 158 | "source": [ 159 | "'''\n", 160 | "Search In BST\n", 161 | "\n", 162 | "Given a BST and an integer k. Find if the integer k is present in given BST or not. \n", 163 | "You have to return true, if node with data k is present, return false otherwise.\n", 164 | "\n", 165 | "Note: Assume that BST contains all unique elements.\n", 166 | "\n", 167 | "Input Format:\n", 168 | "The first line of input contains data of the nodes of the tree in level order form. \n", 169 | "The data of the nodes of the tree is separated by space. If any node does not have left or right child, \n", 170 | "take -1 in its place. Since -1 is used as an indication whether the left or right nodes exist, therefore, \n", 171 | "it will not be a part of the data of any node. \n", 172 | "\n", 173 | "The following line of input contains an integer, that denotes the value of k.\n", 174 | "\n", 175 | "Output Format:\n", 176 | "The first and only line of output contains a boolean value. Print true, if node with data k is present, print false otherwise. \n", 177 | "\n", 178 | "Constraints:\n", 179 | "Time Limit: 1 second\n", 180 | "\n", 181 | "Sample Input 1 :\n", 182 | "8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1\n", 183 | "2\n", 184 | "Sample Output 1 :\n", 185 | "true\n", 186 | "\n", 187 | "Sample Input 2 :\n", 188 | "8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1\n", 189 | "12\n", 190 | "Sample Output 2 :\n", 191 | "false\n", 192 | "'''\n", 193 | "\n", 194 | "import queue\n", 195 | "class BinaryTreeNode:\n", 196 | " def __init__(self, data):\n", 197 | " self.data = data\n", 198 | " self.left = None\n", 199 | " self.right = None\n", 200 | "\n", 201 | "def searchInBST(root, k):\n", 202 | " if root is None:\n", 203 | " return None\n", 204 | " if root.data==k:\n", 205 | " return True\n", 206 | " if root.data>k:\n", 207 | " \treturn searchInBST(root.left, k)\n", 208 | " else:\n", 209 | " \treturn searchInBST(root.right, k)\n", 210 | " \n", 211 | "def buildLevelTree(levelorder):\n", 212 | " index = 0\n", 213 | " length = len(levelorder)\n", 214 | " if length<=0 or levelorder[0]==-1:\n", 215 | " return None\n", 216 | " root = BinaryTreeNode(levelorder[index])\n", 217 | " index += 1\n", 218 | " q = queue.Queue()\n", 219 | " q.put(root)\n", 220 | " while not q.empty():\n", 221 | " currentNode = q.get()\n", 222 | " leftChild = levelorder[index]\n", 223 | " index += 1\n", 224 | " if leftChild != -1:\n", 225 | " leftNode = BinaryTreeNode(leftChild)\n", 226 | " currentNode.left =leftNode\n", 227 | " q.put(leftNode)\n", 228 | " rightChild = levelorder[index]\n", 229 | " index += 1\n", 230 | " if rightChild != -1:\n", 231 | " rightNode = BinaryTreeNode(rightChild)\n", 232 | " currentNode.right =rightNode\n", 233 | " q.put(rightNode)\n", 234 | " return root\n", 235 | "\n", 236 | "# Main\n", 237 | "levelOrder = [int(i) for i in input().strip().split()]\n", 238 | "root = buildLevelTree(levelOrder)\n", 239 | "k=int(input())\n", 240 | "ans = searchInBST(root, k)\n", 241 | "if ans:\n", 242 | " print(\"true\")\n", 243 | "else:\n", 244 | " print(\"false\")" 245 | ] 246 | }, 247 | { 248 | "cell_type": "code", 249 | "source": [ 250 | "'''\n", 251 | "Elements Between K1 and K2\n", 252 | "\n", 253 | "Given a Binary Search Tree and two integers k1 and k2, find and print the elements which are in range k1 and k2 (both inclusive).\n", 254 | "Print the elements in increasing order.\n", 255 | "\n", 256 | "Input format:\n", 257 | "The first line of input contains data of the nodes of the tree in level order form. \n", 258 | "The data of the nodes of the tree is separated by space. If any node does not have left or right child, \n", 259 | "take -1 in its place. Since -1 is used as an indication whether the left or right nodes exist, therefore, \n", 260 | "it will not be a part of the data of any node.\n", 261 | "\n", 262 | "The following line contains two integers, that denote the value of k1 and k2.\n", 263 | "\n", 264 | "Output Format:\n", 265 | " The first and only line of output prints the elements which are in range k1 and k2 (both inclusive). \n", 266 | " Print the elements in increasing order.\n", 267 | "\n", 268 | "Constraints:\n", 269 | "Time Limit: 1 second\n", 270 | "\n", 271 | "Sample Input 1:\n", 272 | "8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1\n", 273 | "6 10\n", 274 | "Sample Output 1:\n", 275 | "6 7 8 10\n", 276 | "'''\n", 277 | "\n", 278 | "import queue\n", 279 | "class BinaryTreeNode:\n", 280 | " def __init__(self, data):\n", 281 | " self.data = data\n", 282 | " self.left = None\n", 283 | " self.right = None\n", 284 | "\n", 285 | "def elementsInRangeK1K2(root, k1, k2):\n", 286 | " if root is None:\n", 287 | " return\n", 288 | " elif root.datak2:\n", 291 | " elementsInRangeK1K2(root.left, k1, k2)\n", 292 | " else:\n", 293 | " elementsInRangeK1K2(root.left, k1, k2)\n", 294 | " print(root.data, end=' ')\n", 295 | " elementsInRangeK1K2(root.right, k1, k2)\n", 296 | " \n", 297 | "def buildLevelTree(levelorder):\n", 298 | " index = 0\n", 299 | " length = len(levelorder)\n", 300 | " if length<=0 or levelorder[0]==-1:\n", 301 | " return None\n", 302 | " root = BinaryTreeNode(levelorder[index])\n", 303 | " index += 1\n", 304 | " q = queue.Queue()\n", 305 | " q.put(root)\n", 306 | " while not q.empty():\n", 307 | " currentNode = q.get()\n", 308 | " leftChild = levelorder[index]\n", 309 | " index += 1\n", 310 | " if leftChild != -1:\n", 311 | " leftNode = BinaryTreeNode(leftChild)\n", 312 | " currentNode.left =leftNode\n", 313 | " q.put(leftNode)\n", 314 | " rightChild = levelorder[index]\n", 315 | " index += 1\n", 316 | " if rightChild != -1:\n", 317 | " rightNode = BinaryTreeNode(rightChild)\n", 318 | " currentNode.right =rightNode\n", 319 | " q.put(rightNode)\n", 320 | " return root\n", 321 | "\n", 322 | "# Main\n", 323 | "levelOrder = [int(i) for i in input().strip().split()]\n", 324 | "root = buildLevelTree(levelOrder)\n", 325 | "k1, k2 = (int(i) for i in input().strip().split())\n", 326 | "elementsInRangeK1K2(root, k1, k2)" 327 | ], 328 | "metadata": { 329 | "id": "rcXtjHaGDfFb" 330 | }, 331 | "execution_count": null, 332 | "outputs": [] 333 | }, 334 | { 335 | "cell_type": "code", 336 | "source": [ 337 | "'''\n", 338 | "Construct BST\n", 339 | "\n", 340 | "Given a sorted integer array A of size n, which contains all unique elements. \n", 341 | "You need to construct a balanced BST from this input array. Return the root of constructed BST.\n", 342 | "\n", 343 | "Note: If array size is even, take first mid as root.\n", 344 | "\n", 345 | "Input format:\n", 346 | "The first line of input contains an integer, which denotes the value of n. \n", 347 | "The following line contains n space separated integers, that denote the values of array.\n", 348 | "\n", 349 | "Output Format:\n", 350 | "The first and only line of output contains values of BST nodes, printed in pre order traversal.\n", 351 | "\n", 352 | "Constraints:\n", 353 | "Time Limit: 1 second\n", 354 | "\n", 355 | "Sample Input 1:\n", 356 | "7\n", 357 | "1 2 3 4 5 6 7\n", 358 | "Sample Output 1:\n", 359 | "4 2 1 3 6 5 7 \n", 360 | "'''\n", 361 | "\n", 362 | "import queue\n", 363 | "class BinaryTreeNode:\n", 364 | " def __init__(self, data):\n", 365 | " self.data = data\n", 366 | " self.left = None\n", 367 | " self.right = None\n", 368 | "\n", 369 | "def constructBST(lst, startIndex, endIndex):\n", 370 | " if startIndex>endIndex:\n", 371 | " return \n", 372 | " \n", 373 | " mid = (startIndex+endIndex)//2\n", 374 | "\n", 375 | " root = BinaryTreeNode(lst[mid])\n", 376 | " root.left = constructBST(lst, startIndex, mid-1)\n", 377 | " root.right = constructBST(lst, mid+1, endIndex)\n", 378 | " \n", 379 | " return root\n", 380 | "\n", 381 | "def preOrder(root):\n", 382 | " # Given a binary tree, print the preorder traversal of given tree. Pre-order\n", 383 | " # traversal is: Root LeftChild RightChild\n", 384 | " if root==None:\n", 385 | " return\n", 386 | " print(root.data, end=' ')\n", 387 | " preOrder(root.left)\n", 388 | " preOrder(root.right)\n", 389 | "\n", 390 | "# Main\n", 391 | "n=int(input())\n", 392 | "if(n>0):\n", 393 | " lst=[int(i) for i in input().strip().split()]\n", 394 | "else:\n", 395 | " lst=[]\n", 396 | "root=constructBST(lst, 0, len(lst)-1)\n", 397 | "preOrder(root)" 398 | ], 399 | "metadata": { 400 | "id": "i9X_5GReKgZn" 401 | }, 402 | "execution_count": null, 403 | "outputs": [] 404 | } 405 | ] 406 | } -------------------------------------------------------------------------------- /07_Binary-Search-Tree/Binary-Search-Trees-1/Quiz_Binary-Search-Tree-1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddhapuraharsh/Data-Structures_Algorithms_Coding-Ninjas_Full-Course/149411eb7d59abd80d2a65f0ff1039b62558bb1b/07_Binary-Search-Tree/Binary-Search-Trees-1/Quiz_Binary-Search-Tree-1.pdf -------------------------------------------------------------------------------- /07_Binary-Search-Tree/Binary-Search-Trees-2/Problems_Binary_Search_Tree_2.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "Problems_Binary-Search-Tree-2", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "source": [ 22 | "**CONTENT**" 23 | ], 24 | "metadata": { 25 | "id": "o7_kl1tdQBpY" 26 | } 27 | }, 28 | { 29 | "cell_type": "code", 30 | "source": [ 31 | "class BinaryTreeNode:\n", 32 | "\n", 33 | " def __init__(self,data):\n", 34 | " self.data=data;\n", 35 | " self.left=None\n", 36 | " self.right=None\n", 37 | " \n", 38 | "def search(root,x):\n", 39 | " if root==None:\n", 40 | " return False\n", 41 | " if root.data==x:\n", 42 | " return True\n", 43 | " elif root.data>x:\n", 44 | " return search(root.left,x)\n", 45 | " else:\n", 46 | " return search(root.left,x)\n", 47 | "\n", 48 | "def printTreeDetailed(root):\n", 49 | " if root==None:\n", 50 | " return\n", 51 | " print(root.data,end=\":\")\n", 52 | " if root.left!=None:\n", 53 | " print(\"L\",root.left.data,end=\",\")\n", 54 | " if root.right!=None:\n", 55 | " print(\"R\",root.right.data,end=\"\")\n", 56 | " print()\n", 57 | " printTreeDetailed(root.left)\n", 58 | " printTreeDetailed(root.right)\n", 59 | "\n", 60 | "import queue\n", 61 | "def takeTreeInputLevelWise():\n", 62 | " q=queue.Queue()\n", 63 | " print(\"Enter root\")\n", 64 | " rootData=int(input())\n", 65 | " if rootData==-1:\n", 66 | " return None\n", 67 | " root=BinaryTreeNode(rootData)\n", 68 | " q.put(root)\n", 69 | " while(not(q.empty())):\n", 70 | " current_node=q.get()\n", 71 | " print(\"Enter left child of\",current_node.data)\n", 72 | " leftChildData=int(input())\n", 73 | " if leftChildData!=-1:\n", 74 | " leftChild=BinaryTreeNode(leftChildData)\n", 75 | " current_node.left=leftChild\n", 76 | " q.put(leftChild)\n", 77 | " print(\"Enter right child of\",current_node.data)\n", 78 | " rightChildData=int(input())\n", 79 | " if rightChildData!=-1:\n", 80 | " rightChild=BinaryTreeNode(rightChildData)\n", 81 | " current_node.right=rightChild\n", 82 | " q.put(rightChild)\n", 83 | " return root\n", 84 | "\n", 85 | "def nodeToRootPath(root,s):\n", 86 | " if root==None:\n", 87 | " return None\n", 88 | " if root.data==s:\n", 89 | " l=list()\n", 90 | " l.append(root.data)\n", 91 | " return l\n", 92 | " leftOutput=nodeToRootPath(root.left,s)\n", 93 | " if leftOutput!=None:\n", 94 | " leftOutput.append(root.data)\n", 95 | " return leftOutput\n", 96 | " rightOutput=nodeToRootPath(root.right,s)\n", 97 | " if rightOutput!=None:\n", 98 | " rightOutput.append(root.data)\n", 99 | " return rightOutput\n", 100 | " else:\n", 101 | " return None\n", 102 | "\n", 103 | "root=takeTreeInputLevelWise()\n", 104 | "printTreeDetailed(root)\n", 105 | "nodeToRootPath(root,5)" 106 | ], 107 | "metadata": { 108 | "id": "ne3Yz9XAQECO" 109 | }, 110 | "execution_count": null, 111 | "outputs": [] 112 | }, 113 | { 114 | "cell_type": "markdown", 115 | "source": [ 116 | "**CONTENT PROBLEMS**" 117 | ], 118 | "metadata": { 119 | "id": "LAMbOztNJgpj" 120 | } 121 | }, 122 | { 123 | "cell_type": "code", 124 | "execution_count": null, 125 | "metadata": { 126 | "id": "7hl6_i-8JW-_" 127 | }, 128 | "outputs": [], 129 | "source": [ 130 | "'''\n", 131 | "Find path in BST\n", 132 | "\n", 133 | "Given a BST and an integer k. Find and return the path from the node with data k and root \n", 134 | "(if a node with data k is present in given BST) in a list. Return empty list otherwise.\n", 135 | "\n", 136 | "Note: Assume that BST contains all unique elements.\n", 137 | "\n", 138 | "Input Format :\n", 139 | "The first line of input contains data of the nodes of the tree in level order form. \n", 140 | "The data of the nodes of the tree is separated by space. If any node does not have left or right child, \n", 141 | "take -1 in its place. Since -1 is used as an indication whether the left or right nodes exist, therefore, \n", 142 | "it will not be a part of the data of any node. \n", 143 | "\n", 144 | "The following line of input contains an integer, that denotes the value of k.\n", 145 | "\n", 146 | "Output Format :\n", 147 | "The first line and only line of output prints the data of the nodes in the path from node k to root. \n", 148 | "The data of the nodes is separated by single space.\n", 149 | "\n", 150 | "Constraints:\n", 151 | "Time Limit: 1 second \n", 152 | "\n", 153 | "Sample Input 1:\n", 154 | "8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1\n", 155 | "2\n", 156 | "Sample Output 1:\n", 157 | "2 5 8\n", 158 | "'''\n", 159 | "\n", 160 | "import queue\n", 161 | "class BinaryTreeNode:\n", 162 | " def __init__(self, data):\n", 163 | " self.data = data\n", 164 | " self.left = None\n", 165 | " self.right = None\n", 166 | "\n", 167 | "def findPathBST(root,data):\n", 168 | " if root is None:\n", 169 | " return None\n", 170 | " if root.data == data:\n", 171 | " lst = list()\n", 172 | " lst.append(root.data)\n", 173 | " return lst\n", 174 | " leftOutput = findPathBST(root.left,data)\n", 175 | " if leftOutput != None:\n", 176 | " leftOutput.append(root.data)\n", 177 | " return leftOutput\n", 178 | " rightOutput = findPathBST(root.right,data)\n", 179 | " if rightOutput != None:\n", 180 | " rightOutput.append(root.data)\n", 181 | " return rightOutput\n", 182 | " \n", 183 | "def buildLevelTree(levelorder):\n", 184 | " index = 0\n", 185 | " length = len(levelorder)\n", 186 | " if length<=0 or levelorder[0]==-1:\n", 187 | " return None\n", 188 | " root = BinaryTreeNode(levelorder[index])\n", 189 | " index += 1\n", 190 | " q = queue.Queue()\n", 191 | " q.put(root)\n", 192 | " while not q.empty():\n", 193 | " currentNode = q.get()\n", 194 | " leftChild = levelorder[index]\n", 195 | " index += 1\n", 196 | " if leftChild != -1:\n", 197 | " leftNode = BinaryTreeNode(leftChild)\n", 198 | " currentNode.left =leftNode\n", 199 | " q.put(leftNode)\n", 200 | " rightChild = levelorder[index]\n", 201 | " index += 1\n", 202 | " if rightChild != -1:\n", 203 | " rightNode = BinaryTreeNode(rightChild)\n", 204 | " currentNode.right =rightNode\n", 205 | " q.put(rightNode)\n", 206 | " return root\n", 207 | "\n", 208 | "# Main\n", 209 | "levelOrder = [int(i) for i in input().strip().split()]\n", 210 | "root = buildLevelTree(levelOrder)\n", 211 | "data = int(input())\n", 212 | "path = findPathBST(root,data)\n", 213 | "if path is not None:\n", 214 | " for ele in path:\n", 215 | " print(ele,end=' ')" 216 | ] 217 | }, 218 | { 219 | "cell_type": "code", 220 | "source": [ 221 | "'''\n", 222 | "BST Class\n", 223 | "\n", 224 | "Implement the BST class which includes following functions -\n", 225 | "\n", 226 | "1. search\n", 227 | "Given an element, find if that is present in BST or not. Return true or false.\n", 228 | "\n", 229 | "2. insert -\n", 230 | "Given an element, insert that element in the BST at the correct position. \n", 231 | "If element is equal to the data of the node, insert it in the left subtree.\n", 232 | "\n", 233 | "3. delete -\n", 234 | "Given an element, remove that element from the BST. \n", 235 | "If the element which is to be deleted has both children, \n", 236 | "replace that with the minimum element from right sub-tree.\n", 237 | "\n", 238 | "4. printTree (recursive) -\n", 239 | "Print the BST in ithe following format -\n", 240 | "\n", 241 | "For printing a node with data N, you need to follow the exact format -\n", 242 | "N:L:x,R:y\n", 243 | "\n", 244 | "where, N is data of any node present in the binary tree. \n", 245 | "x and y are the values of left and right child of node N. Print the children only if it is not null.\n", 246 | "\n", 247 | "There is no space in between.\n", 248 | "You need to print all nodes in the recursive format in different lines.\n", 249 | "\n", 250 | "'''\n", 251 | "\n", 252 | "\n", 253 | "\n", 254 | "class BinaryTreeNode:\n", 255 | " def __init__(self, data):\n", 256 | " self.data = data\n", 257 | " self.left = None\n", 258 | " self.right = None\n", 259 | " \n", 260 | "class BST:\n", 261 | " \n", 262 | " def __init__(self):\n", 263 | " self.root = None\n", 264 | " self.numNodes = 0\n", 265 | " \n", 266 | " \n", 267 | " def printTreeHelper(self,root):\n", 268 | " if root==None:\n", 269 | " return\n", 270 | " print(root.data,end=\":\")\n", 271 | " if root.left!=None:\n", 272 | " print(\"L:\" + str(root.left.data),end=\",\")\n", 273 | " if root.right!=None:\n", 274 | " print(\"R:\" + str(root.right.data),end=\"\")\n", 275 | " print()\n", 276 | " self.printTreeHelper(root.left)\n", 277 | " self.printTreeHelper(root.right)\n", 278 | " \n", 279 | " def printTree(self):\n", 280 | " self.printTreeHelper(self.root)\n", 281 | " \n", 282 | " \n", 283 | " def isPresentHelper(self,root,data):\n", 284 | " if root==None:\n", 285 | " return False\n", 286 | " if root.data==data:\n", 287 | " return True\n", 288 | " if root.data>data:\n", 289 | " #call on left\n", 290 | " return self.isPresentHelper(root.left,data)\n", 291 | " else:\n", 292 | " #Call on right\n", 293 | " return self.isPresentHelper(root.right,data)\n", 294 | " \n", 295 | " def search(self, data):\n", 296 | " return self.isPresentHelper(self.root,data)\n", 297 | " \n", 298 | " \n", 299 | " def insertHelper(self,root,data):\n", 300 | " if root==None:\n", 301 | " node=BinaryTreeNode(data)\n", 302 | " return node\n", 303 | " if root.data>=data:\n", 304 | " root.left=self.insertHelper(root.left,data)\n", 305 | " return root\n", 306 | " else:\n", 307 | " root.right=self.insertHelper(root.right,data)\n", 308 | " return root\n", 309 | " \n", 310 | " def insert(self, data):\n", 311 | " self.numNodes += 1\n", 312 | " self.root=self.insertHelper(self.root,data)\n", 313 | " \n", 314 | " \n", 315 | " def min(self,root):\n", 316 | " if root==None:\n", 317 | " return 10000\n", 318 | " if root.left==None:\n", 319 | " return root.data\n", 320 | " \n", 321 | " def deleteDataHelper(self,root,data):\n", 322 | " if root==None:\n", 323 | " return False, None\n", 324 | " if root.datadata:\n", 329 | " deleted,newLeftNode=self.deleteDataHelper(root.left,data)\n", 330 | " root.left=newLeftNode\n", 331 | " return deleted,root\n", 332 | " #root is leaf\n", 333 | " if root.left==None and root.right==None:\n", 334 | " return True, None\n", 335 | " # root has one child\n", 336 | " if root.left==None:\n", 337 | " return True,root.right\n", 338 | " if root.right==None:\n", 339 | " return True,root.left\n", 340 | " #root has 2 children\n", 341 | " replacement=self.min(root.right)\n", 342 | " root.data=replacement\n", 343 | " deleted,newRightNode=self.deleteDataHelper(root.right,replacement)\n", 344 | " root.right=newRightNode\n", 345 | " return True,root\n", 346 | " \n", 347 | " def delete(self, data):\n", 348 | " deleted,newRoot=self.deleteDataHelper(self.root,data)\n", 349 | " if deleted:\n", 350 | " self.numNodes-=1\n", 351 | " self.root=newRoot\n", 352 | " return deleted\n", 353 | " \n", 354 | " def count(self):\n", 355 | " return self.numNodes\n", 356 | "\n", 357 | " \n", 358 | "b = BST()\n", 359 | "q = int(input())\n", 360 | "while (q > 0) :\n", 361 | " li = [int(ele) for ele in input().strip().split()]\n", 362 | " choice = li[0]\n", 363 | " q-=1\n", 364 | " if choice == 1:\n", 365 | " data = li[1]\n", 366 | " b.insert(data)\n", 367 | " elif choice == 2:\n", 368 | " data = li[1]\n", 369 | " b.delete(data)\n", 370 | " elif choice == 3:\n", 371 | " data = li[1]\n", 372 | " ans = b.search(data)\n", 373 | " if ans is True:\n", 374 | " print('true')\n", 375 | " else:\n", 376 | " print('false')\n", 377 | " else:\n", 378 | " b.printTree()" 379 | ], 380 | "metadata": { 381 | "id": "uoTa5z4DzIJC" 382 | }, 383 | "execution_count": null, 384 | "outputs": [] 385 | } 386 | ] 387 | } -------------------------------------------------------------------------------- /07_Binary-Search-Tree/Binary-Search-Trees-2/Quiz_Binary-Search-Tree-2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddhapuraharsh/Data-Structures_Algorithms_Coding-Ninjas_Full-Course/149411eb7d59abd80d2a65f0ff1039b62558bb1b/07_Binary-Search-Tree/Binary-Search-Trees-2/Quiz_Binary-Search-Tree-2.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![SUPPORT](https://user-images.githubusercontent.com/82281356/150489925-f6a199b8-09aa-4ab0-8814-c13afbe874b3.jpg)](https://ko-fi.com/harshsiddhapura) 2 | 3 | 4 | # Data Structures & Algorithms Coding Ninjas Full Course 5 | All the quizzes, content and coding assignment solutions of Data Structures and Algorithms course of Coding Ninjas. 6 | -------------------------------------------------------------------------------- /Test-1/Test_1.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "Test-1", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "markdown", 21 | "source": [ 22 | "1.Recurrence Relation for Tower of Hanoi Problem\n", 23 | "\n", 24 | "The recurrence relation capturing the optimal execution time of the Towers of Hanoi problem with n discs is :\n", 25 | "\n", 26 | "T(n) = 2T(n − 2) + 2\n", 27 | "\n", 28 | "T(n) = 2T(n − 1) + n\n", 29 | "\n", 30 | "T(n) = 2T(n/2) + 1\n", 31 | "\n", 32 | "**T(n) = 2T(n − 1) + 1** -> Correct Answer\n", 33 | "\n", 34 | "--------------------------------------------------------------------\n", 35 | "\n", 36 | "\n", 37 | "2.Complexity of different operations in a sorted array.\n", 38 | "\n", 39 | "Which of the following operations is not O(1) for an array of sorted data. You may assume that array elements are distinct.\n", 40 | "\n", 41 | "Find the ith largest element\n", 42 | "\n", 43 | "**Delete an element** -> Correct Answer\n", 44 | "\n", 45 | "Find the ith smallest element\n", 46 | "\n", 47 | "All of the above\n", 48 | "\n", 49 | "--------------------------------------------------------------------\n", 50 | "\n", 51 | "3.Complexity of a Recurrence Relation\n", 52 | "\n", 53 | "Which one of the following correctly determines the solution of the recurrence relation with T(1) = 1?\n", 54 | "T(n) = 2T(n/2) + Logn\n", 55 | "\n", 56 | "**O(N)** -> Correct Answer\n", 57 | "\n", 58 | "O(NlogN)\n", 59 | "\n", 60 | "O(N^2)\n", 61 | "\n", 62 | "O(log N)\n", 63 | "\n", 64 | "--------------------------------------------------------------------" 65 | ], 66 | "metadata": { 67 | "id": "sDezOpcMYXWp" 68 | } 69 | }, 70 | { 71 | "cell_type": "code", 72 | "execution_count": null, 73 | "metadata": { 74 | "colab": { 75 | "base_uri": "https://localhost:8080/" 76 | }, 77 | "id": "PSvt-TwBbWBi", 78 | "outputId": "7a183516-5f9f-40bc-8223-445711caaebc" 79 | }, 80 | "outputs": [ 81 | { 82 | "output_type": "stream", 83 | "name": "stdout", 84 | "text": [ 85 | "True\n" 86 | ] 87 | } 88 | ], 89 | "source": [ 90 | "'''\n", 91 | "Does s contain t ?\n", 92 | "\n", 93 | "Given two string s and t, write a function to check if s contains all characters of t (in the same order as they are in string t).\n", 94 | "Return true or false.\n", 95 | "\n", 96 | "Do it recursively.\n", 97 | "E.g. : s = “abchjsgsuohhdhyrikkknddg” contains all characters of t=”coding” in the same order. So function will return true.\n", 98 | "\n", 99 | "Input Format :\n", 100 | "Line 1 : String s\n", 101 | "Line 2 : String t\n", 102 | "Output Format :\n", 103 | "true or false\n", 104 | "\n", 105 | "Sample Input 1 :\n", 106 | "abchjsgsuohhdhyrikkknddg\n", 107 | "coding\n", 108 | "Sample Output 1 :\n", 109 | "true\n", 110 | "\n", 111 | "Sample Input 2 :\n", 112 | "abcde\n", 113 | "aeb\n", 114 | "Sample Output 2 :\n", 115 | "false\n", 116 | "'''\n", 117 | "\n", 118 | "\n", 119 | "def contains(s, t, lenS, lenT):\n", 120 | " \n", 121 | " if lenT==0:\n", 122 | " return True\n", 123 | " \n", 124 | " if lenS==0:\n", 125 | " return False\n", 126 | " \n", 127 | " if(s[lenS-1]==t[lenT-1]):\n", 128 | " return contains(s, t, lenS-1, lenT-1)\n", 129 | " \n", 130 | " else:\n", 131 | " return contains(s, t, lenS-1, lenT)\n", 132 | " \n", 133 | "\n", 134 | "s = input()\n", 135 | "t = input()\n", 136 | "\n", 137 | "lenS = len(s)\n", 138 | "lenT = len(t)\n", 139 | "\n", 140 | "ans = contains(s, t, lenS, lenT)\n", 141 | "if ans is True:\n", 142 | " print('true')\n", 143 | "else:\n", 144 | " print('false')" 145 | ] 146 | }, 147 | { 148 | "cell_type": "code", 149 | "source": [ 150 | "'''\n", 151 | "Split Array\n", 152 | "\n", 153 | "Given an integer array A of size N, check if the input array can be splitted in two parts such that -\n", 154 | "- Sum of both parts is equal\n", 155 | "- All elements in the input, which are divisible by 5 should be in same group.\n", 156 | "- All elements in the input, which are divisible by 3 (but not divisible by 5) should be in other group.\n", 157 | "- Elements which are neither divisible by 5 nor by 3, can be put in any group.\n", 158 | "Groups can be made with any set of elements, i.e. elements need not to be continuous. And you need to consider each and every element of input array in some group.\n", 159 | "Return true, if array can be split according to the above rules, else return false.\n", 160 | "\n", 161 | "Input Format :\n", 162 | "Line 1 : Integer N (size of array)\n", 163 | "Line 2 : Array A elements (separated by space)\n", 164 | "Output Format :\n", 165 | "true or false\n", 166 | "\n", 167 | "Constraints :\n", 168 | "1 <= N <= 50\n", 169 | "\n", 170 | "Sample Input 1 :\n", 171 | "2\n", 172 | "1 2\n", 173 | "Sample Output 1 :\n", 174 | "false\n", 175 | "\n", 176 | "Sample Input 2 :\n", 177 | "3\n", 178 | "1 4 3\n", 179 | "Sample Output 2 :\n", 180 | "true\n", 181 | "'''\n", 182 | "\n", 183 | "\n", 184 | "def split(arr, start, end, arrSum1, arrSum2):\n", 185 | " \n", 186 | " if start>end:\n", 187 | " return arrSum1==arrSum2\n", 188 | " \n", 189 | " if arr[start]%5 == 0:\n", 190 | " return split(arr, start+1, end, arrSum1+arr[start], arrSum2)\n", 191 | " \n", 192 | " elif arr[start]%3 == 0:\n", 193 | " return split(arr, start+1, end, arrSum1, arrSum2+arr[start])\n", 194 | " \n", 195 | " else:\n", 196 | " return split(arr, start+1, end, arrSum1, arrSum2+arr[start]) or split(arr, start+1, end, arrSum1+arr[start], arrSum2)\n", 197 | " \n", 198 | " \n", 199 | "n = int(input())\n", 200 | "arr = [int(ele) for ele in input().split()]\n", 201 | "\n", 202 | "start = 0\n", 203 | "end = n-1\n", 204 | "arrSum1 = 0\n", 205 | "arrSum2 = 0\n", 206 | "\n", 207 | "ans = split(arr, start, end, arrSum1, arrSum2)\n", 208 | "if ans is True:\n", 209 | " print('true')\n", 210 | "else:\n", 211 | " print('false')" 212 | ], 213 | "metadata": { 214 | "colab": { 215 | "base_uri": "https://localhost:8080/" 216 | }, 217 | "id": "zbUehMfRtGtM", 218 | "outputId": "c72a67cb-b301-47f6-b19b-2ef3a4ba7b47" 219 | }, 220 | "execution_count": null, 221 | "outputs": [ 222 | { 223 | "output_type": "stream", 224 | "name": "stdout", 225 | "text": [ 226 | "2\n", 227 | "1 1\n", 228 | "true\n" 229 | ] 230 | } 231 | ] 232 | }, 233 | { 234 | "cell_type": "code", 235 | "source": [ 236 | "'''\n", 237 | "Maximum Profit on App\n", 238 | "\n", 239 | "You have made a smartphone app and want to set its subscription price such that the profit earned is maximised. There are certain users who will subscribe to your app only if their budget is greater than or equal to your price.\n", 240 | "You will be provided with a list of size N having budgets of subscribers and you need to return the maximum profit that you can earn.\n", 241 | "Lets say you decide that price of your app is Rs. x and there are N number of subscribers. So maximum profit you can earn is :\n", 242 | " m * x\n", 243 | "where m is total number of subscribers whose budget is greater than or equal to x.\n", 244 | "\n", 245 | "Input format :\n", 246 | "Line 1 : N (No. of subscribers)\n", 247 | "Line 2 : Budget of subscribers (separated by space)\n", 248 | "Output Format :\n", 249 | " Maximum profit\n", 250 | "\n", 251 | "Constraints :\n", 252 | "1 <= N <= 10^6\n", 253 | "1 <=budget[i]<=9999\n", 254 | "\n", 255 | "Sample Input 1 :\n", 256 | "4\n", 257 | "30 20 53 14\n", 258 | "Sample Output 1 :\n", 259 | "60\n", 260 | "Sample Output 1 Explanation :\n", 261 | "Price of your app should be Rs. 20 or Rs. 30. For both prices, you can get the profit Rs. 60.\n", 262 | "\n", 263 | "Sample Input 2 :\n", 264 | "5\n", 265 | "34 78 90 15 67\n", 266 | "Sample Output 2 :\n", 267 | "201\n", 268 | "Sample Output 2 Explanation :\n", 269 | "Price of your app should be Rs. 67. You can get the profit Rs. 201 (i.e. 3 * 67).\n", 270 | "'''\n", 271 | "\n", 272 | "def maximumProfit(arr):\n", 273 | " \n", 274 | " maxProfit = 0\n", 275 | " length = len(arr)\n", 276 | " arr.sort()\n", 277 | " \n", 278 | " for i in range(length):\n", 279 | " maxProfit = max(maxProfit, arr[i]*(length-i))\n", 280 | " \n", 281 | " return maxProfit\n", 282 | "\n", 283 | "n = int(input())\n", 284 | "arr = [int(ele) for ele in input().split()]\n", 285 | "ans = maximumProfit(arr)\n", 286 | "print(ans)" 287 | ], 288 | "metadata": { 289 | "colab": { 290 | "base_uri": "https://localhost:8080/" 291 | }, 292 | "id": "-0p5BEImP_4Y", 293 | "outputId": "4630b6f0-b373-4502-946b-c7cec8432785" 294 | }, 295 | "execution_count": null, 296 | "outputs": [ 297 | { 298 | "output_type": "stream", 299 | "name": "stdout", 300 | "text": [ 301 | "4\n", 302 | "20 30 53 14\n", 303 | "60\n" 304 | ] 305 | } 306 | ] 307 | } 308 | ] 309 | } -------------------------------------------------------------------------------- /Test-2/Test_2.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "Test-2", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | } 17 | }, 18 | "cells": [ 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": { 23 | "id": "xXyruCkAr700" 24 | }, 25 | "outputs": [], 26 | "source": [ 27 | "'''\n", 28 | "Next Number\n", 29 | "\n", 30 | "Given a large number represented in the form of a linked list. Write code to increment the \n", 31 | "number by 1 in-place(i.e. without using extra space).\n", 32 | "\n", 33 | "Note: You don't need to print the elements, just update the elements and return the head of updated LL.\n", 34 | "\n", 35 | "Input Constraints:\n", 36 | "1 <= Length of Linked List <=10^6.\n", 37 | "\n", 38 | "Input format :\n", 39 | "Line 1 : Linked list elements (separated by space and terminated by -1)\n", 40 | "\n", 41 | "Output Format :\n", 42 | "Line 1: Updated linked list elements \n", 43 | "\n", 44 | "Sample Input 1 :\n", 45 | "3 9 2 5 -1\n", 46 | "Sample Output 1 :\n", 47 | "3 9 2 6\n", 48 | "\n", 49 | "Sample Input 2 :\n", 50 | "9 9 9 -1\n", 51 | "Sample Output 1 :\n", 52 | "1 0 0 0 \n", 53 | "'''\n", 54 | "\n", 55 | "class Node:\n", 56 | " def __init__(self, data):\n", 57 | " self.data = data\n", 58 | " self.next = None\n", 59 | " \n", 60 | "def reverseLL(head):\n", 61 | " prev = None\n", 62 | " current = head\n", 63 | " while(current is not None):\n", 64 | " next = current.next\n", 65 | " current.next = prev\n", 66 | " prev = current\n", 67 | " current = next\n", 68 | " return prev\n", 69 | "\n", 70 | "def nextNumber(head):\n", 71 | " head = reverseLL(head)\n", 72 | " carry = 1\n", 73 | " temp = head\n", 74 | " while(temp is not None):\n", 75 | " sum = temp.data + carry\n", 76 | " temp.data = sum%10\n", 77 | " carry = sum//10\n", 78 | " temp = temp.next\n", 79 | " \n", 80 | " if carry==1:\n", 81 | " temp = head\n", 82 | " while(temp.next is not None):\n", 83 | " temp = temp.next\n", 84 | " newNode = Node(carry)\n", 85 | " temp.next = newNode\n", 86 | " \n", 87 | " return reverseLL(head)\n", 88 | " \n", 89 | " \n", 90 | "def ll(arr):\n", 91 | " if len(arr)==0:\n", 92 | " return None\n", 93 | " head = Node(arr[0])\n", 94 | " last = head\n", 95 | " for data in arr[1:]:\n", 96 | " last.next = Node(data)\n", 97 | " last = last.next\n", 98 | " return head\n", 99 | "\n", 100 | "def printll(head):\n", 101 | " while head is not None:\n", 102 | " print(head.data,end= ' ')\n", 103 | " head = head.next\n", 104 | " return\n", 105 | "\n", 106 | "# Read the link list elements including -1\n", 107 | "arr=[int(ele) for ele in input().split()]\n", 108 | "# Create a Linked list after removing -1 from list\n", 109 | "l = ll(arr[:-1])\n", 110 | "head = nextNumber(l)\n", 111 | "printll(head)" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "source": [ 117 | "'''\n", 118 | "Dequeue\n", 119 | "\n", 120 | "You need to implement a class for Dequeue i.e. for double ended queue. In this queue, elements can be \n", 121 | "inserted and deleted from both the ends.\n", 122 | "\n", 123 | "You don't need to double the capacity.\n", 124 | "\n", 125 | "You need to implement the following functions -\n", 126 | "\n", 127 | "1. constructor - You need to create the appropriate constructor. Size for the queue passed is 10.\n", 128 | "2. insertFront - This function takes an element as input and insert the element at the front of queue. \n", 129 | "Insert the element only if queue is not full. And if queue is full, print -1 and return.\n", 130 | "3. insertRear - This function takes an element as input and insert the element at the end of queue. \n", 131 | "Insert the element only if queue is not full. And if queue is full, print -1 and return.\n", 132 | "4. deleteFront - This function removes an element from the front of queue. Print -1 if queue is empty.\n", 133 | "5. deleteRear - This function removes an element from the end of queue. Print -1 if queue is empty.\n", 134 | "6. getFront - Returns the element which is at front of the queue. Return -1 if queue is empty.\n", 135 | "7. getRear - Returns the element which is at end of the queue. Return -1 if queue is empty.\n", 136 | "\n", 137 | "Sample Input 1:\n", 138 | "5\n", 139 | "1\n", 140 | "49\n", 141 | "1\n", 142 | "64\n", 143 | "2\n", 144 | "99\n", 145 | "5\n", 146 | "6\n", 147 | "-1\n", 148 | "\n", 149 | "Sample Output 1:\n", 150 | "-1\n", 151 | "64\n", 152 | "99\n", 153 | "\n", 154 | "Explanation:\n", 155 | "The first choice code corresponds to getFront. Since the queue is empty, hence the output is -1. \n", 156 | "The following input adds 49 at the top and the resultant queue becomes: 49.\n", 157 | "The following input adds 64 at the top and the resultant queue becomes: 64 -> 49\n", 158 | "The following input add 99 at the end and the resultant queue becomes: 64 -> 49 -> 99\n", 159 | "The following input corresponds to getFront. Hence the output is 64.\n", 160 | "The following input corresponds to getRear. Hence the output is 99.\n", 161 | "'''\n", 162 | "\n", 163 | "import collections\n", 164 | "inp_ls = list(map(int, input().split()))\n", 165 | "itr = 0\n", 166 | "queue = collections.deque()\n", 167 | "n = 0\n", 168 | "while inp_ls[itr]!=-1:\n", 169 | " choice = inp_ls[itr]\n", 170 | " if(choice==1):\n", 171 | " itr = itr+1\n", 172 | " if(n<=9):\n", 173 | " queue.appendleft(inp_ls[itr])\n", 174 | " n += 1\n", 175 | " else:\n", 176 | " print(-1)\n", 177 | " elif(choice==2):\n", 178 | " itr = itr+1\n", 179 | " if(n<=9):\n", 180 | " queue.append(inp_ls[itr])\n", 181 | " n += 1\n", 182 | " else:\n", 183 | " print(-1)\n", 184 | " elif(choice==3):\n", 185 | " if(n>=1):\n", 186 | " queue.popleft()\n", 187 | " n -= 1\n", 188 | " else:\n", 189 | " print(-1)\n", 190 | " elif(choice==4):\n", 191 | " if(n>=1):\n", 192 | " queue.pop()\n", 193 | " n -= 1\n", 194 | " else:\n", 195 | " print(-1)\n", 196 | " elif(choice==5):\n", 197 | " if(n>=1):\n", 198 | " element = queue.popleft()\n", 199 | " print(element)\n", 200 | " queue.appendleft(element)\n", 201 | " else:\n", 202 | " print(-1)\n", 203 | " elif(choice==6):\n", 204 | " if(n>=1):\n", 205 | " element = queue.pop()\n", 206 | " print(element)\n", 207 | " queue.append(element)\n", 208 | " else:\n", 209 | " print(-1)\n", 210 | " itr =itr + 1" 211 | ], 212 | "metadata": { 213 | "id": "XCfBRa2RskmD" 214 | }, 215 | "execution_count": null, 216 | "outputs": [] 217 | }, 218 | { 219 | "cell_type": "code", 220 | "source": [ 221 | "'''\n", 222 | "Delete Alternate Nodes\n", 223 | "\n", 224 | "Given a Singly Linked List of integers, delete all the alternate nodes in the list.\n", 225 | "\n", 226 | "Example:\n", 227 | "List: 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> null\n", 228 | "Alternate nodes will be: 20, 40, and 60.\n", 229 | "\n", 230 | "Hence after deleting, the list will be:\n", 231 | "Output: 10 -> 30 -> 50 -> null\n", 232 | "\n", 233 | "Note :\n", 234 | "The head of the list will remain the same. Don't need to print or return anything.\n", 235 | "\n", 236 | "Input format :\n", 237 | "The first and the only line of input will contain the elements of the Singly Linked List separated by \n", 238 | "a single space and terminated by -1.\n", 239 | "\n", 240 | "Output Format :\n", 241 | "The only line of output will contain the updated list elements.\n", 242 | "\n", 243 | "Input Constraints:\n", 244 | "1 <= N <= 10 ^ 6.\n", 245 | "Where N is the size of the Singly Linked List\n", 246 | "\n", 247 | "Time Limit: 1 sec\n", 248 | "\n", 249 | "Sample Input 1:\n", 250 | "1 2 3 4 5 -1\n", 251 | "Sample Output 1:\n", 252 | "1 3 5\n", 253 | "Explanation of Sample Input 1:\n", 254 | "2, 4 are alternate nodes so we need to delete them \n", 255 | "\n", 256 | "Sample Input 2:\n", 257 | "10 20 30 40 50 60 70 -1\n", 258 | "Sample Output 2:\n", 259 | "10 30 50 70 \n", 260 | "'''\n", 261 | "\n", 262 | "import math\n", 263 | "\n", 264 | "class Node:\n", 265 | "\tdef _init_(self, data):\n", 266 | "\t\tself.data = data\n", 267 | "\t\tself.next = None\n", 268 | "\n", 269 | "def deleteAlternateNodes(head):\n", 270 | "\tif (head == None):\n", 271 | "\t\treturn\n", 272 | "\tprev = head\n", 273 | "\tnow = head.next\n", 274 | "\twhile (prev != None and now != None):\n", 275 | "\t\tprev.next = now.next\n", 276 | "\t\tnow = None\n", 277 | "\t\tprev = prev.next\n", 278 | "\t\tif (prev != None):\n", 279 | "\t\t\tnow = prev.next" 280 | ], 281 | "metadata": { 282 | "id": "wlpObXDts-f8" 283 | }, 284 | "execution_count": null, 285 | "outputs": [] 286 | } 287 | ] 288 | } --------------------------------------------------------------------------------