├── README.md ├── addTwoStrings.png ├── loopDetected.png ├── intersectionOfTwoLinkedList.png ├── 27RemoveElement.java ├── 26RemoveDuplicates.java ├── 242isAnagram.java ├── 50myPow.java ├── 28strStr.java ├── 49groupAnagrams.java ├── 206ReverseLinkedList.java ├── 12IntegertoRoman.java ├── 3LengthOfLongestSubstring.java ├── 48RotateImage.java ├── 1184distanceBetweenBusStops.java ├── 152MaximumProductSubarray.java ├── 13RomantoInteger.java ├── rainWaterTrap.py ├── 104MaximumDepthofBinaryTree.java ├── 24swapPairs.java ├── 6ZigZagConversion.java ├── 15_3Sum.java ├── 94BinaryTreeInorderTraversal.java ├── 29DivideTwoIntegers.java ├── 94inorderTraversal.java ├── 20ValidParentheses.java ├── 19removeNthFromEnd.java ├── 994RottingOranges.java ├── 3. Longest Substring Repeating Characters.ipynb ├── 38CountandSay.java ├── 98isValidBST.java ├── 17LetterCombinations.java ├── 23mergeKLists.java ├── 415. Add two Strings.ipynb ├── Binary-Tree.ipynb ├── Stack-Linked-List.ipynb ├── Binary-Tree-BST.ipynb ├── Detect-Loop-Linked-List.ipynb ├── In-Order-Traversal-Without-Recursion.ipynb ├── Intersection-of-Linked-List.ipynb ├── SinglyLinkedList.ipynb └── Tree-Traversal.ipynb /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | Problem Solving 3 | -------------------------------------------------------------------------------- /addTwoStrings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chandu-muthyala/LeetCode/master/addTwoStrings.png -------------------------------------------------------------------------------- /loopDetected.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chandu-muthyala/LeetCode/master/loopDetected.png -------------------------------------------------------------------------------- /intersectionOfTwoLinkedList.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chandu-muthyala/LeetCode/master/intersectionOfTwoLinkedList.png -------------------------------------------------------------------------------- /27RemoveElement.java: -------------------------------------------------------------------------------- 1 | class 27RemoveElement { 2 | public int removeElement(int[] nums, int val) { 3 | int k = 0; 4 | for(int i = 0; i0){ 13 | if(n%2 ==1) result *=x; 14 | x = x*x; 15 | n = n >> 1; 16 | } 17 | return result; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /28strStr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int strStr(String haystack, String needle) { 3 | int haystack_length = haystack.length(); 4 | int needle_length = needle.length(); 5 | if(needle.isEmpty()) return 0; 6 | 7 | for(int i = 0; i<=haystack_length-needle_length; i++){ 8 | for(int j = 0; j< needle_length && haystack.charAt(i+j) == needle.charAt(j); j++){ 9 | if(j == needle_length-1) return i; 10 | } 11 | } 12 | return -1; 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /49groupAnagrams.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> groupAnagrams(String[] strs) { 3 | if(strs == null || strs.length ==0 ) return new ArrayList(); 4 | Map ans = new HashMap(); 5 | for(String s: strs){ 6 | char[] ca = s.toCharArray(); 7 | Arrays.sort(ca); 8 | String key = String.valueOf(ca); 9 | if(!ans.containsKey(key)) ans.put(key, new ArrayList()); 10 | ans.get(key).add(s); 11 | } 12 | return new ArrayList(ans.values()); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /206ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class 206ReverseLinkedList { 10 | public ListNode reverseList(ListNode head) { 11 | ListNode revHead = null; 12 | while(head != null){ 13 | ListNode new_node = new ListNode(head.val); 14 | new_node.next = revHead; 15 | revHead = new_node; 16 | head = head.next; 17 | } 18 | return revHead; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /12IntegertoRoman.java: -------------------------------------------------------------------------------- 1 | class 12IntegertoRoman { 2 | public String intToRoman(int num) { 3 | int arabics[] = new int[]{1000, 900, 500, 400, 100, 90, 50,40, 10, 9, 5, 4, 1}; 4 | String romans[] = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 5 | StringBuilder sb = new StringBuilder(); 6 | for(int i= 0; i=0){ 8 | sb.append(romans[i]); 9 | num = num-arabics[i]; 10 | } 11 | } 12 | return sb.toString(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /3LengthOfLongestSubstring.java: -------------------------------------------------------------------------------- 1 | class 3LengthOfLongestSubstring { 2 | public int lengthOfLongestSubstring(String s) { 3 | int ans = 0, i = 0, j = 0; 4 | Set set = new HashSet(); 5 | int l = s.length(); 6 | while(i=start && idestination && (i>=start || i map = new HashMap(); 4 | map.put('M', 1000); 5 | map.put('D', 500); 6 | map.put('C', 100); 7 | map.put('L', 50); 8 | map.put('X', 10); 9 | map.put('V', 5); 10 | map.put('I', 1); 11 | int sum = map.get(s.charAt(0)); 12 | for(int i=1; imap.get(s.charAt(i-1))){ 14 | sum += map.get(s.charAt(i)) - (2*map.get(s.charAt(i-1))); 15 | }else{ 16 | sum += map.get(s.charAt(i)); 17 | } 18 | } 19 | return sum; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /rainWaterTrap.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def trap(self, height): 3 | """ 4 | :type height: List[int] 5 | :rtype: int 6 | """ 7 | total_water = 0 8 | l_max = 0 9 | r_max = 0 10 | l = 0 11 | r = len(height) - 1 12 | while r > l: 13 | if height[l]= l_max: 15 | l_max = height[l] 16 | else: 17 | total_water += l_max - height[l] 18 | 19 | l += 1 20 | else: 21 | if height[r] >= r_max: 22 | r_max = height[r] 23 | else: 24 | total_water += r_max - height[r] 25 | 26 | r -= 1 27 | return total_water 28 | -------------------------------------------------------------------------------- /104MaximumDepthofBinaryTree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxDepth(TreeNode root) { 3 | if (root == null) return 0; 4 | 5 | int left_depth = maxDepth(root.left); 6 | int right_depth = maxDepth(root.right); 7 | 8 | return Math.max(left_depth, right_depth)+1; 9 | } 10 | } 11 | 12 | // 2nd Method 13 | class Solution { 14 | int answer = 0; 15 | public int maxDepth(TreeNode root) { 16 | return answer; 17 | 18 | } 19 | public void max_depth(TreeNode root, int depth){ 20 | if (root == null) return; 21 | 22 | if (root.left == null && root.right == null){ 23 | answer = Math.max(answer, depth); 24 | } 25 | max_depth(root.left, depth+1); 26 | max_depth(root.right, depth+1); 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /24swapPairs.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode swapPairs(ListNode head) { 13 | ListNode first, second, current, dummy = new ListNode(0); 14 | dummy.next = head; 15 | current = dummy; 16 | while(current.next != null && current.next.next != null){ 17 | first = current.next; 18 | second = current.next.next; 19 | 20 | first.next = second.next; 21 | current.next = second; 22 | 23 | current.next.next = first; 24 | current = current.next.next; 25 | } 26 | return dummy.next; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /6ZigZagConversion.java: -------------------------------------------------------------------------------- 1 | class 6ZigZagConversion { 2 | public String convert(String s, int numRows) { 3 | 4 | if(numRows<2) return s; 5 | 6 | int length = s.length(); 7 | List rows = new ArrayList<>(); 8 | String zigzag = ""; 9 | int min = Math.min(numRows, length); 10 | 11 | for(int i = 0; i <= min; i++){ 12 | rows.add(new StringBuilder()); 13 | } 14 | 15 | int curRow = 0; 16 | Boolean goingDown = false; 17 | for(char ch: s.toCharArray()){ 18 | rows.get(curRow).append(ch); 19 | if(curRow == 0 || curRow == (min-1)){ 20 | goingDown = !goingDown; 21 | } 22 | curRow += goingDown ? 1 : -1; 23 | } 24 | for(int i =0; i> threeSum(int[] nums) { 3 | List> output = new LinkedList(); 4 | Arrays.sort(nums); 5 | for(int i= 0; i0 && nums[i] != nums[i-1])){ 7 | int left = i+1; 8 | int right = nums.length-1; 9 | int sum = 0-nums[i]; 10 | while(leftsum){ 18 | right--; 19 | }else{ 20 | left++; 21 | } 22 | } 23 | } 24 | while(i < nums.length-1 && nums[i] == nums[i+1]) i++; 25 | 26 | } 27 | return output; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /94BinaryTreeInorderTraversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class 94BinaryTreeInorderTraversal { 11 | public List inorderTraversal(TreeNode root) { 12 | List inOrderList=new ArrayList(); 13 | 14 | // ***** DFS **** 15 | // getInorderList(root, inOrderList); 16 | // return inOrderList; 17 | 18 | // } 19 | // public void getInorderList(TreeNode root, List inOrderList){ 20 | // if(root == null){ 21 | // return; 22 | // } 23 | // getInorderList(root.left, inOrderList); 24 | // inOrderList.add(root.val); 25 | // getInorderList(root.right, inOrderList); 26 | // } 27 | 28 | Stack stack = new Stack(); 29 | while (root != null || !stack.empty()) { 30 | while (root != null) { 31 | stack.add(root); 32 | root = root.left; 33 | } 34 | root = stack.pop(); 35 | inOrderList.add(root.val); 36 | root = root.right; 37 | } 38 | return inOrderList; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /29DivideTwoIntegers.java: -------------------------------------------------------------------------------- 1 | // Brute Force Time limit exceeds 2 | class Solution { 3 | public int divide(int dividend, int divisor) { 4 | if(dividend == Integer.MIN_VALUE && divisor==-1){ 5 | return Integer.MAX_VALUE; 6 | } 7 | 8 | int sign = (dividend<0) ^ (divisor<0)?-1:1; 9 | int result = 0; 10 | long x = Math.abs((long)dividend); 11 | long y = Math.abs((long)divisor); 12 | while(x>=y){ 13 | x = x-y; 14 | result++; 15 | } 16 | return result*sign; 17 | 18 | } 19 | } 20 | 21 | // 2nd method-maximum divisor power 22 | class Solution { 23 | public int divide(int dividend, int divisor) { 24 | if(dividend == Integer.MIN_VALUE && divisor==-1){ 25 | return Integer.MAX_VALUE; 26 | } 27 | 28 | int sign = (dividend<0) ^ (divisor<0)?-1:1; 29 | int result = 0; 30 | 31 | long x = Math.abs((long)dividend); 32 | long y = Math.abs((long)divisor); 33 | 34 | while(x-y>=0){ 35 | int count = 0; 36 | while(x-(y<<1<=0){ 37 | count++; 38 | } 39 | result += 1< inorderTraversal(TreeNode root) { 12 | List inOrderList = new ArrayList(); 13 | 14 | getInorderList(root, inOrderList); 15 | return inOrderList; 16 | } 17 | 18 | public void getInorderList(TreeNode root, List inOrderList){ 19 | 20 | if(root == null){ 21 | return; 22 | } 23 | getInorderList(root.left, inOrderList); 24 | inOrderList.add(root.val); 25 | getInorderList(root.right, inOrderList); 26 | } 27 | } 28 | 29 | 30 | // Method-2: 31 | class Solution { 32 | public List inorderTraversal(TreeNode root) { 33 | List inOrderList = new ArrayList(); 34 | Stack stack = new Stack(); 35 | while(root != null || !stack.isEmpty()){ 36 | while(root != null){ 37 | stack.add(root); 38 | root = root.left; 39 | } 40 | root = stack.pop(); 41 | inOrderList.add(root.val); 42 | root = root.right; 43 | } 44 | return inOrderList; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /20ValidParentheses.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isValid(String s) { 3 | Stack stack = new Stack<>(); 4 | for(int i = 0; i0){ 27 | temp = temp.next; 28 | count--; 29 | } 30 | temp.next = temp.next.next; 31 | return current.next; 32 | } 33 | } 34 | 35 | 36 | // Second solution 37 | class Solution { 38 | public ListNode removeNthFromEnd(ListNode head, int n) { 39 | ListNode fast, slow, temp = new ListNode(0); 40 | temp.next = head; 41 | fast = temp; 42 | slow = temp; 43 | while(n>=0){ 44 | fast = fast.next; 45 | n--; 46 | } 47 | while(fast != null){ 48 | fast = fast.next; 49 | slow = slow.next; 50 | } 51 | slow.next = slow.next.next; 52 | return temp.next; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /994RottingOranges.java: -------------------------------------------------------------------------------- 1 | class 994RottingOranges { 2 | public int orangesRotting(int[][] grid) { 3 | int row = grid.length, col = grid[0].length; 4 | int freshCount = 0; 5 | Queue rotten = new LinkedList<>(); 6 | for (int i =0; i= row || y >= col || x < 0 || y < 0 || grid[x][y] != 1 ){ 29 | continue; 30 | } 31 | grid[x][y] = 2; 32 | rotten.add(new int[]{x,y}); 33 | freshCount--; 34 | 35 | } 36 | } 37 | 38 | totalMinutes++; 39 | } 40 | return freshCount == 0 ? totalMinutes - 1: -1; 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /3. Longest Substring Repeating Characters.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 75, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "def longestSubString(string):\n", 10 | " index = 0\n", 11 | " temp = []\n", 12 | " maxLen = 0\n", 13 | " while len(string) > index:\n", 14 | " temp.append(string[index])\n", 15 | " if len(temp) == len(set(temp)):\n", 16 | " maxLen = len(temp)\n", 17 | " else:\n", 18 | " temp = temp[1:]\n", 19 | " index = index+1\n", 20 | " print('Longest Sub-String in string:', \"\".join(temp), \", length:\", maxLen) " 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": 76, 26 | "metadata": {}, 27 | "outputs": [], 28 | "source": [ 29 | "string = \"abcafghbcfgaabc\"" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": 77, 35 | "metadata": {}, 36 | "outputs": [ 37 | { 38 | "name": "stdout", 39 | "output_type": "stream", 40 | "text": [ 41 | "Longest Sub-String in string: fgaabc , length: 6\n" 42 | ] 43 | } 44 | ], 45 | "source": [ 46 | "longestSubString(string)" 47 | ] 48 | } 49 | ], 50 | "metadata": { 51 | "kernelspec": { 52 | "display_name": "Python 3", 53 | "language": "python", 54 | "name": "python3" 55 | }, 56 | "language_info": { 57 | "codemirror_mode": { 58 | "name": "ipython", 59 | "version": 3 60 | }, 61 | "file_extension": ".py", 62 | "mimetype": "text/x-python", 63 | "name": "python", 64 | "nbconvert_exporter": "python", 65 | "pygments_lexer": "ipython3", 66 | "version": "3.6.4" 67 | } 68 | }, 69 | "nbformat": 4, 70 | "nbformat_minor": 2 71 | } 72 | -------------------------------------------------------------------------------- /38CountandSay.java: -------------------------------------------------------------------------------- 1 | class 38CountandSay { 2 | public String countAndSay(int n) { 3 | 4 | if(n<0) return null; 5 | 6 | String s = "1"; 7 | for(int i = 1; i1){ 41 | temp = ""; 42 | for(int i = 0; i1){ 64 | StringBuilder temp = new StringBuilder(); 65 | for(int i = 0; i=val) return false; 26 | if(upper != null && upper<=val) return false; 27 | 28 | if( !isValidNode(node.left, lower, val) ) return false; 29 | if( !isValidNode(node.right, val, upper)) return false; 30 | 31 | return true; 32 | 33 | 34 | } 35 | } 36 | 37 | // 2nd method 38 | class Solution { 39 | LinkedList stack = new LinkedList(); 40 | LinkedList uppers = new LinkedList(); 41 | LinkedList lowers = new LinkedList(); 42 | public void updateStack(TreeNode node, Integer lower, Integer upper){ 43 | stack.add(node); 44 | lowers.add(lower); 45 | uppers.add(upper); 46 | } 47 | public boolean isValidBST(TreeNode root) { 48 | Integer upper = null, lower = null, val; 49 | updateStack(root, lower, upper); 50 | while(!stack.isEmpty()){ 51 | root = stack.poll(); 52 | lower = lowers.poll(); 53 | upper = uppers.poll(); 54 | if(root == null) continue; 55 | val = root.val; 56 | if(lower != null && lower>=val) return false; 57 | if(upper != null && upper <= val) return false; 58 | 59 | updateStack(root.left, lower, val); 60 | updateStack(root.right, val, upper); 61 | } 62 | return true; 63 | 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /17LetterCombinations.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // DFS Recursive Method 3 | Map phone = new HashMap() {{ 4 | put("2", "abc"); 5 | put("3", "def"); 6 | put("4", "ghi"); 7 | put("5", "jkl"); 8 | put("6", "mno"); 9 | put("7", "pqrs"); 10 | put("8", "tuv"); 11 | put("9", "wxyz"); 12 | }}; 13 | List output = new ArrayList(); 14 | 15 | public void getCombinations(String combination, String next_digit){ 16 | if(next_digit.length() == 0){ 17 | output.add(combination); 18 | }else{ 19 | String digit = next_digit.substring(0,1); 20 | String letters = phone.get(digit); 21 | for(int i = 0; i letterCombinations(String digits) { 28 | if(digits.length() !=0){ 29 | getCombinations("", digits); 30 | } 31 | return output; 32 | } 33 | 34 | // BFS: Iterative Method 35 | public List letterCombinations(String digits) { 36 | HashMap phone = new HashMap<>(); 37 | phone.put('2', "abc"); 38 | phone.put('3', "def"); 39 | phone.put('4', "ghi"); 40 | phone.put('5', "jkl"); 41 | phone.put('6', "mno"); 42 | phone.put('7', "pqrs"); 43 | phone.put('8', "tuv"); 44 | phone.put('9', "wxyz"); 45 | 46 | List output = new ArrayList<>(); 47 | if (digits.length() == 0) { 48 | return output; 49 | } 50 | 51 | output.add(""); 52 | for(int i = 0; i temp = new ArrayList(); 55 | for(int j = 0; j0){ 19 | while(l>0){ 20 | lists[0] = mergeTwoLists(lists[0], lists[l]); 21 | l--; 22 | } 23 | } 24 | 25 | return lists[0]; 26 | } 27 | public ListNode mergeTwoLists(ListNode l1, ListNode l2){ 28 | ListNode head = new ListNode(0), current = head; 29 | while(l1 != null && l2 !=null){ 30 | if(l1.val0){ 64 | int i =0, j = l; 65 | while(i=j){ 71 | l = j; 72 | } 73 | 74 | } 75 | 76 | return lists[0]; 77 | } 78 | public ListNode mergeTwoLists(ListNode l1, ListNode l2){ 79 | ListNode head = new ListNode(0), current = head; 80 | while(l1 != null && l2 !=null){ 81 | if(l1.val" 12 | ], 13 | "text/plain": [ 14 | "" 15 | ] 16 | }, 17 | "metadata": {}, 18 | "output_type": "display_data" 19 | } 20 | ], 21 | "source": [ 22 | "%%html\n", 23 | "\"addTwoStrings\"" 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": 5, 29 | "metadata": {}, 30 | "outputs": [ 31 | { 32 | "data": { 33 | "text/plain": [ 34 | "48" 35 | ] 36 | }, 37 | "execution_count": 5, 38 | "metadata": {}, 39 | "output_type": "execute_result" 40 | } 41 | ], 42 | "source": [ 43 | "ord('0') #is used to calculate ascii va" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": 19, 49 | "metadata": {}, 50 | "outputs": [], 51 | "source": [ 52 | "def convertToInteger(temp_str):\n", 53 | " '''\n", 54 | " This function is used to convert string to integer \n", 55 | " \n", 56 | " arg: str,\n", 57 | " \n", 58 | " return: integer\n", 59 | " '''\n", 60 | " k = 0\n", 61 | " for i in temp_str:\n", 62 | " k = k*10 + (ord(i) - 48)\n", 63 | " return k\n", 64 | "\n", 65 | "def addStrings(str1, str2):\n", 66 | " '''\n", 67 | " this function is used to send two str to func to convert and add them and return the result\n", 68 | " arg(str1, sytr2):str,\n", 69 | " return: sum of two strings\n", 70 | " '''\n", 71 | " result = convertToInteger(str1)+convertToInteger(str2)\n", 72 | " return result" 73 | ] 74 | }, 75 | { 76 | "cell_type": "code", 77 | "execution_count": 20, 78 | "metadata": {}, 79 | "outputs": [ 80 | { 81 | "data": { 82 | "text/plain": [ 83 | "24" 84 | ] 85 | }, 86 | "execution_count": 20, 87 | "metadata": {}, 88 | "output_type": "execute_result" 89 | } 90 | ], 91 | "source": [ 92 | "addStrings('21','3')" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": null, 98 | "metadata": {}, 99 | "outputs": [], 100 | "source": [] 101 | } 102 | ], 103 | "metadata": { 104 | "kernelspec": { 105 | "display_name": "Python 3", 106 | "language": "python", 107 | "name": "python3" 108 | }, 109 | "language_info": { 110 | "codemirror_mode": { 111 | "name": "ipython", 112 | "version": 3 113 | }, 114 | "file_extension": ".py", 115 | "mimetype": "text/x-python", 116 | "name": "python", 117 | "nbconvert_exporter": "python", 118 | "pygments_lexer": "ipython3", 119 | "version": "3.6.4" 120 | } 121 | }, 122 | "nbformat": 4, 123 | "nbformat_minor": 2 124 | } 125 | -------------------------------------------------------------------------------- /Binary-Tree.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 4, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "class Node:\n", 10 | " def __init__(self, data):\n", 11 | " '''\n", 12 | " This is a Node class default constructor for all the parents nodes.\n", 13 | " '''\n", 14 | " self.left = None\n", 15 | " self.right = None\n", 16 | " self.data = data\n", 17 | " \n", 18 | " def insert(self, data):\n", 19 | " '''\n", 20 | " This func is used to insert element into to the binary tree.\n", 21 | " '''\n", 22 | " if self.data is None:\n", 23 | " self.data = data\n", 24 | " elif self.data > data:\n", 25 | " if self.left is None:\n", 26 | " self.left = Node(data)\n", 27 | " else:\n", 28 | " self.left.insert(data)\n", 29 | " elif self.data < data:\n", 30 | " if self.right is None:\n", 31 | " self.right = Node(data)\n", 32 | " else:\n", 33 | " self.right.insert(data)\n", 34 | " def printTree(self):\n", 35 | " '''\n", 36 | " Print Binary Tree \n", 37 | " '''\n", 38 | " if self.left:\n", 39 | " self.left.printTree()\n", 40 | " print(self.data, end=' ')\n", 41 | " if self.right:\n", 42 | " self.right.printTree() " 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": 5, 48 | "metadata": {}, 49 | "outputs": [ 50 | { 51 | "name": "stdout", 52 | "output_type": "stream", 53 | "text": [ 54 | "10 " 55 | ] 56 | } 57 | ], 58 | "source": [ 59 | "root = Node(10)\n", 60 | "root.printTree()" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": 6, 66 | "metadata": {}, 67 | "outputs": [ 68 | { 69 | "name": "stdout", 70 | "output_type": "stream", 71 | "text": [ 72 | "4 5 6 8 10 11 12 13 " 73 | ] 74 | } 75 | ], 76 | "source": [ 77 | "root.insert(8)\n", 78 | "root.insert(5)\n", 79 | "root.insert(4)\n", 80 | "root.insert(6)\n", 81 | "root.insert(12)\n", 82 | "root.insert(11)\n", 83 | "root.insert(13)\n", 84 | "root.printTree()" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": null, 90 | "metadata": {}, 91 | "outputs": [], 92 | "source": [] 93 | } 94 | ], 95 | "metadata": { 96 | "kernelspec": { 97 | "display_name": "Python 3", 98 | "language": "python", 99 | "name": "python3" 100 | }, 101 | "language_info": { 102 | "codemirror_mode": { 103 | "name": "ipython", 104 | "version": 3 105 | }, 106 | "file_extension": ".py", 107 | "mimetype": "text/x-python", 108 | "name": "python", 109 | "nbconvert_exporter": "python", 110 | "pygments_lexer": "ipython3", 111 | "version": "3.6.4" 112 | } 113 | }, 114 | "nbformat": 4, 115 | "nbformat_minor": 2 116 | } 117 | -------------------------------------------------------------------------------- /Stack-Linked-List.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 3, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "#Creating a Node\n", 10 | "class Node:\n", 11 | " def __init__(self, value=None):\n", 12 | " '''\n", 13 | " Constructor of the class\n", 14 | " args:\n", 15 | " value(DataType:any) - value\n", 16 | " return None\n", 17 | " '''\n", 18 | " self.value = value\n", 19 | " self.next = None" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": 18, 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "class Stack_LL:\n", 29 | " def __init__(self):\n", 30 | " '''\n", 31 | " Constructor of the class\n", 32 | " '''\n", 33 | " self.head = None\n", 34 | " \n", 35 | " def print_LL(self):\n", 36 | " '''\n", 37 | " It will print the entire Stack-Linked List:LIFO\n", 38 | " return None\n", 39 | " '''\n", 40 | " temp_node = self.head\n", 41 | " if temp_node is None:\n", 42 | " print(\"Print: Stack is Empty\")\n", 43 | " return None\n", 44 | " while(temp_node != None):\n", 45 | " print(temp_node.value, end=' ')\n", 46 | " temp_node = temp_node.next\n", 47 | " print()\n", 48 | " def insertE(self, data):\n", 49 | " '''\n", 50 | " Inserting an Element at the beginning of the Stack Linked List\n", 51 | " \n", 52 | " args:\n", 53 | " data(DataType:any) - Value\n", 54 | " return None\n", 55 | " '''\n", 56 | " temp_node = Node(data)\n", 57 | " \n", 58 | " if self.head == None:\n", 59 | " self.head = temp_node\n", 60 | " else:\n", 61 | " temp_node.next = self.head\n", 62 | " self.head = temp_node\n", 63 | " def removeE(self):\n", 64 | " '''\n", 65 | " Removing an Element at the beginning of the Stack Linked List\n", 66 | " \n", 67 | " args:\n", 68 | " data(DataType:any) - Value\n", 69 | " return None\n", 70 | " '''\n", 71 | " if self.head == None:\n", 72 | " print(\"Remove: Stack Is Empty\")\n", 73 | " else:\n", 74 | " temp_node = self.head.next\n", 75 | " self.head = temp_node\n", 76 | " \n", 77 | " " 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "execution_count": 19, 83 | "metadata": {}, 84 | "outputs": [ 85 | { 86 | "name": "stdout", 87 | "output_type": "stream", 88 | "text": [ 89 | "Print: Stack is Empty\n", 90 | "1 \n", 91 | "3 2 1 \n", 92 | "Removing Elements\n", 93 | "2 1 \n", 94 | "1 \n", 95 | "Print: Stack is Empty\n", 96 | "Remove: Stack Is Empty\n", 97 | "Print: Stack is Empty\n" 98 | ] 99 | } 100 | ], 101 | "source": [ 102 | "stack_list = Stack_LL()\n", 103 | "stack_list.print_LL()\n", 104 | "stack_list.insertE(1)\n", 105 | "stack_list.print_LL()\n", 106 | "stack_list.insertE(2)\n", 107 | "stack_list.insertE(3)\n", 108 | "stack_list.print_LL()\n", 109 | "\n", 110 | "#remove Element\n", 111 | "print(\"Removing Elements\")\n", 112 | "stack_list.removeE()\n", 113 | "stack_list.print_LL()\n", 114 | "\n", 115 | "stack_list.removeE()\n", 116 | "stack_list.print_LL()\n", 117 | "\n", 118 | "stack_list.removeE()\n", 119 | "stack_list.print_LL()\n", 120 | "\n", 121 | "stack_list.removeE()\n", 122 | "stack_list.print_LL()" 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": null, 128 | "metadata": {}, 129 | "outputs": [], 130 | "source": [] 131 | } 132 | ], 133 | "metadata": { 134 | "kernelspec": { 135 | "display_name": "Python 3", 136 | "language": "python", 137 | "name": "python3" 138 | }, 139 | "language_info": { 140 | "codemirror_mode": { 141 | "name": "ipython", 142 | "version": 3 143 | }, 144 | "file_extension": ".py", 145 | "mimetype": "text/x-python", 146 | "name": "python", 147 | "nbconvert_exporter": "python", 148 | "pygments_lexer": "ipython3", 149 | "version": "3.6.4" 150 | } 151 | }, 152 | "nbformat": 4, 153 | "nbformat_minor": 2 154 | } 155 | -------------------------------------------------------------------------------- /Binary-Tree-BST.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 44, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "class Node:\n", 10 | " def __init__(self, data):\n", 11 | " '''\n", 12 | " This is a Node class default constructor for all the parents nodes.\n", 13 | " '''\n", 14 | " self.left = None\n", 15 | " self.right = None\n", 16 | " self.data = data\n", 17 | " \n", 18 | " def insert(self, data):\n", 19 | " '''\n", 20 | " This func is used to insert element into to the binary tree.\n", 21 | " '''\n", 22 | " if self.data is None:\n", 23 | " self.data = data\n", 24 | " elif self.data > data:\n", 25 | " if self.left is None:\n", 26 | " self.left = Node(data)\n", 27 | " else:\n", 28 | " self.left.insert(data)\n", 29 | " elif self.data < data:\n", 30 | " if self.right is None:\n", 31 | " self.right = Node(data)\n", 32 | " else:\n", 33 | " self.right.insert(data)\n", 34 | " \n", 35 | " def findValue(self, lkpVal):\n", 36 | " '''\n", 37 | " This function is used to search element in the Tree;\n", 38 | " lkpVal: lookup Value\n", 39 | " return: element found or not\n", 40 | " '''\n", 41 | " if lkpVal < self.data:\n", 42 | " if self.left is None:\n", 43 | " return str(lkpVal)+\" is Not Found in the TREE\"\n", 44 | " return self.left.findValue(lkpVal)\n", 45 | " elif lkpVal > self.data:\n", 46 | " if self.right is None:\n", 47 | " return str(lkpVal)+\" is Not Found in the TREE\"\n", 48 | " return self.right.findValue(lkpVal)\n", 49 | " else:\n", 50 | " print(\"\\n\"+str(lkpVal)+\" is Found in the TREE\")\n", 51 | " \n", 52 | " def printTree(self):\n", 53 | " '''\n", 54 | " Print Binary Tree \n", 55 | " '''\n", 56 | " if self.left:\n", 57 | " self.left.printTree()\n", 58 | " print(self.data, end=' ')\n", 59 | " if self.right:\n", 60 | " self.right.printTree() " 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": 45, 66 | "metadata": {}, 67 | "outputs": [ 68 | { 69 | "name": "stdout", 70 | "output_type": "stream", 71 | "text": [ 72 | "10 " 73 | ] 74 | } 75 | ], 76 | "source": [ 77 | "root = Node(10)\n", 78 | "root.printTree()" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": 46, 84 | "metadata": {}, 85 | "outputs": [ 86 | { 87 | "name": "stdout", 88 | "output_type": "stream", 89 | "text": [ 90 | "4 5 6 8 10 11 12 13 \n", 91 | "11 is Found in the TREE\n" 92 | ] 93 | }, 94 | { 95 | "data": { 96 | "text/plain": [ 97 | "'14 is Not Found in the TREE'" 98 | ] 99 | }, 100 | "execution_count": 46, 101 | "metadata": {}, 102 | "output_type": "execute_result" 103 | } 104 | ], 105 | "source": [ 106 | "#insert into the B-Tree\n", 107 | "root.insert(8)\n", 108 | "root.insert(5)\n", 109 | "root.insert(4)\n", 110 | "root.insert(6)\n", 111 | "root.insert(12)\n", 112 | "root.insert(11)\n", 113 | "root.insert(13)\n", 114 | "#Print Tree\n", 115 | "root.printTree()\n", 116 | "#Find value in the Tree\n", 117 | "\n", 118 | "root.findValue(11) # Found\n", 119 | "root.findValue(14) #Not Found" 120 | ] 121 | }, 122 | { 123 | "cell_type": "code", 124 | "execution_count": null, 125 | "metadata": {}, 126 | "outputs": [], 127 | "source": [] 128 | }, 129 | { 130 | "cell_type": "code", 131 | "execution_count": null, 132 | "metadata": {}, 133 | "outputs": [], 134 | "source": [] 135 | } 136 | ], 137 | "metadata": { 138 | "kernelspec": { 139 | "display_name": "Python 3", 140 | "language": "python", 141 | "name": "python3" 142 | }, 143 | "language_info": { 144 | "codemirror_mode": { 145 | "name": "ipython", 146 | "version": 3 147 | }, 148 | "file_extension": ".py", 149 | "mimetype": "text/x-python", 150 | "name": "python", 151 | "nbconvert_exporter": "python", 152 | "pygments_lexer": "ipython3", 153 | "version": "3.6.4" 154 | } 155 | }, 156 | "nbformat": 4, 157 | "nbformat_minor": 2 158 | } 159 | -------------------------------------------------------------------------------- /Detect-Loop-Linked-List.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 6, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "class Node:\n", 10 | " def __init__(self, data):\n", 11 | " self.data = data\n", 12 | " self.next = None" 13 | ] 14 | }, 15 | { 16 | "cell_type": "code", 17 | "execution_count": 19, 18 | "metadata": {}, 19 | "outputs": [], 20 | "source": [ 21 | "class LinkedList:\n", 22 | " def __init__(self):\n", 23 | " self.head = None\n", 24 | " \n", 25 | " def insertE(self, data):\n", 26 | " temp_node = Node(data)\n", 27 | " if self.head == None:\n", 28 | " self.head = temp_node\n", 29 | " else:\n", 30 | " temp_node.next = self.head\n", 31 | " self.head = temp_node\n", 32 | " \n", 33 | " def printLL(self):\n", 34 | " temp_node = self.head\n", 35 | " if temp_node == None:\n", 36 | " print(\"Empty: No Elements presentin LL.\")\n", 37 | " return None\n", 38 | " else:\n", 39 | " while(temp_node):\n", 40 | " print(temp_node.data, end=' ')\n", 41 | " temp_node = temp_node.next\n", 42 | " print()\n", 43 | " def detectLoop(self):\n", 44 | " temp_list = []\n", 45 | " temp_node = self.head\n", 46 | " if temp_node == None:\n", 47 | "# print(\"Dection: Empty list\")\n", 48 | " return \"Dection: Empty list\"\n", 49 | " else:\n", 50 | " while temp_node.next:\n", 51 | " if temp_node.next in temp_list:\n", 52 | " return \"Detection: True, Found loop in the linked list\"\n", 53 | " else:\n", 54 | " temp_list.append(temp_node.next)\n", 55 | " temp_node = temp_node.next\n", 56 | " return \"Detection: False, loop not found in the linked list\"\n", 57 | " \n", 58 | " def loopStartsAt(self):\n", 59 | " if self.head == None:\n", 60 | " return \"LoopStartAt: Empty List\"\n", 61 | " else:\n", 62 | " slow_p = self.head\n", 63 | " fast_p = self.head\n", 64 | " while(slow_p and fast_p and fast_p.next):\n", 65 | " slow_p = slow_p.next\n", 66 | " fast_p = fast_p.next.next\n", 67 | " if slow_p == fast_p:\n", 68 | " return \"LoopStartAt: \"+str(slow_p.data)\n", 69 | " " 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": 20, 75 | "metadata": {}, 76 | "outputs": [ 77 | { 78 | "name": "stdout", 79 | "output_type": "stream", 80 | "text": [ 81 | "10 4 15 20 \n", 82 | "Detection: True, Found loop in the linked list\n" 83 | ] 84 | }, 85 | { 86 | "data": { 87 | "text/plain": [ 88 | "'LoopStartAt: 10'" 89 | ] 90 | }, 91 | "execution_count": 20, 92 | "metadata": {}, 93 | "output_type": "execute_result" 94 | } 95 | ], 96 | "source": [ 97 | "temp_obj = LinkedList()\n", 98 | "temp_obj.insertE(20)\n", 99 | "temp_obj.insertE(15)\n", 100 | "temp_obj.insertE(4)\n", 101 | "temp_obj.insertE(10)\n", 102 | "\n", 103 | "#print the lonked list\n", 104 | "temp_obj.printLL()\n", 105 | "\n", 106 | "#Create loop\n", 107 | "temp_obj.head.next.next.next.next = temp_obj.head \n", 108 | "\n", 109 | "#Check loop in the linked list\n", 110 | "result = temp_obj.detectLoop()\n", 111 | "print(result)\n", 112 | "#If found Loop starts at which element\n", 113 | "temp_obj.loopStartsAt()" 114 | ] 115 | }, 116 | { 117 | "cell_type": "code", 118 | "execution_count": 26, 119 | "metadata": {}, 120 | "outputs": [ 121 | { 122 | "data": { 123 | "text/html": [ 124 | "" 125 | ], 126 | "text/plain": [ 127 | "" 128 | ] 129 | }, 130 | "metadata": {}, 131 | "output_type": "display_data" 132 | } 133 | ], 134 | "source": [ 135 | "%%html\n", 136 | "" 137 | ] 138 | }, 139 | { 140 | "cell_type": "code", 141 | "execution_count": null, 142 | "metadata": {}, 143 | "outputs": [], 144 | "source": [] 145 | } 146 | ], 147 | "metadata": { 148 | "kernelspec": { 149 | "display_name": "Python 3", 150 | "language": "python", 151 | "name": "python3" 152 | }, 153 | "language_info": { 154 | "codemirror_mode": { 155 | "name": "ipython", 156 | "version": 3 157 | }, 158 | "file_extension": ".py", 159 | "mimetype": "text/x-python", 160 | "name": "python", 161 | "nbconvert_exporter": "python", 162 | "pygments_lexer": "ipython3", 163 | "version": "3.6.4" 164 | } 165 | }, 166 | "nbformat": 4, 167 | "nbformat_minor": 2 168 | } 169 | -------------------------------------------------------------------------------- /In-Order-Traversal-Without-Recursion.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 64, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "class Node:\n", 10 | " def __init__(self, data):\n", 11 | " self.data = data\n", 12 | " self.left = None\n", 13 | " self.right = None\n", 14 | " \n", 15 | " def insert(self, data):\n", 16 | " if self.data is None:\n", 17 | " self.data = Node(data)\n", 18 | " elif self.data > data:\n", 19 | " if self.left:\n", 20 | " self.left.insert(data)\n", 21 | " else:\n", 22 | " self.left = Node(data)\n", 23 | " elif self.data < data:\n", 24 | " if self.right:\n", 25 | " self.right.insert(data)\n", 26 | " else:\n", 27 | " self.right = Node(data)\n", 28 | "def printInOrder(root):\n", 29 | " current = root\n", 30 | " stack = []\n", 31 | " while True:\n", 32 | " if current is not None:\n", 33 | " stack.append(current)\n", 34 | " current = current.left\n", 35 | " elif stack:\n", 36 | " current = stack.pop()\n", 37 | " print(current.data, end = ' ')\n", 38 | " current = current.right\n", 39 | " else:\n", 40 | " break\n", 41 | "\n", 42 | "def printTraversalOrder(root):\n", 43 | " h = height(root)\n", 44 | " for i in range(1, h+1):\n", 45 | " printLevelOrder(root, i)\n", 46 | "def printLevelOrder(node, level):\n", 47 | " if node is None:\n", 48 | " return\n", 49 | " else:\n", 50 | " if level == 1:\n", 51 | " print(node.data, end = ' ')\n", 52 | " elif level>1:\n", 53 | " printLevelOrder(node.left, level-1)\n", 54 | " printLevelOrder(node.right, level-1)\n", 55 | "def height(node):\n", 56 | " if node is None:\n", 57 | " return 0\n", 58 | " else:\n", 59 | " lHeight = height(node.left)\n", 60 | " rHeight = height( node.right)\n", 61 | " \n", 62 | " if lHeight>rHeight:\n", 63 | " return lHeight+1\n", 64 | " else:\n", 65 | " return rHeight+1" 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": 65, 71 | "metadata": {}, 72 | "outputs": [], 73 | "source": [ 74 | "root = Node(5)\n", 75 | "root.insert(7)\n", 76 | "root.insert(6)\n", 77 | "root.insert(4)\n", 78 | "root.insert(3)\n", 79 | "root.insert(1)\n", 80 | "root.insert(2)" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": 66, 86 | "metadata": {}, 87 | "outputs": [ 88 | { 89 | "name": "stdout", 90 | "output_type": "stream", 91 | "text": [ 92 | "1 2 3 4 5 6 7 " 93 | ] 94 | } 95 | ], 96 | "source": [ 97 | "printInOrder(root)" 98 | ] 99 | }, 100 | { 101 | "cell_type": "code", 102 | "execution_count": 67, 103 | "metadata": {}, 104 | "outputs": [ 105 | { 106 | "name": "stdout", 107 | "output_type": "stream", 108 | "text": [ 109 | "5 4 7 3 6 1 2 " 110 | ] 111 | } 112 | ], 113 | "source": [ 114 | "printTraversalOrder(root)" 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": 70, 120 | "metadata": {}, 121 | "outputs": [], 122 | "source": [ 123 | "def printLevelByLevel(root):\n", 124 | " thisLevelNodes = [root]\n", 125 | " mainList = []\n", 126 | " while thisLevelNodes:\n", 127 | " nextLevelNodes = []\n", 128 | " levelData = []\n", 129 | " for node in thisLevelNodes:\n", 130 | " levelData.append(node.data)\n", 131 | " if node.left:\n", 132 | " nextLevelNodes.append(node.left)\n", 133 | " if node.right:\n", 134 | " nextLevelNodes.append(node.right)\n", 135 | " mainList.append(levelData)\n", 136 | " thisLevelNodes = nextLevelNodes\n", 137 | " print(mainList)\n" 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": 71, 143 | "metadata": {}, 144 | "outputs": [ 145 | { 146 | "name": "stdout", 147 | "output_type": "stream", 148 | "text": [ 149 | "[[5], [4, 7], [3, 6], [1], [2]]\n" 150 | ] 151 | } 152 | ], 153 | "source": [ 154 | "printLevelByLevel(root)" 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": null, 160 | "metadata": {}, 161 | "outputs": [], 162 | "source": [] 163 | } 164 | ], 165 | "metadata": { 166 | "kernelspec": { 167 | "display_name": "Python 3", 168 | "language": "python", 169 | "name": "python3" 170 | }, 171 | "language_info": { 172 | "codemirror_mode": { 173 | "name": "ipython", 174 | "version": 3 175 | }, 176 | "file_extension": ".py", 177 | "mimetype": "text/x-python", 178 | "name": "python", 179 | "nbconvert_exporter": "python", 180 | "pygments_lexer": "ipython3", 181 | "version": "3.6.4" 182 | } 183 | }, 184 | "nbformat": 4, 185 | "nbformat_minor": 2 186 | } 187 | -------------------------------------------------------------------------------- /Intersection-of-Linked-List.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "data": { 10 | "text/html": [ 11 | "\"intersection" 12 | ], 13 | "text/plain": [ 14 | "" 15 | ] 16 | }, 17 | "metadata": {}, 18 | "output_type": "display_data" 19 | } 20 | ], 21 | "source": [ 22 | "%%html\n", 23 | "\"intersection" 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": 2, 29 | "metadata": {}, 30 | "outputs": [], 31 | "source": [ 32 | "class Node:\n", 33 | " def __init__(self, data):\n", 34 | " self.data = data\n", 35 | " self.next = None" 36 | ] 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": 3, 41 | "metadata": {}, 42 | "outputs": [], 43 | "source": [ 44 | "class LinkedList:\n", 45 | " def __init__(self, skip):\n", 46 | " self.head = None\n", 47 | " self.skip = skip\n", 48 | " def printLL(self):\n", 49 | " temp_node = self.head\n", 50 | " if temp_node == None:\n", 51 | " print(\"Empty: No Elements presentin LL.\")\n", 52 | " return None\n", 53 | " else:\n", 54 | " while(temp_node):\n", 55 | " print(temp_node.data, end=' ')\n", 56 | " temp_node = temp_node.next\n", 57 | " print()\n", 58 | " def createLinkedListA(self, temp_list):\n", 59 | " for i in range(0, len(temp_list)):\n", 60 | " newNode = Node(temp_list[i])\n", 61 | " if self.head == None:\n", 62 | " self.head = newNode\n", 63 | " else:\n", 64 | " nextNode = self.head\n", 65 | " while nextNode.next != None:\n", 66 | " nextNode = nextNode.next\n", 67 | " nextNode.next = newNode\n", 68 | " def createLinkedListB(self,objA, temp_list):\n", 69 | " temp_nodeA = objA.head\n", 70 | " while objA.skip:\n", 71 | " temp_nodeA = temp_nodeA.next\n", 72 | " objA.skip -= 1\n", 73 | " \n", 74 | " for i in range(0, self.skip+1):\n", 75 | " newNode = Node(temp_list[i])\n", 76 | " if self.head == None:\n", 77 | " self.head = newNode\n", 78 | " else:\n", 79 | " nextNode = self.head\n", 80 | " while nextNode.next != None:\n", 81 | " nextNode = nextNode.next\n", 82 | " nextNode.next = newNode\n", 83 | " nextNode.next = temp_nodeA \n", 84 | " def getLength(self, objA):\n", 85 | " length_a = 0\n", 86 | " length_b = 0\n", 87 | " temp_nodeA = objA.head\n", 88 | " while temp_nodeA:\n", 89 | " length_a += 1\n", 90 | " temp_nodeA = temp_nodeA.next\n", 91 | " temp_nodeB = self.head\n", 92 | " while temp_nodeB:\n", 93 | " length_b += 1\n", 94 | " temp_nodeB = temp_nodeB.next\n", 95 | " return length_a, length_b\n", 96 | " def findCommonPoint(self, objA, diff):\n", 97 | " temp_nodeA = objA.head\n", 98 | " temp_nodeB = self.head\n", 99 | " while diff:\n", 100 | " temp_nodeB = temp_nodeB.next\n", 101 | " diff -= 1\n", 102 | " while temp_nodeB and temp_nodeA:\n", 103 | " if temp_nodeB == temp_nodeA:\n", 104 | " print(\"Intersection point of linked list is at:\", temp_nodeA.data)\n", 105 | " return None\n", 106 | " else:\n", 107 | " temp_nodeB = temp_nodeB.next\n", 108 | " temp_nodeA = temp_nodeA.next\n", 109 | " " 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": 8, 115 | "metadata": {}, 116 | "outputs": [], 117 | "source": [ 118 | "objA = LinkedList(2)\n", 119 | "\n", 120 | "objB = LinkedList(3)" 121 | ] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": 9, 126 | "metadata": {}, 127 | "outputs": [ 128 | { 129 | "name": "stdout", 130 | "output_type": "stream", 131 | "text": [ 132 | "4 1 8 4 5 \n", 133 | "5 0 1 8 4 5 \n", 134 | "Intersection point of linked list is at: 8\n" 135 | ] 136 | } 137 | ], 138 | "source": [ 139 | "objA.createLinkedListA([4, 1, 8, 4, 5])\n", 140 | "objA.printLL()\n", 141 | "objB.createLinkedListB(objA, [5, 0, 1, 8, 4, 5])\n", 142 | "objB.printLL()\n", 143 | "length_a, length_b = objB.getLength(objA)\n", 144 | "objB.findCommonPoint(objA, abs(length_a-length_b))" 145 | ] 146 | } 147 | ], 148 | "metadata": { 149 | "kernelspec": { 150 | "display_name": "Python 3", 151 | "language": "python", 152 | "name": "python3" 153 | }, 154 | "language_info": { 155 | "codemirror_mode": { 156 | "name": "ipython", 157 | "version": 3 158 | }, 159 | "file_extension": ".py", 160 | "mimetype": "text/x-python", 161 | "name": "python", 162 | "nbconvert_exporter": "python", 163 | "pygments_lexer": "ipython3", 164 | "version": "3.6.4" 165 | } 166 | }, 167 | "nbformat": 4, 168 | "nbformat_minor": 2 169 | } 170 | -------------------------------------------------------------------------------- /SinglyLinkedList.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 71, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "class Node:\n", 10 | " def __init__(self, value=None):\n", 11 | " '''\n", 12 | " Constructor of the class\n", 13 | " args:\n", 14 | " value(DataType:any) - value\n", 15 | " return None\n", 16 | " '''\n", 17 | " self.value = value\n", 18 | " self.next = None\n", 19 | "\n", 20 | "class SLinkedList:\n", 21 | " def __init__(self):\n", 22 | " '''\n", 23 | " Constructor of the class\n", 24 | " '''\n", 25 | " self.head = None\n", 26 | " \n", 27 | " def printLinkedList(self):\n", 28 | " '''\n", 29 | " It will print the entire Singly Linked List\n", 30 | " return None\n", 31 | " '''\n", 32 | " temp = self.head\n", 33 | " while temp !=None:\n", 34 | " print(temp.value, end = ' ')\n", 35 | " temp = temp.next\n", 36 | " print(\"\")\n", 37 | " def insertAtFirst(self, data):\n", 38 | " '''\n", 39 | " Inserting an Element at the beginning of the Singly Linked List\n", 40 | " \n", 41 | " args:\n", 42 | " data(DataType:any) - Value\n", 43 | " return None\n", 44 | " '''\n", 45 | " newNode = Node(data)\n", 46 | " if self.head == None:\n", 47 | " self.head = newNode\n", 48 | " else:\n", 49 | " newNode.next = self.head\n", 50 | " self.head = newNode\n", 51 | " \n", 52 | " def insertAtLast(self, data):\n", 53 | " '''\n", 54 | " Inserting an Element at last of the Singly Linked List\n", 55 | " \n", 56 | " args:\n", 57 | " data(DataType:any) - Value\n", 58 | " return None\n", 59 | " '''\n", 60 | " newNode = Node(data)\n", 61 | " if self.head == None:\n", 62 | " self.head = newNode\n", 63 | " else:\n", 64 | " nextNode = self.head\n", 65 | " while nextNode.next != None:\n", 66 | " nextNode = nextNode.next\n", 67 | " nextNode.next = newNode\n", 68 | " def removeFE(self):\n", 69 | " '''\n", 70 | " This function will remove first element from the Singly Linked List\n", 71 | " return None\n", 72 | " '''\n", 73 | " if self.head == None:\n", 74 | " print(\"No Elements in the Singly Linked List\")\n", 75 | " else:\n", 76 | " if self.head.next == None:\n", 77 | " self.head = None\n", 78 | " else:\n", 79 | " tempNode = self.head.next\n", 80 | " self.head = tempNode\n", 81 | " def removeLE(self):\n", 82 | " '''\n", 83 | " This function will remove first element from the Singly Linked List\n", 84 | " return None\n", 85 | " '''\n", 86 | " if self.head == None:\n", 87 | " print(\"No Elements in the Singly Linked List\")\n", 88 | " else:\n", 89 | " if self.head.next == None:\n", 90 | " self.head = None\n", 91 | " else:\n", 92 | " tempNode = self.head\n", 93 | " while tempNode.next != None:\n", 94 | " lastNode = tempNode\n", 95 | " tempNode = tempNode.next\n", 96 | " lastNode.next = None\n", 97 | " " 98 | ] 99 | }, 100 | { 101 | "cell_type": "code", 102 | "execution_count": 72, 103 | "metadata": {}, 104 | "outputs": [], 105 | "source": [ 106 | "list1 = SLinkedList()" 107 | ] 108 | }, 109 | { 110 | "cell_type": "code", 111 | "execution_count": 73, 112 | "metadata": {}, 113 | "outputs": [ 114 | { 115 | "name": "stdout", 116 | "output_type": "stream", 117 | "text": [ 118 | "No Elements in the Singly Linked List\n", 119 | "2 1 \n", 120 | "2 \n", 121 | "3 2 \n", 122 | "2 \n", 123 | "4 2 \n", 124 | "4 2 5 \n", 125 | "2 5 \n", 126 | "\n" 127 | ] 128 | } 129 | ], 130 | "source": [ 131 | "list1.removeFE()\n", 132 | "\n", 133 | "list1.insertAtFirst(1)\n", 134 | "list1.insertAtFirst(2)\n", 135 | "list1.printLinkedList()\n", 136 | "\n", 137 | "list1.removeLE()\n", 138 | "list1.printLinkedList()\n", 139 | "\n", 140 | "list1.insertAtFirst(3)\n", 141 | "list1.printLinkedList()\n", 142 | "\n", 143 | "list1.removeFE()\n", 144 | "list1.printLinkedList()\n", 145 | "\n", 146 | "list1.insertAtFirst(4)\n", 147 | "list1.printLinkedList()\n", 148 | "\n", 149 | "list1.insertAtLast(5)\n", 150 | "list1.printLinkedList()\n", 151 | "\n", 152 | "list1.removeFE()\n", 153 | "list1.printLinkedList()\n", 154 | "list1.removeFE()\n", 155 | "list1.removeFE()\n", 156 | "list1.printLinkedList()" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": null, 162 | "metadata": {}, 163 | "outputs": [], 164 | "source": [] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "execution_count": null, 169 | "metadata": {}, 170 | "outputs": [], 171 | "source": [] 172 | } 173 | ], 174 | "metadata": { 175 | "kernelspec": { 176 | "display_name": "Python 3", 177 | "language": "python", 178 | "name": "python3" 179 | }, 180 | "language_info": { 181 | "codemirror_mode": { 182 | "name": "ipython", 183 | "version": 3 184 | }, 185 | "file_extension": ".py", 186 | "mimetype": "text/x-python", 187 | "name": "python", 188 | "nbconvert_exporter": "python", 189 | "pygments_lexer": "ipython3", 190 | "version": "3.6.4" 191 | } 192 | }, 193 | "nbformat": 4, 194 | "nbformat_minor": 2 195 | } 196 | -------------------------------------------------------------------------------- /Tree-Traversal.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 71, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "class Node:\n", 10 | " def __init__(self, data):\n", 11 | " '''\n", 12 | " This is a Node class default constructor for all the parents nodes.\n", 13 | " '''\n", 14 | " self.left = None\n", 15 | " self.right = None\n", 16 | " self.data = data\n", 17 | " \n", 18 | " def insert(self, data):\n", 19 | " '''\n", 20 | " This func is used to insert element into to the binary tree.\n", 21 | " '''\n", 22 | " if self.data is None:\n", 23 | " self.data = data\n", 24 | " elif self.data > data:\n", 25 | " if self.left is None:\n", 26 | " self.left = Node(data)\n", 27 | " else:\n", 28 | " self.left.insert(data)\n", 29 | " elif self.data < data:\n", 30 | " if self.right is None:\n", 31 | " self.right = Node(data)\n", 32 | " else:\n", 33 | " self.right.insert(data)\n", 34 | " \n", 35 | " def findValue(self, lkpVal):\n", 36 | " '''\n", 37 | " This function is used to search element in the Tree;\n", 38 | " lkpVal: lookup Value\n", 39 | " return: element found or not\n", 40 | " '''\n", 41 | " if lkpVal < self.data:\n", 42 | " if self.left is None:\n", 43 | " return str(lkpVal)+\" is Not Found in the TREE\"\n", 44 | " return self.left.findValue(lkpVal)\n", 45 | " elif lkpVal > self.data:\n", 46 | " if self.right is None:\n", 47 | " return str(lkpVal)+\" is Not Found in the TREE\"\n", 48 | " return self.right.findValue(lkpVal)\n", 49 | " else:\n", 50 | " print(\"\\n\"+str(lkpVal)+\" is Found in the TREE\")\n", 51 | " \n", 52 | " def printPreorderTree(self):\n", 53 | " '''\n", 54 | " Print Binary Tree \n", 55 | " '''\n", 56 | " print(self.data, end=' ')\n", 57 | " if self.left:\n", 58 | " self.left.printPreorderTree()\n", 59 | " if self.right:\n", 60 | " self.right.printPreorderTree()\n", 61 | " def printInorderTree(self):\n", 62 | " '''\n", 63 | " Print Binary Tree \n", 64 | " '''\n", 65 | " if self.left:\n", 66 | " self.left.printInorderTree()\n", 67 | " print(self.data, end=' ')\n", 68 | " if self.right:\n", 69 | " self.right.printInorderTree()\n", 70 | " def printpostorderTree(self):\n", 71 | " '''\n", 72 | " Print Binary Tree \n", 73 | " '''\n", 74 | " if self.left:\n", 75 | " self.left.printpostorderTree()\n", 76 | " if self.right:\n", 77 | " self.right.printpostorderTree()\n", 78 | " print(self.data, end=' ')" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": 72, 84 | "metadata": {}, 85 | "outputs": [ 86 | { 87 | "ename": "AttributeError", 88 | "evalue": "'Node' object has no attribute 'printTree'", 89 | "output_type": "error", 90 | "traceback": [ 91 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 92 | "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", 93 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mroot\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mNode\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m10\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mroot\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mprintTree\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 94 | "\u001b[0;31mAttributeError\u001b[0m: 'Node' object has no attribute 'printTree'" 95 | ] 96 | } 97 | ], 98 | "source": [ 99 | "root = Node(10)\n", 100 | "root.printTree()" 101 | ] 102 | }, 103 | { 104 | "cell_type": "code", 105 | "execution_count": 73, 106 | "metadata": {}, 107 | "outputs": [ 108 | { 109 | "data": { 110 | "text/plain": [ 111 | "'14 is Not Found in the TREE'" 112 | ] 113 | }, 114 | "execution_count": 73, 115 | "metadata": {}, 116 | "output_type": "execute_result" 117 | } 118 | ], 119 | "source": [ 120 | "#insert into the B-Tree\n", 121 | "root.insert(8)\n", 122 | "root.insert(5)\n", 123 | "root.insert(4)\n", 124 | "root.insert(6)\n", 125 | "root.insert(12)\n", 126 | "root.insert(11)\n", 127 | "root.insert(13)\n", 128 | "#Find value in the Tree\n", 129 | "root.findValue(14) #Not Found" 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "execution_count": 76, 135 | "metadata": {}, 136 | "outputs": [ 137 | { 138 | "name": "stdout", 139 | "output_type": "stream", 140 | "text": [ 141 | "\n", 142 | "Pre-Order Traversal10 8 5 4 6 12 11 13 \n", 143 | "In-Order Traversal\n", 144 | "4 5 6 8 10 11 12 13 \n", 145 | "Post-Order Traversal\n", 146 | "4 6 5 8 11 13 12 10 " 147 | ] 148 | } 149 | ], 150 | "source": [ 151 | "# Tree Traversal\n", 152 | "print(\"\\nPre-Order Traversal: \", end='')\n", 153 | "root.printPreorderTree()\n", 154 | "print(\"\\nIn-Order Traversal: \", end = '')\n", 155 | "root.printInorderTree()\n", 156 | "print(\"\\nPost-Order Traversal: \", end = '')\n", 157 | "root.printpostorderTree()" 158 | ] 159 | }, 160 | { 161 | "cell_type": "code", 162 | "execution_count": null, 163 | "metadata": {}, 164 | "outputs": [], 165 | "source": [] 166 | }, 167 | { 168 | "cell_type": "code", 169 | "execution_count": null, 170 | "metadata": {}, 171 | "outputs": [], 172 | "source": [] 173 | } 174 | ], 175 | "metadata": { 176 | "kernelspec": { 177 | "display_name": "Python 3", 178 | "language": "python", 179 | "name": "python3" 180 | }, 181 | "language_info": { 182 | "codemirror_mode": { 183 | "name": "ipython", 184 | "version": 3 185 | }, 186 | "file_extension": ".py", 187 | "mimetype": "text/x-python", 188 | "name": "python", 189 | "nbconvert_exporter": "python", 190 | "pygments_lexer": "ipython3", 191 | "version": "3.6.4" 192 | } 193 | }, 194 | "nbformat": 4, 195 | "nbformat_minor": 2 196 | } 197 | --------------------------------------------------------------------------------