Advertisement
Guest User

Untitled

a guest
Feb 17th, 2020
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 30.48 KB | None | 0 0
  1. /*  Given a binary tree, return the inorder, preorder, postorder traversal of its nodes values
  2.  
  3. Input: [1,null,2,3]
  4.    1
  5.     \
  6.      2
  7.     /
  8.    3    */
  9.  
  10. //inorder - Output: [1,3,2]     order is (Left, Root, Right)
  11.  
  12. public void inorder(TreeNode root,List list) {
  13.   if(root == null) return;
  14.   inorder(root.left, list);
  15.   list.add(root.val);
  16.   inorder(root.right, list);
  17. }
  18.  
  19. public List<Integer> inorderTraversal(TreeNode root) { 
  20.   List<Integer> res = new ArrayList<>();
  21.   if (root==null) return res;
  22.  
  23.   Stack<TreeNode> stack = new Stack<>();
  24.   TreeNode curr = root;
  25.  
  26.   while(curr != null || !stack.isEmpty()){
  27.     while (curr!=null){
  28.         stack.push(curr);
  29.         curr=curr.left;
  30.     }
  31.     curr=stack.pop();
  32.     res.add(curr.val);
  33.     curr=curr.right;
  34.   }
  35.   return res;
  36. }
  37.  
  38. /**
  39.  
  40.         10           #1      #2     #3      #4      #5     
  41.        /  \         ------  ------  ------  ------  ------ 
  42.      11    18       | 15 |  |    |  |    |  |    |  |    | 
  43.     /  \            ------  ------  ------  ------  ------ 
  44.   15    12          | 11 |  | 12 |  |    |  |    |  |    | 
  45.                     ------  ------  ------  ------  ------ 
  46.                     | 10 |  | 10 |  |    |  | 18 |  | 18 | 
  47.                     ------  ------  ------  ------  ------ 
  48. #1 push root to stack
  49. then we traverse to left node, because left node is not null then we push the node into stack
  50. push 11 then repeat and push 15.
  51.  
  52. #2 -> because 15 doesnt have any nodes we pop 15 out and print it or push to list
  53. then we go to the right node of 11. node 11 doesn't have more node on the right
  54. so we pop 11 out and print it. Then we traverse to the right node.
  55. because the right node is not null then we add it to stack
  56.  
  57. #3 -> because theres no more child from 12 then we go to the root node which is 10
  58. theres no more left child of 10 so we pop it and print
  59.  
  60. #4 -> We push 18 into stack now because root doesnt have anymore child on the left.
  61.  
  62. #5 -> we check the left and there are no more child so we pop it out of the stack and print
  63.  
  64. result = [15, 11, 12, 10, 18]
  65.  
  66. */
  67.  
  68.  
  69. //PreOrder - Output: [1,2,3]    order is (Root, Left, Right)
  70.  
  71. public void preorder(TreeNode root, List list) {
  72.   if(root == null) {
  73.       return;
  74.   }
  75.   list.add(root.val);
  76.   preorder(root.left,list);
  77.   preorder(root.right, list);
  78. }
  79.  
  80. public List<Integer> preorderTraversal(TreeNode root) {
  81.   List<Integer> list = new ArrayList<>();
  82.   if(root == null) return list;
  83.   Stack<TreeNode> stack = new Stack<>();
  84.   stack.push(root);
  85.   while(!stack.isEmpty()) {
  86.     TreeNode current = stack.pop();
  87.     list.add(current.val);
  88.     if(current.right!=null) {
  89.        stack.push(current.right);
  90.     }
  91.     if(current.left!=null) {
  92.       stack.push(current.left);
  93.     }
  94.   }
  95.   return list;
  96. }
  97.  
  98. /**
  99.  
  100.         10           #1      #2     #3      #4      #5      #6      #7     
  101.        /  \         ------  ------  ------  ------  ------  ------  ------ 
  102.      11    18       |    |  |    |  |    |  |    |  | 15 |  |    |  |    | 
  103.     /  \            ------  ------  ------  ------  ------  ------  ------ 
  104.   15    12          |    |  |    |  | 11 |  |    |  | 12 |  | 12 |  | 12 | 
  105.                     ------  ------  ------  ------  ------  ------  ------ 
  106.                     | 10 |  |    |  | 18 |  | 18 |  | 18 |  | 18 |  | 18 | 
  107.                     ------  ------  ------  ------  ------  ------  ------ 
  108.  
  109. #1 -> add in root
  110. #2 -> enter loop and pop element out, can either print or add to list
  111. #3 -> after element has been popped out, check if element has child. If it does then add
  112. right child then leftroot has 2 child so add in right child of 18 then left child of 11
  113. #4 -> pop out 11 and check if it has children
  114. #5 -> 11 has children, so add in right (12) then left (15)
  115. #6 -> pop out 15, but has no child so we run through the loop again
  116. #7 -> pop out 12, but has no child so we run through the loop again
  117.  
  118. 18 is the last element, also no child so pop it, then print it
  119.  
  120. if all elements were added to a list, then traverse through the list and print
  121.  
  122. result = [10, 11, 15, 12, 18]
  123. */
  124.  
  125. //PostOrder - Output: [3,2,1]   order is (Left, Right, Root)
  126.  
  127. public void postOrder(TreeNode root, List list) {
  128.   if(root == null) return;
  129.   postOrder(root.left, list);
  130.   postOrder(root.right, list);
  131.   list.add(root.val);
  132. }
  133.  
  134. public List<Integer> postorderTraversal(TreeNode root) {
  135.   List<Integer> list = new ArrayList<>();
  136.   if(root == null) return list;
  137.   Stack<TreeNode> stack = new Stack<>();
  138.   stack.push(root);
  139.   while(!stack.isEmpty()) {
  140.     TreeNode curr = stack.pop();
  141.     list.add(0,curr.val);
  142.     if(curr.left!=null) {
  143.       stack.push(curr.left);
  144.     }
  145.     if(curr.right!=null) {
  146.        stack.push(curr.right);
  147.     }
  148.   }
  149.   return list;
  150. }
  151. /**
  152.  
  153.         10           #1      #2     #3      #4      #5      #6      #7      #8 
  154.        /  \         ------  ------  ------  ------  ------  ------  ------  ------
  155.      11    18       | 15 |  |    |  | 12  | |    |  |    |  |    |  |    |  |    |
  156.     /  \            ------  ------  ------  ------  ------  ------  ------  ------
  157.   15    12          | 11 |  | 11 |  | 11 |  | 11 |  | 11 |  |    |  | 18 |  |    |
  158.                     ------  ------  ------  ------  ------  ------  ------  ------
  159.                     | 10 |  | 10 |  | 10 |  | 10 |  | 10 |  | 10 |  | 10 |  | 10 |
  160.                     ------  ------  ------  ------  ------  ------  ------  ------
  161.  
  162. #1 -> push root into stack, set the pointer of root to point to the next left node.
  163. if left node (11) exists then add 11 to the stack
  164. check if next left node(15) is empty or not, because the node exists then again push 15
  165. into the stackcheck if next left node is empty, because it is empty check
  166. check the top element's child of the right tree using stack peek method,
  167. Or pop out the element and add it to array or print if no right child exists
  168.  
  169. #2 -> 15 has no more child node, so we pop out 15 then we check if 11 has any right child
  170. #3 -> 11 has a right child so we push 12 into stack and repeat #1
  171. #4 -> 12 has no more child so we pop 12 then check 11
  172. #5 -> 11 has no more child so we pop 11 out
  173. #6 -> check if 10 has a right child
  174. #7 -> 10 has a right child so we push the child into the stack
  175. #8 -> check if 18 has left child, because there is none, so we check the right child
  176. which is also none, pop 18 out of the stack
  177. #9 -> 10 has no more child so we pop it out of the stack and then print
  178.  
  179.  
  180. result = [15, 12, 11, 18, 10]
  181.  
  182. */
  183.  
  184. //Level order traversal
  185.  
  186. public void levelOrder (Node root) {
  187.     Queue<Node> q = new Queue<>();
  188.     q.add(root);
  189.  
  190.     while(!q.isEmpty()) {
  191.         Node temp = q.poll; //removes the element at the front
  192.         if(temp.left != null) {
  193.             q.add(temp.left);
  194.         }
  195.         if(temp.right != null) {
  196.             q.add(root.right);
  197.         }
  198.     }
  199. }
  200.  
  201. /*
  202. N-ary Tree Postorder Traversal
  203.  
  204. Given an n-ary tree, return the postorder traversal of its nodes values.
  205.  
  206.     1
  207.   / | \
  208.  3  2  4
  209. / \
  210. 5  6
  211.  
  212. Return its postorder traversal as: [5,6,3,2,4,1].
  213.  
  214. post order is left, right then root
  215. */
  216.  
  217. public List<Integer> postorder(Node root) {
  218.     List<Integer> ls = new ArrayList<>();
  219.     if(root == null) {
  220.         return ls;
  221.     }
  222.    
  223.     for(Node child: root.children) {   //add all the children in first
  224.         ls.addAll(postorder(child));
  225.     }
  226.     ls.add(root.val);   //once all children is added, then you add the root
  227.     return ls;
  228. }
  229.  
  230. /*
  231. Given an n-ary tree, return the preorder traversal of its nodes' values.
  232.  
  233. Return its preorder traversal as: [1,3,5,6,2,4].
  234.  
  235. preorder is root, then left, then right  */
  236.  
  237. public List<Integer> preorder(Node root) {
  238.     List<Integer> ls = new ArrayList<>();
  239.     if(root == null) {
  240.         return ls;
  241.     }
  242.     ls.add(root.val);       //add in root first
  243.     for(Node child: root.children) {
  244.         ls.addAll(preorder(child));   //then add in the children
  245.     }
  246.     return ls;
  247.    
  248. }
  249.  
  250. //calculating height of a binary tree
  251.  
  252. int height(Node root) {
  253.     if(root == null) {
  254.         return -1
  255.     }
  256.     return 1 + Math.max(height(root.left), height(root.right))
  257. }
  258.  
  259. /*
  260. calculating size of a tree(number of nodes)
  261. traverse through tree using any tree traversal methods andadd the item in a data structure
  262. calculate size from arraylist and return number
  263. */
  264. class solution {
  265.    
  266.     public static void inOrder(Node root,List list) {
  267.         if(root == null) {
  268.             return;
  269.         }
  270.         inOrder(root.left, list);
  271.         list.add(root);
  272.         inOrder(root.right, list);
  273.     }
  274.  
  275.     public static int count(Node root) {
  276.         List<Integer> ls = new ArrayList<>();
  277.         inOrder(root, ls);
  278.         int count = ls.size();
  279.         return count
  280.     }
  281. }
  282.  
  283. or
  284.  
  285. //recursive method will recursively count all nodes on left and right.
  286. public static int count(Node root) {
  287.     if(root == null) {
  288.         return 0;
  289.     }
  290.     return 1 + count(root.left) + count(root.right);
  291. }
  292.  
  293. //check if binary tree is BST
  294.  
  295.  public boolean isBST(TreeNode node, long lower_limit, long upper_limit) {
  296.     if (node == null) {
  297.         return true;
  298.     }
  299.     if (node.val <= lower_limit || upper_limit <= node.val) {
  300.         return false;
  301.     }
  302.     return isBST(node.left, lower_limit, node.val) && isBST(node.right, node.val, upper_limit);
  303. }
  304.  
  305. public boolean isValidBST(TreeNode root) {
  306.     return isBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
  307.    
  308. }
  309.  
  310. //binary search tree search and insert
  311.  
  312. public Node search(Node current, int val) {
  313.     if(current == null) {
  314.         return current;
  315.     }
  316.     if(current.val > val) { //if current value is greater than the value, check left
  317.         return search(current.left, val);
  318.     } //otherwise check right
  319.     return search(current.right, val);
  320.  
  321. public Node addNode(Node current, int val) {
  322.     if(current == null) {
  323.         return new Node(val);   //if the root of tree does not exist, add a new node
  324.     }
  325.     if(val < current.val) { //if value is less than root or node, then it must go to left
  326.         current.left = addNode(current.left, val);
  327.     } else if(val > current.val) { //if value is more than root or node, then it must go to right
  328.         current.right = addNode(current.right, val);
  329.     } else {
  330.         return current;
  331.     }
  332.     return current;
  333. }
  334.  
  335. /*
  336. construct binary search tree from its given level order traversal
  337. */
  338. // function to get a new node
  339. public static Node getNode(int data) {
  340.     // Allocate memory
  341.     Node newNode = new Node();
  342.      
  343.     // put in the data  
  344.     newNode.data = data;
  345.     newNode.left = newNode.right = null;  //left and right node are null
  346.     return newNode;
  347. }
  348. public Node LevelOrder(Node root , int data)  
  349. {
  350.     if(root == null)
  351.     {  
  352.         root = getNode(data);
  353.         return root;
  354.     }
  355.     if(data <= root.data)
  356.         root.left = LevelOrder(root.left, data);
  357.     else
  358.         root.right = LevelOrder(root.right, data);
  359.     return root;      
  360. }
  361.  
  362. /*
  363. Given a Binary Search Tree (BST) with the root node root,
  364. return the minimum difference between the values of any two different nodes in the tree.
  365.  
  366. Input: root = [4,2,6,1,3,null,null]
  367. Output: 1
  368. Explanation:
  369. Note that root is a TreeNode object, not an array.
  370.  
  371. The given tree [4,2,6,1,3,null,null] is represented by the following diagram:
  372.  
  373.           4
  374.         /   \
  375.       2      6
  376.      / \    
  377.     1   3  
  378.  
  379. while the minimum difference in this tree is 1, it occurs between node 1 and node 2,
  380. also between node 3 and node 2.
  381. */
  382.  
  383. Integer prev;
  384. int minDiff = Integer.MAX_VALUE;
  385.  
  386. public int minDiffInBST(TreeNode root) {
  387.     inorder(root);
  388.     return minDiff;
  389. }
  390.  
  391. private void inorder(TreeNode root) {
  392.     if (root == null)
  393.         return;
  394.     inorder(root.left);
  395.     if (prev != null)
  396.         minDiff = Math.min(minDiff, Math.abs(root.val - prev));
  397.     prev = root.val;
  398.     inorder(root.right);
  399. }
  400.  
  401. /*
  402.  
  403. Lowest common Ancestor
  404. Binary tree
  405. Binary Search Tree
  406.  
  407.           4
  408.         /   \
  409.       2      6
  410.      / \    
  411.     1   3
  412.  
  413. */
  414.  
  415. public Node LCABT(Node root, Node n1, Node n2) {
  416.     if(root == null) {
  417.         return null;
  418.     }
  419.     if(root == n1 || root == n2) {
  420.         return root;
  421.     }
  422.     Node left = LCABT(root.left, n1, n2);
  423.     Node right = LCABT(root.right, n1, n2);
  424.  
  425.     if(left != null && right != null) {
  426.         //left value or right value is returning not null so the value is near by
  427.         return root;
  428.     }
  429.     if(left == null && right == null) {
  430.         //left value and right value does not exist
  431.         return null;
  432.     }
  433.     return left != null? left : right;
  434.     //check left tree if value exist, traverse left, otherwise traverse right
  435. }
  436.  
  437. public Node LCABsearchT(Node root, Node n1, Node n2) {
  438.     if(root == null) {
  439.         return null;
  440.     }
  441.     //if n1 and n2 is small than root, then traverse to left
  442.     if(root.val > n1 && root.vale > n2) {
  443.         return LCABsearchT(root.left, n1, n2);
  444.     }
  445.     //if n1 and n2 is bigger than root, then traverse to right
  446.     if(root.val < n1 && root.val < n2) {
  447.         return LCABsearchT(root.right, n1, n2);
  448.     }
  449.     return root;
  450. }
  451.  
  452. /*
  453. Test if binary tree is symmetric (mirror of itself)
  454.  
  455. need to check and compare left subtree and right subtree along with its children.
  456. recursively check left and right and right and left child nodes
  457. */
  458.  
  459. public boolean isSymmetric(TreeNode root) {
  460.     return root == null || check(leftTree, rightTree);
  461. }
  462.  
  463. public boolean check(TreeNode leftTree, TreeNode rightTree) {
  464.     if(leftTree == null && rightTree == null) {
  465.         return true;
  466.     }
  467.     if(leftTree != null && rightTree != null) {
  468.         return check(leftTree.right, rightTree.left) &&
  469.             check(leftTree.left, rightTree.right);
  470.     }
  471.     return false;
  472. }
  473.  
  474. //LINKEDLIST
  475.  
  476. public ListNode reverseList(ListNode head) {
  477.     ListNode curr = head;
  478.     ListNode prev = null;
  479.    
  480.     if(head == null) return prev;
  481.    
  482.     while(curr != null) {
  483.         ListNode temp = curr.next; //pointer to point to next value
  484.         curr.next = prev; //next value is point to previous value
  485.         prev = curr; //previous is set to current number
  486.         curr = temp; //current is set to next value
  487.     }
  488.    
  489.     return prev;
  490. }
  491.  
  492. /*
  493. Merge two sorted linked lists and return it as a new list.
  494. The new list should be made by splicing together the nodes of the first two lists.
  495.  
  496. Input: 1->2->4, 1->3->4
  497. Output: 1->1->2->3->4->4
  498. */
  499.  
  500. public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  501.     ListNode dummy = new ListNode(0);
  502.     ListNode head = dummy;
  503.    
  504.     while(l1 != null && l2 != null) {
  505.         //if l1 less than l2
  506.         //add l1 to dummy and traverse l1
  507.         //else add l2 to dummy and traverel2
  508.         if(l1.val < l2.val) {
  509.             head.next = l1;
  510.             l1 = l1.next;
  511.         } else {
  512.             head.next = l2;
  513.             l2 = l2.next;
  514.         }
  515.         head = head.next;
  516.     }
  517.     //most likely some sort of remainder in either list so we need to take account to that
  518.     if(l1!=null) {
  519.         head.next = l1;
  520.     }
  521.     if(l2!=null) {
  522.         head.next = l2;
  523.     }
  524.     return dummy.next;
  525. }
  526.  
  527. /*
  528. Given a non-empty, singly linked list with head node head, return a middle node of linked list.
  529. If there are two middle nodes, return the second middle node.
  530.  
  531. Input: [1,2,3,4,5]
  532. Output: Node 3 from this list (Serialization: [3,4,5])
  533. The returned node has value 3.  (The judge's serialization of this node is [3,4,5]).
  534. Note that we returned a ListNode object ans, such that:
  535. ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
  536.  
  537. Input: [1,2,3,4,5,6]
  538. Output: Node 4 from this list (Serialization: [4,5,6])
  539. Since the list has two middle nodes with values 3 and 4, we return the second one.
  540.  
  541. The number of nodes in the given list will be between 1 and 100.
  542. */
  543.  
  544. public ListNode middleNode(ListNode head) {
  545.     ListNode l[] = new ListNode[100];
  546.     int count = 0;
  547.    
  548.     while(head != null) {
  549.         l[count++] = head; //count the amount of elements in linkedlist
  550.         head = head.next; //traverse
  551.     }
  552.     return l[count/2];
  553. }
  554.  
  555. /*
  556. Given a sorted linked list, delete all duplicates such that each element appear only once.
  557.  
  558. Input: 1->1->2
  559. Output: 1->2
  560.  
  561. Input: 1->1->2->3->3
  562. Output: 1->2->3
  563. */
  564.  
  565. public ListNode deleteDuplicates(ListNode head) {
  566.     ListNode curr = head;
  567.    
  568.     while(curr != null && curr.next != null) {
  569.         if(curr.val == curr.next.val) {
  570.             curr.next = curr.next.next;
  571.         } else {
  572.             curr = curr.next;
  573.         }
  574.     }
  575.     return head;
  576. }
  577.  
  578. /*
  579. Given a singly linked list, determine if it is a palindrome.
  580.  
  581. Input: 1->2
  582. Output: false
  583.  
  584. Input: 1->2->2->1
  585. Output: true
  586. */
  587.  
  588. class Solution {
  589.     public ListNode reverse(ListNode head) {
  590.         ListNode prev = null;
  591.         while(head != null) {
  592.             ListNode temp = head.next;
  593.             head.next = prev;
  594.             prev = head;
  595.             head = temp;
  596.         }
  597.         return prev;
  598.     }
  599.    
  600.     public boolean isPalindrome(ListNode head) {
  601.         //have 2 pointers, one fast and one slow
  602.         //slow pointer should reach to halfway of list
  603.         //fast will reach to end + null
  604.         //once fast is equal to null then we take slow and reverse it
  605.         //set fast pointer back to head and traverse fast and slow
  606.         //while slow doesnt hit null, if fast and slow is same then it is palindrome
  607.        
  608.         ListNode slow = head;
  609.         ListNode fast = head;
  610.        
  611.         while(fast != null && fast.next != null) {
  612.             slow = slow.next;
  613.             fast = fast.next.next;
  614.         }
  615.        
  616.         slow = reverse(slow); //reverse one half of the linked list
  617.         fast = head; //set fast to point to head (first in list)
  618.         while(slow != null) {
  619.             if(fast.val != slow.val) {
  620.                 return false;
  621.             }
  622.             slow = slow.next;
  623.             fast = fast.next;
  624.         }
  625.         return true;
  626.     }
  627. }
  628.  
  629. /*
  630. Sort a linked list in O(n log n) time using constant space complexity.
  631.  
  632. Input: 4->2->1->3
  633. Output: 1->2->3->4
  634.  
  635. Input: -1->5->3->4->0
  636. Output: -1->0->3->4->5
  637.  
  638. idea behind is merge sort
  639. */
  640.  
  641. public ListNode merge(ListNode l1, ListNode l2) {
  642.     ListNode temp = new ListNode(0);
  643.     ListNode curr = temp;
  644.    
  645.     while(l1 != null && l2 != null) {
  646.         if(l1.val < l2.val) {
  647.             curr.next = l1;
  648.             l1 = l1.next;
  649.         } else {
  650.             curr.next = l2;
  651.             l2 = l2.next;
  652.         }
  653.     }
  654.     if(l1 != null) {
  655.         curr.next = l1;
  656.         l1 = l1.next;
  657.     }
  658.     if(l2 != null) {
  659.         curr.next = l2;
  660.         l2 = l2.next;
  661.     }
  662.     return temp.next;
  663. }
  664.  
  665. public ListNode sortList(ListNode head) {
  666.     if(head == null || head.next == null) {
  667.         return head;
  668.     }
  669.     ListNode temp = head;
  670.     ListNode slow = head;
  671.     ListNode fast = head;
  672.    
  673.     //idea is to have 2 pointers and traverse
  674.     //split linkedlist into 2 lists
  675.     //perform mergesort on linkedlist
  676.    
  677.     //head of list one is head, tail is temp
  678.     //head of list two is slow, tail is fast
  679.     while(fast != null && fast.next != null) {
  680.         temp = slow; //temp will eventually be the tail of a linked list
  681.         slow = slow.next; //slow will eventually be the head of a linkedlist
  682.         fast = fast.next.next; //fast will eventually be tail of slow list
  683.     }
  684.     temp.next = null; //end of list one is now null
  685.     ListNode leftSide = sortList(head); //split left linkedlist
  686.     ListNode rightSide = sortList(slow); //split into right
  687.     return merge(leftSide, rightSide);
  688. }
  689.  
  690. /*
  691. Merge k sorted linked lists and return it as one sorted list.
  692. Input:
  693. [
  694.   1->4->5,
  695.   1->3->4,
  696.   2->6
  697. ]
  698. Output: 1->1->2->3->4->4->5->6
  699.  
  700. use a minheap, minheap implementation is using PQ and will sort itself.
  701. */
  702.  
  703. class Solution {
  704.     public ListNode mergeKLists(ListNode[] lists) {
  705.         PriorityQueue<Integer> minHeap = new PriorityQueue<>();
  706.        
  707.         //for every node in lists
  708.         for(ListNode head : lists) {
  709.             // while the list is not empty
  710.             while(head != null) {
  711.                 minHeap.add(head.val);
  712.                 head = head.next; //traverse list
  713.             }
  714.         }
  715.         ListNode dummy = new ListNode(-1);
  716.         ListNode head = dummy;
  717.         while(!minHeap.isEmpty()) {
  718.             head.next = new ListNode(minHeap.remove());
  719.             head = head.next;
  720.         }  
  721.     }
  722.     return dummy.next;
  723. }
  724.  
  725. /*
  726. Given a singly linked list, group all odd nodes together followed by the even nodes.
  727. Please note here we are talking about the node number and not the value in the nodes.
  728.  
  729. Input: 1->2->3->4->5->NULL
  730. Output: 1->3->5->2->4->NULL
  731. Example 2:
  732.  
  733. Input: 2->1->3->5->6->4->7->NULL
  734. Output: 2->3->6->7->1->5->4->NULL
  735. */
  736.  
  737. class Solution {
  738.     public ListNode oddEvenList(ListNode head) {
  739.         if(head == null) {
  740.             return null;
  741.         }
  742.        
  743.         //list will be odd first then even to the end of list
  744.         //problem is split odd and even nodes, not the value it holds
  745.        
  746.         ListNode odd = head; //first index of list is odd
  747.         ListNode even = head.next;//second index of list is even, point even to value after head
  748.         ListNode evenHead = even; //head of even number
  749.        
  750.         while(even != null && even.next != null) {
  751.             odd.next = even.next; //after all odd number, then even is next
  752.             odd = odd.next;
  753.             even.next = odd.next;
  754.             even = even.next;
  755.         }
  756.         odd.next = evenHead;
  757.         return head;
  758.     }
  759. }
  760.  
  761. /*
  762. You are given two non-empty linked lists representing two non-negative integers.
  763. The digits are stored in reverse order and each of their nodes contain a single digit.
  764. Add the two numbers and return it as a linked list.
  765.  
  766. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
  767. Output: 7 -> 0 -> 8
  768. Explanation: 342 + 465 = 807.
  769. */
  770.  
  771. public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
  772.     //create new linkedlist to store result
  773.     //traverse linkedlist
  774.     //need variable to hold carry value
  775.    
  776.     ListNode dummy = new ListNode(0);
  777.     ListNode l3 = dummy;
  778.     int carry = 0;
  779.     while(l1 != null && l2 != null) {
  780.         int l1_val = (l1 != null)? l1.val : 0;
  781.         //if one of the node is missing a value, fill it with 0
  782.         int l2_val = (l2 != null)? l2.val : 0;
  783.         //if one of the node is missing a value, fill it with 0
  784.         int current_sum = l1.val + l2.val;
  785.         carry = current_sum / 10; //calculate the carry
  786.         int last_digit = current_sum % 10; //calculate the digit that is actually wanted
  787.        
  788.         // 2+5 = 7, carry = 0, digit = 7
  789.         // 4+6 = 10 carry = 1, digit = 0
  790.        
  791.         ListNode new_node = new ListNode(last_digit);
  792.         l3.next = new_node;
  793.        
  794.         if(l1 != null) {
  795.             l1 = l1.next;
  796.         }
  797.         if(l2 != null) {
  798.             l2 = l2.next;
  799.         }
  800.         l3 = l3.next;
  801.     }
  802.     if(carry > 0) {
  803.         ListNode new_node = new ListNode(carry);
  804.         l3.next = new_node.next;
  805.         l3 = l3.next;
  806.     }
  807.     return dummy.next;
  808. }
  809.  
  810. /*
  811. ARRAY SORTING
  812.  
  813. Given an array with n objects colored red, white or blue,
  814. sort them in-place so that objects of the same color are adjacent,
  815. with the colors in the order red, white and blue.
  816. use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
  817. Note: You are not suppose to use the library's sort function for this problem.
  818.  
  819. Input: [2,0,2,1,1,0]
  820. Output: [0,0,1,1,2,2]
  821. */
  822.  
  823. class Solution {
  824.     public void sortColors(int[] nums) {
  825.         int count0 = 0;
  826.         int count1 = 0;
  827.         int count2 = 0;
  828.        
  829.         for(int i = 0; i < nums.length;i++) {
  830.             if(nums[i] == 0) {
  831.                 count0++;
  832.             }
  833.             if(nums[i] == 1) {
  834.                 count1++;
  835.             }
  836.             if(nums[i] == 2) {
  837.                 count2++;
  838.             }
  839.         }
  840.        
  841.         for(int i = 0; i < nums.length; i++) {
  842.             if(i < count0) {
  843.                 nums[i] = 0;
  844.             } else if (i < count0 + count1) {
  845.                 nums[i] = 1;
  846.             } else {
  847.                 nums[i] = 2;
  848.             }
  849.         }
  850.     }
  851. }
  852.  
  853. /*
  854. Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
  855.  
  856. The number of elements initialized in nums1 and nums2 are m and n respectively.
  857. You may assume that nums1 has enough space (size that is greater or equal to m + n)
  858. to hold additional elements from nums2.
  859.  
  860. Input:
  861. nums1 = [1,2,3,0,0,0], m = 3
  862. nums2 = [2,5,6],       n = 3
  863.  
  864. Output: [1,2,2,3,5,6]
  865. */
  866.  
  867. public void merge(int[] nums1, int m, int[] nums2, int n) {
  868.     int count = m + n -1;
  869.     --m;
  870.     --n;
  871.     while(m >= 0 && n >= 0) {
  872.         if(nums1[m] > nums2[n]) {  //compare element from both array
  873.             nums1[count--] = nums1[m--];
  874.             //if element in nums1 is bigger, move it to the back of array
  875.         } else {
  876.             nums1[count--] = nums2[n--];
  877.             //if element in nums2 is bigger, move nums2 element to nums1 at the back
  878.         }
  879.     }
  880.     while (n >= 0) {
  881.         nums1[count--] = nums2[n--];
  882.     }
  883. }
  884.  
  885. /*
  886. Say you have an array for which the ith element is the price of a given stock on day i.
  887. If you were only permitted to complete at most one transaction
  888. (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit
  889. Note that you cannot sell a stock before you buy one.
  890.  
  891. Input: [7,1,5,3,6,4]
  892. Output: 5
  893. Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
  894.              Not 7-1 = 6, as selling price needs to be larger than buying price.
  895.  
  896. Input: [7,6,4,3,1]
  897. Output: 0
  898. Explanation: In this case, no transaction is done, i.e. max profit = 0.
  899. */
  900.  
  901. class Solution {
  902.     public int maxProfit(int[] prices) {
  903.         if(prices.length == 0) {
  904.             return 0;
  905.         }
  906.         int buy = prices[0]; // set buy price to the first element
  907.         int profit = 0 ;
  908.         for(int i = 1; i < prices.length; i++) { //for each stock price
  909.             if((prices[i] - buy) > 0) {
  910.                 //if each stock price minus that you bought is greater than 0
  911.                 profit = Math.max(prices[i] - buy, profit);
  912.                 //profit will be the comparison of the 2 profits
  913.                 //profit is the comparison of possible current profit vs the previous profits.
  914.             } else {
  915.                 buy = prices[i];
  916.             }
  917.         }
  918.         return profit;
  919.     }
  920. }
  921.  
  922. /*
  923. Say you have an array for which the ith element is the price of a given stock on day i.
  924. Design an algorithm to find the maximum profit. You may complete as many transactions as you like
  925. (i.e., buy one and sell one share of the stock multiple times).
  926. Note: You may not engage in multiple transactions at the same time
  927. (i.e., you must sell the stock before you buy again).
  928.  
  929. Input: [7,1,5,3,6,4]
  930. Output: 7
  931. Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
  932.              Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
  933.  
  934. Input: [1,2,3,4,5]
  935. Output: 4
  936. Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
  937.              Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
  938.              engaging multiple transactions at the same time. You must sell before buying again
  939.  
  940. Input: [7,6,4,3,1]
  941. Output: 0
  942. Explanation: In this case, no transaction is done, i.e. max profit = 0.
  943. */
  944.  
  945. class Solution {
  946.     public int maxProfit(int[] prices) {
  947.         int profit = 0;
  948.         //if a[i] < a[i+1] then the step would be to buy then sell
  949.         //if a[i+1] is smaller then you traverse      
  950.         for(int i = 0; i < prices.length -1; i++) {          
  951.            if(prices[i] < prices[i+1]) {
  952.                profit += prices[i+1] - prices[i];    
  953.             }  
  954.         }
  955.         return profit;
  956.     }
  957. }
  958.  
  959. /*
  960. Given an integer array nums, find the contiguous subarray (containing at least one number)
  961. which has the largest sum and return its sum.
  962.  
  963. Input: [-2,1,-3,4,-1,2,1,-5,4],
  964. Output: 6
  965. Explanation: [4,-1,2,1] has the largest sum = 6.
  966. */
  967.  
  968. class Solution {
  969.     public int maxSubArray(int[] nums) {
  970.         int maxSum = Integer.MIN_VALUE;
  971.         int tempSum = 0;
  972.        
  973.         for(int i = 0; i < nums.length; i++) { // go through array
  974.             tempSum = tempSum + nums[i]; //keep adding number
  975.             if(maxSum < tempSum) {
  976.                 maxSum = tempSum;
  977.             }
  978.             if(tempSum < 0) {
  979.                 tempSum = 0;
  980.             }
  981.         }
  982.         return maxSum;
  983.     }
  984. }
  985.  
  986.  
  987. /*
  988. Find the kth largest element in an unsorted array.
  989. Note that it is the kth largest element in the sorted order, not the kth distinct element.
  990.  
  991. Input: [3,2,1,5,6,4] and k = 2
  992. Output: 5
  993.  
  994. Input: [3,2,3,1,2,4,5,5,6] and k = 4
  995. Output: 4
  996. */
  997.  
  998. public int findKthLargest(int[] nums, int k) {
  999.     PriorityQueue<Integer> minHeap = new PriorityQueue<>();
  1000.     for(int i : nums) {
  1001.         minHeap.add(i); //go through array and add element to minHeap
  1002.         if(minHeap.size() > k) {
  1003.             minHeap.remove(); //it will remove the smallest element in minheap
  1004.         }
  1005.     }
  1006.     return minHeap.remove();
  1007. }
  1008.  
  1009. STRINGS
  1010.  
  1011. /*
  1012. Reverse string by word
  1013. */
  1014.  
  1015. public String reverseWord(String input) {
  1016.     String reverse = "";
  1017.     String wordSplit[] = input.split(" "); //assume word is separated by space
  1018.     for(int i = wordSplit.length -1; i > -1; i--) {
  1019.         reverse = reverse + wordSplit[i] + " ";
  1020.     }
  1021.     return reverse;
  1022. }
  1023. //original: I love java programming
  1024. //reversed: programming java love I
  1025.  
  1026. /*
  1027. Reverse string by character
  1028. */
  1029.  
  1030. public String reverseCharWord(String input) {
  1031.     String reverse = "";
  1032.     String wordSplit = input.split(" "); //assume word is separated by space
  1033.     for(int i = input.length - 1; i < input.length -1; i--) {
  1034.         reverse = reverse + input.charAt(i);
  1035.     }
  1036.     return reverse;
  1037. }
  1038. //original: I love java programming
  1039. //reversed: gnimmargorp avaj evol I
  1040.  
  1041. public static HashSet<String> getAllPermutations(String str) {
  1042.     HashSet<String> permutations = new HashSet<>();
  1043.  
  1044.     if(str == null || str.length == 0) {
  1045.         permutations.add("");
  1046.         return permutations;
  1047.     }
  1048.  
  1049.     char first = str.substring(0); //first character is stored in variable
  1050.     String remainingString = str.substring(1); //the rest of the string minus first character
  1051.     //stored in remainingString variable
  1052.     HashSet<String> words = getAllPermutations(remainingString);
  1053.     for(String word : words) {
  1054.         for(int i = 0; i < word.length(); i++) {
  1055.             String prefix = word.substring(0, i);
  1056.             String suffix = word.substring(i);
  1057.             permutations.add(prefix + first + suffix);
  1058.         }
  1059.     }
  1060.     return permutations;
  1061. }
  1062.  
  1063. /*
  1064. Given two strings s and t , write a function to determine if t is an anagram of s.
  1065.  
  1066. Example 1:
  1067.  
  1068. Input: s = "anagram", t = "nagaram"
  1069. Output: true
  1070. Example 2:
  1071.  
  1072. Input: s = "rat", t = "car"
  1073. Output: false
  1074. */
  1075.  
  1076. public boolean isAnagram(String s, String t) {
  1077.     if(s.length() != t.length()) {
  1078.         return false;
  1079.     } //check length, if length is not the same, then its not anagram
  1080.     char[] c1 = s.toCharArray(); //convert to character array
  1081.     char[] c2 = t.toCharArray(); //convert to character array
  1082.     Arrays.sort(c1); //sort character
  1083.     Arrays.sort(c2); //sort character
  1084.     String s1 = new String(c1); //create new string from sorted characters
  1085.     String s2 = new String(c2); //create new string from sorted characters
  1086.     if(s1.equals(s2)) { //if string1 is same as string2 then its anagram
  1087.         return true;
  1088.     }
  1089.         return false;
  1090. }
  1091.  
  1092. /*
  1093. Given an array of strings, group anagrams together.
  1094.  
  1095. Example:
  1096.  
  1097. Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
  1098. Output:            
  1099. [                           example where the
  1100.   ["ate","eat","tea"],              key  <-> value
  1101.   ["nat","tan"],                    aet       list[ate, eat, tea]
  1102.   ["bat"]
  1103. ]
  1104. */
  1105.  
  1106. //the anagrams all look alike when its sorted
  1107. //sort the word then some how group it, the sorted key word will be the key with a list of values
  1108. //using a map we can use the sorted word as a key
  1109. //value would be the unsorted word.
  1110. public List<List<String>> groupAnagrams(String[] strs) {
  1111.     List<List<String>> anagramGroup = new ArrayList<>();
  1112.     HashMap<String, List<String>> map = new HashMap();
  1113.  
  1114.     for(String current : strs) {
  1115.         char[] characters = current.toCharArray();
  1116.         Arrays.sort(characters); //sort the current word
  1117.         String sorted = new String(chracters); //sorted word will become Key for map usage
  1118.  
  1119.         if(!map.containsKey(sorted)) { //if map does not contain key
  1120.             map.put(sorted, new ArrayList()); //add in the with a new arraylist
  1121.         }                       //MAP<KEY, LIST[,,,,]>
  1122.         map.get(sorted).add(current); //get the key and add current strings to list
  1123.     }
  1124.     anagramGroup.addAll(map.values()); //add all map values into list
  1125.     return anagramGroup;
  1126. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement