diff --git a/.mergify.yml b/.mergify.yml deleted file mode 100644 index e1ddd1945..000000000 --- a/.mergify.yml +++ /dev/null @@ -1,14 +0,0 @@ -pull_request_rules: - - name: assign PRs with Python files modified to jd - conditions: - - files~=\.java$ - actions: - assign: - add_users: - - kunal-kushwaha - - name: ask to resolve conflict - conditions: - - conflict - actions: - comment: - message: This pull request is now in conflicts. Could you fix it @{{author}}? 🙏 diff --git a/README.md b/README.md index e9bb09119..5632563e2 100644 --- a/README.md +++ b/README.md @@ -1,58 +1,5 @@ -# 🔥DSA-Bootcamp-Java - -![DSA-Bootcamp-Java](https://socialify.git.ci/kunal-kushwaha/DSA-Bootcamp-Java/image?description=1&font=Inter&language=1&owner=1&pattern=Charlie%20Brown&theme=Dark) - -- ▶ Subscribe to our channel - -- 🧑‍💻 Syllabus and website - -- 📂 Complete Playlist - -- ✍️ Assignments (Solutions can be found on LeetCode itself) - -- 🏆 Competitive Programming Resources - - -## Connect with me - - -   - - -   - - -   - - -   - - - - -## Join Community Classroom Groups - - -   - - - -   - - -   - - -   - - -   - - - - - -## Thanks to all the contributors ❤️ - - - +# DSA + Interview preparation bootcamp +- Subscribe to the [YouTube channel](https://www.youtube.com/KunalKushwaha?sub_confirmation=1) +- [Lectures](https://www.youtube.com/playlist?list=PL9gnSGHSqcnr_DxHsP7AW9ftq0AtAyYqJ) +- [Course website](https://www.techwithkunal.com/courses/dsa) +- [Assignments](https://github.com/kunal-kushwaha/DSA-Bootcamp-Java/tree/main/assignments) (solutions can be found on LeetCode) diff --git a/SYLLABUS.md b/SYLLABUS.md new file mode 100644 index 000000000..e9c72d5f2 --- /dev/null +++ b/SYLLABUS.md @@ -0,0 +1,205 @@ +- [Complete Git & GitHub Course](https://youtu.be/apGV9Kg7ics) +- [Introduction to Programming](https://youtu.be/wn49bJOYAZM) + - [Types of languages](https://youtu.be/wn49bJOYAZM?t=171) + - [Memory management](https://youtu.be/wn49bJOYAZM?t=1488) +- [Flow of the program](https://youtu.be/lhELGQAV4gg) + - [Flowcharts](https://youtu.be/lhELGQAV4gg) + - [Pseudocode](https://youtu.be/lhELGQAV4gg?t=715) +- [Introduction to Java](https://youtu.be/4EP8YzcN0hQ) + - [Introduction](https://youtu.be/4EP8YzcN0hQ) + - [How it works](https://youtu.be/4EP8YzcN0hQ?t=93) + - [Setup Installation](https://youtu.be/4EP8YzcN0hQ?t=1486) + - [Input and Output in Java](https://youtu.be/TAtrPoaJ7gc) + - [Conditionals & Loops in Java](https://youtu.be/ldYLYRNaucM?t=88) + - [if-else](https://youtu.be/ldYLYRNaucM?t=88) + - [loops](https://youtu.be/ldYLYRNaucM?t=440) + - [Switch statements](https://youtu.be/mA23x39DjbI) + - [Data-types](https://youtu.be/TAtrPoaJ7gc?t=2800) + - [Coding best practices](https://youtu.be/waGfV-IoOt8) +- [Functions](https://youtu.be/vvanI8NRlSI) + - [Introduction](https://youtu.be/vvanI8NRlSI) + - [Scoping in Java](https://youtu.be/vvanI8NRlSI?t=2801) + - [Shadowing](https://youtu.be/vvanI8NRlSI?t=3584) + - [Variable Length Arguments](https://youtu.be/vvanI8NRlSI?t=4013) + - [Overloading](https://youtu.be/vvanI8NRlSI?t=4327) +- [Arrays](https://youtu.be/n60Dn0UsbEk) + - [Introduction](https://youtu.be/n60Dn0UsbEk) + - [Memory management](https://youtu.be/n60Dn0UsbEk?t=632) + - [Input and Output](https://youtu.be/n60Dn0UsbEk?t=1675) + - [ArrayList Introduction](https://youtu.be/n60Dn0UsbEk?t=4868) + - Searching + - [Linear Search](https://youtu.be/_HRA37X8N_Q) + - [Binary Search](https://youtu.be/f6UU7V3szVw) + - [Modified Binary Search](https://youtu.be/f6UU7V3szVw?t=2508) + - [Binary Search on 2D Arrays](https://www.youtube.com/watch?v=enI_KyGLYPo) + - Sorting + - [Insertion Sort](https://youtu.be/By_5-RRqVeE) + - [Selection Sort](https://youtu.be/Nd4SCCIHFWk) + - [Bubble Sort](https://youtu.be/F5MZyqRp_IM) + - [Cyclic Sort](https://youtu.be/JfinxytTYFQ) + - [Count Sort](https://youtu.be/FOo820lJV1Y) + - [Radix Sort](https://youtu.be/mLi6VQDqAOs) +- [Pattern questions](https://youtu.be/lsOOs5J8ycw) +- [Strings](https://www.youtube.com/watch?v=zL1DPZ0Ovlo) + - [Introduction](https://www.youtube.com/watch?v=zL1DPZ0Ovlo) + - [How Strings work](https://youtu.be/zL1DPZ0Ovlo?t=216) + - [Comparison of methods](https://youtu.be/zL1DPZ0Ovlo?t=977) + - [Operations in Strings](https://youtu.be/zL1DPZ0Ovlo?t=1681) + - [StringBuilder in Java](https://youtu.be/zL1DPZ0Ovlo?t=4199) + - [StringBuffer](https://www.youtube.com/watch?v=YFZai3fPUQI) +- [Maths for DSA](https://youtu.be/fzip9Aml6og) + - [Introduction](https://youtu.be/fzip9Aml6og?t=20) + - [Complete Bitwise Operators](https://youtu.be/fzip9Aml6og?t=95) + - [Range of numbers](https://youtu.be/fzip9Aml6og?t=4169) + - [Prime numbers](https://youtu.be/lmSpZ0bjCyQ?t=57) + - [Sieve of Eratosthenes](https://youtu.be/lmSpZ0bjCyQ?t=850) + - [Newton's Square Root Method](https://youtu.be/lmSpZ0bjCyQ?t=1989) + - [Factors](https://youtu.be/lmSpZ0bjCyQ?t=3004) + - [Modulo properties](https://youtu.be/lmSpZ0bjCyQ?t=3980) + - [Number Theory](https://youtu.be/lmSpZ0bjCyQ?t=4405) + - [HCF / LCM](https://youtu.be/lmSpZ0bjCyQ?t=5110) + - [Euclidean algorithm](https://youtu.be/lmSpZ0bjCyQ?t=5520) + - [BigInteger & BigDecimal](https://www.youtube.com/watch?v=lHtoypC-4Ps) +- [Recursion](https://www.youtube.com/playlist?list=PL9gnSGHSqcnp39cTyB1dTZ2pJ04Xmdrod) + - [Introduction](https://youtu.be/M2uO2nMT0Bk) + - [Flow of recursive programs - stacks](https://youtu.be/M2uO2nMT0Bk?t=2124) + - [Why recursion?](https://youtu.be/M2uO2nMT0Bk?t=2708) + - [Tree building of function calls](https://youtu.be/M2uO2nMT0Bk?t=3033) + - [Tail recursion](https://youtu.be/M2uO2nMT0Bk?t=4308) + - [Sorting](https://www.youtube.com/playlist?list=PL9gnSGHSqcnq-9CXLt9DsInytRMLoyZQ_) + - [Merge Sort](https://youtu.be/iKGAgWdgoRk) + - [Quick Sort](https://www.youtube.com/watch?v=Z8svOqamag8&list=PL9gnSGHSqcnr_DxHsP7AW9ftq0AtAyYqJ&index=27) + - [Backtracking](https://youtu.be/zg5v2rlV1tM) + - [N-Queens](https://youtu.be/nC1rbW2YSz0) + - [N-Knights](https://youtu.be/nC1rbW2YSz0?t=2342) + - [Sudoku Solver](https://youtu.be/nC1rbW2YSz0?t=3190) + - [Maze problems](https://www.youtube.com/watch?v=zg5v2rlV1tM) + - [Recursion String Problems](https://youtu.be/gdifkIwCJyg) + - [Recursion Google, Amazon Questions](https://youtu.be/9ByWqPzfXDU) + - [Recursion Array Problems](https://youtu.be/sTdiMLom00U) + - [Recursion Pattern Problems](https://youtu.be/ymgnIIclCF0) + - [Subset Questions](https://youtu.be/9ByWqPzfXDU) +- [Space and Time Complexity Analysis](https://youtu.be/mV3wrLBbuuE) + - [Introduction](https://youtu.be/mV3wrLBbuuE) + - [Comparisons of various cases](https://youtu.be/mV3wrLBbuuE?t=1039) + - [Solving Linear Recurrence Relations](https://youtu.be/mV3wrLBbuuE?t=6252) + - [Solving Divide and Conquer Recurrence Relations](https://youtu.be/mV3wrLBbuuE?t=4609) + - [Big-O, Big-Omega, Big-Theta Notations](https://youtu.be/mV3wrLBbuuE?t=2271) + - [Little Notations](https://youtu.be/mV3wrLBbuuE?t=2960) + - [Get equation of any relation easily - best and easiest approach](https://youtu.be/mV3wrLBbuuE?t=8189) + - [Complexity discussion of all the problems we do](https://youtu.be/mV3wrLBbuuE?t=3866) + - [Space Complexity](https://youtu.be/mV3wrLBbuuE?t=3330) + - [NP-Completeness Introduction](https://youtu.be/mV3wrLBbuuE?t=8695) +- [Object Oriented Programming](https://www.youtube.com/playlist?list=PL9gnSGHSqcno1G3XjUbwzXHL8_EttOuKk) + - [Introduction](https://www.youtube.com/watch?v=BSVKUk58K6U) + - [Classes & its instances](https://youtu.be/BSVKUk58K6U?t=467) + - [this keyword in Java](https://youtu.be/BSVKUk58K6U?t=3380) + - [Properties](https://www.youtube.com/watch?v=46T2wD3IuhM) + - [Inheritance](https://youtu.be/46T2wD3IuhM?t=146) + - [Abstraction](https://youtu.be/46T2wD3IuhM?t=7102) + - [Polymorphism](https://youtu.be/46T2wD3IuhM?t=4226) + - [Encapsulation](https://youtu.be/46T2wD3IuhM?t=7022) + - [Overloading & Overriding](https://youtu.be/46T2wD3IuhM?t=4834) + - [Static & Non-Static](https://youtu.be/_Ya6CN13t8k?t=1137) + - [Packages](https://youtu.be/_Ya6CN13t8k?t=182) + - [Access Control](https://youtu.be/W145DXs8fFg) + - [Interfaces](https://youtu.be/rgHZa7-Dibg?t=1510) + - [Abstract Classes](https://youtu.be/rgHZa7-Dibg?t=68) + - [Annotations](https://youtu.be/rgHZa7-Dibg?t=3438) + - [Singleton Class](https://youtu.be/_Ya6CN13t8k?t=4240) + - [final, finalize, finally](https://youtu.be/46T2wD3IuhM?t=6317) + - [Object Cloning](https://youtu.be/OY2lPr8h93U?t=4352) + - [Object Class](https://youtu.be/W145DXs8fFg?t=1943) + - [Generics](https://www.youtube.com/watch?v=OY2lPr8h93U) + - [Exception Handling](https://youtu.be/OY2lPr8h93U?t=3405) + - [Collections Framework](https://youtu.be/9ogGan-R1pc?t=49) + - [Vector Class](https://youtu.be/9ogGan-R1pc?t=668) + - [Lambda Expression](https://youtu.be/OY2lPr8h93U?t=2894) + - [Enums](https://youtu.be/9ogGan-R1pc?t=909) +- Linked List + - [Introduction](https://youtu.be/58YbpRDc4yw) + - [Singly + Doubly + Circular LinkedList](https://youtu.be/58YbpRDc4yw) + - [Fast and slow pointer](https://youtu.be/70tx7KcMROc) + - [Cycle Detection](https://youtu.be/70tx7KcMROc) + - [Reversal of LinkedList](https://youtu.be/70tx7KcMROc) + - [Linked List + Recursion](https://youtu.be/70tx7KcMROc) +- [Stacks & Queues](https://www.youtube.com/watch?v=rHQI4mrJ3cg) + - Introduction + - Push efficient + - Pop efficient + - Queue using Stack and vice versa + - Circular Queue + - [Interview problems](https://www.youtube.com/watch?v=S9LUYztYLu4) +- [File handling](https://www.youtube.com/watch?v=b35mlSPOlJg) +- [Trees](https://www.youtube.com/playlist?list=PL9gnSGHSqcnqfctdbCQKaw5oZ9Up2cmsq) + - [Introduction](https://www.youtube.com/watch?v=4s1Tcvm00pA) + - Binary Trees + - Binary Search Trees + - [Interview questions](https://www.youtube.com/watch?v=9D-vP-jcc-Y) + - DFS + - BFS + - [AVL Trees](https://www.youtube.com/watch?v=CVA85JuJEn0) + - [Segment Tree](https://www.youtube.com/watch?v=ciHThtTVNto) + - Fenwick Tree / Binary Indexed Tree +- Heaps + - [Introduction](https://youtu.be/Qf-TDPr0nYw) + - Theory + - Priority Queue + - Heapsort + - Two Heaps Method + - k-way merge + - Top k elements + - Interval problems +- HashMap + - [Introduction](https://youtu.be/XLbvmMz8Fr8) + - Theory - how it works + - Comparisons of various forms + - Limitations and how to solve + - Map using LinkedList + - Map using Hash + - Chaining + - Probing + - [Huffman Coding](https://youtu.be/XLfgeaYHinM) + - [Karp-Rabin Strng matching algorithm](https://youtu.be/swciWFPq3NE) +- Subarray Questions: Sliding window, Two Pointer, Kadane's Algorithm +- Graphs + - Introduction + - BFS + - DFS + - Working with graph components + - Minimum Spanning Trees + - Kruskal Algorithm + - Prims Algorithm + - Dijkstra’s shortest path algorithm + - Topological Sort + - Bellman ford + - A* pathfinding Algorithm +- Dynamic Programming + - Introduction + - Recursion + Recursion DP + Iteration + Iteration Space Optimized + - Complexity Analysis + - 0/1 Knapsack + - Subset Questions + - Unbounded Knapsack + - Subsequence questions + - String DP +- Greedy Algorithms +- Tries + +### Advanced concepts apart from interviews +- Bitwise + DP +- Extended Euclidean algorithm +- Modulo Multiplicative Inverse +- Linear Diophantine Equations +- Matrix Exponentiation +- Mathematical Expectation +- Catalan Numbers +- Fermat’s Theorem +- Wilson's Theorem +- Euler's Theorem +- Lucas Theorem +- Chinese Remainder Theorem +- Euler Totient +- NP-Completeness +- Multithreading +- Square Root Decomposition diff --git a/assignments/17-trees.md b/assignments/17-trees.md new file mode 100644 index 000000000..48af717f3 --- /dev/null +++ b/assignments/17-trees.md @@ -0,0 +1,64 @@ +# Problems + +## Easy + +- [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) `leetcode` +- [Same Tree](https://leetcode.com/problems/same-tree/) `leetcode` +- [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/) `leetcode` +- [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) `leetcode` +- [Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) `leetcode` +- [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) `leetcode` +- [Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/) `leetcode` +- [Path Sum](https://leetcode.com/problems/path-sum/) `leetcode` +- [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) `leetcode` +- [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) `leetcode` +- [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) `leetcode` +- [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) `leetcode` +- [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) `leetcode` +- [Find Mode in Binary Search Tree](https://leetcode.com/problems/find-mode-in-binary-search-tree/) `leetcode` +- [Minimum Absolute Difference in BST](https://leetcode.com/problems/minimum-absolute-difference-in-bst/) `leetcode` +- [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) `leetcode` + +## Medium + +- [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) `leetcode` +- [All Nodes Distance K in Binary Tree](https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/) `leetcode` +- [Validate Binary Tree Nodes](https://leetcode.com/problems/validate-binary-tree-nodes/) `leetcode` +- [Longest Univalue Path](https://leetcode.com/problems/longest-univalue-path/) `leetcode` +- [Closest Nodes Queries in a Binary Search Tree](https://leetcode.com/problems/closest-nodes-queries-in-a-binary-search-tree/) `leetcode` +- [Maximum Width of Binary Tree](https://leetcode.com/problems/maximum-width-of-binary-tree/) `leetcode` +- [Linked List in Binary Tree](https://leetcode.com/problems/linked-list-in-binary-tree/) `leetcode` +- [Operations on Tree](https://leetcode.com/problems/operations-on-tree/) `leetcode` +- [Verify Preorder Serialization of a Binary Tree](https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/) `leetcode` +- [Kth Largest Sum in a Binary Tree](https://leetcode.com/problems/kth-largest-sum-in-a-binary-tree/) `leetcode` +- [Count Nodes With the Highest Score](https://leetcode.com/problems/count-nodes-with-the-highest-score/) `leetcode` +- [Path Sum III](https://leetcode.com/problems/path-sum-iii/) `leetcode` +- [Maximum Product of Splitted Binary Tree](https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/) `leetcode` +- [Most Profitable Path in a Tree](https://leetcode.com/problems/most-profitable-path-in-a-tree/) `leetcode` +- [Step-By-Step Directions From a Binary Tree Node to Another](https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/) `leetcode` +- [Logical OR of Two Binary Grids Represented as Quad-Trees](https://leetcode.com/problems/logical-or-of-two-binary-grids-represented-as-quad-trees/) `leetcode` +- [Flip Binary Tree To Match Preorder Traversal](https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/) `leetcode` + +## Hard + +- [Kth Ancestor of a Tree Node](https://leetcode.com/problems/kth-ancestor-of-a-tree-node/) `leetcode` +- [Difference Between Maximum and Minimum Price Sum](https://leetcode.com/problems/difference-between-maximum-and-minimum-price-sum/) `leetcode` +- [Merge BSTs to Create Single BST](https://leetcode.com/problems/merge-bsts-to-create-single-bst/) `leetcode` +- [Frog Position After T Seconds](https://leetcode.com/problems/frog-position-after-t-seconds/) `leetcode` +- [Height of Binary Tree After Subtree Removal Queries](https://leetcode.com/problems/height-of-binary-tree-after-subtree-removal-queries/) `leetcode` +- [Collect Coins in a Tree](https://leetcode.com/problems/collect-coins-in-a-tree/) `leetcode` +- [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/) `leetcode` +- [Tree of Coprimes](https://leetcode.com/problems/tree-of-coprimes/) `leetcode` +- [Maximum Sum BST in Binary Tree](https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/) `leetcode` +- [Minimize the Total Price of the Trips](https://leetcode.com/problems/minimize-the-total-price-of-the-trips/) `leetcode` +- [Number Of Ways To Reconstruct A Tree](https://leetcode.com/problems/number-of-ways-to-reconstruct-a-tree/) `leetcode` +- [Smallest Missing Genetic Value in Each Subtree](https://leetcode.com/problems/smallest-missing-genetic-value-in-each-subtree/) `leetcode` +- [Vertical Order Traversal of a Binary Tree](https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/) `leetcode` +- [Binary Tree Cameras](https://leetcode.com/problems/binary-tree-cameras/) `leetcode` +- [Number of Ways to Reorder Array to Get Same BST](https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/) `leetcode` +- [Count Number of Possible Root Nodes](https://leetcode.com/problems/count-number-of-possible-root-nodes/) `leetcode` +- [Count Ways to Build Rooms in an Ant Colony](https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony/) `leetcode` +- [Minimum Score After Removals on a Tree](https://leetcode.com/problems/minimum-score-after-removals-on-a-tree/) `leetcode` +- [Create Components With Same Value](https://leetcode.com/problems/create-components-with-same-value/) `leetcode` +- [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) `leetcode` +- [Longest Path With Different Adjacent Characters](https://leetcode.com/problems/longest-path-with-different-adjacent-characters/) `leetcode` diff --git a/assignments/18-heaps.md b/assignments/18-heaps.md new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/assignments/18-heaps.md @@ -0,0 +1 @@ + diff --git a/lectures/06-conditions-loops/code/.idea/misc.xml b/lectures/06-conditions-loops/code/.idea/misc.xml index 116eff691..e151340a5 100644 --- a/lectures/06-conditions-loops/code/.idea/misc.xml +++ b/lectures/06-conditions-loops/code/.idea/misc.xml @@ -1,12 +1,9 @@ - - - - + \ No newline at end of file diff --git a/lectures/19-stacks-n-queues/Questions.pdf b/lectures/19-stacks-n-queues/Questions.pdf new file mode 100644 index 000000000..c9ed1395a Binary files /dev/null and b/lectures/19-stacks-n-queues/Questions.pdf differ diff --git a/lectures/19-stacks-n-queues/questions/LargestAreaHistogram.java b/lectures/19-stacks-n-queues/questions/LargestAreaHistogram.java new file mode 100644 index 000000000..587938ab2 --- /dev/null +++ b/lectures/19-stacks-n-queues/questions/LargestAreaHistogram.java @@ -0,0 +1,39 @@ +import java.util.Stack; + +class Main { + public static void main(String[] args) { + + } + + public int largestRectangleArea(int[] heights) { + Stack stack = new Stack<>(); + int max = 0; + + stack.push(0); + + for (int i = 1; i < heights.length; i++) { + while (!stack.isEmpty() && heights[i] < heights[stack.peek()]) { + max = getMax(heights, stack, max, i); + } + stack.push(i); + } + + int i = heights.length; + while (!stack.isEmpty()) { + max = getMax(heights, stack, max, i); + } + + return max; + } + + private static int getMax(int[] arr, Stack stack, int max, int i) { + int area; + int popped = stack.pop(); + if (stack.isEmpty()) { + area = arr[popped] * i; + } else { + area = arr[popped] * (i - 1 - stack.peek()); + } + return Math.max(max, area); + } +} \ No newline at end of file diff --git a/lectures/19-stacks-n-queues/questions/QueueUsingStack.java b/lectures/19-stacks-n-queues/questions/QueueUsingStack.java new file mode 100644 index 000000000..076342b93 --- /dev/null +++ b/lectures/19-stacks-n-queues/questions/QueueUsingStack.java @@ -0,0 +1,44 @@ +import java.util.Stack; + +public class QueueUsingStack { + private Stack first; + private Stack second; + + public QueueUsingStack() { + first = new Stack<>(); + second = new Stack<>(); + } + + public void add(int item) { + first.push(item); + } + + public int remove() throws Exception { + while (!first.isEmpty()) { + second.push(first.pop()); + } + int removed = second.pop(); + while (!second.isEmpty()) { + first.push(second.pop()); + } + return removed; + } + + public int peek() throws Exception { + while (!first.isEmpty()) { + second.push(first.pop()); + } + + int peeked = second.peek(); + + while (!second.isEmpty()) { + first.push(second.pop()); + } + return peeked; + } + + public boolean isEmpty() { + return first.isEmpty(); + } + +} \ No newline at end of file diff --git a/lectures/19-stacks-n-queues/questions/QueueUsingStackRemove.java b/lectures/19-stacks-n-queues/questions/QueueUsingStackRemove.java new file mode 100644 index 000000000..ac6b7eec6 --- /dev/null +++ b/lectures/19-stacks-n-queues/questions/QueueUsingStackRemove.java @@ -0,0 +1,34 @@ +import java.util.Stack; + +public class QueueUsingStackRemove { + private Stack first; + private Stack second; + + public QueueUsingStackRemove() { + first = new Stack<>(); + second = new Stack<>(); + } + + public void add(int item) throws Exception { + while (!first.isEmpty()) { + second.push(first.pop()); + } + first.push(item); + while (!second.isEmpty()) { + first.push(second.pop()); + } + } + + public int remove() throws Exception { + return first.pop(); + } + + public int peek() throws Exception { + return first.peek(); + } + + public boolean isEmpty() { + return first.isEmpty(); + } + +} \ No newline at end of file diff --git a/lectures/19-stacks-n-queues/questions/TwoStacks.java b/lectures/19-stacks-n-queues/questions/TwoStacks.java new file mode 100644 index 000000000..5fec46e60 --- /dev/null +++ b/lectures/19-stacks-n-queues/questions/TwoStacks.java @@ -0,0 +1,42 @@ +import java.util.*; + +class TwoStacks { + static int twoStacks(int x, int[] a, int[] b) { + return twoStacks(x, a, b, 0, 0) - 1; + } + + private static int twoStacks(int x, int[] a, int[] b, int sum, int count) { + if (sum > x) { + return count; + } + + if (a.length == 0 || b.length == 0) { + return count; + } + + int ans1 = twoStacks(x, Arrays.copyOfRange(a, 1, a.length), b, sum + a[0], count + 1); + int ans2 = twoStacks(x, a, Arrays.copyOfRange(b, 1, b.length), sum + a[0], count + 1); + + return Math.max(ans1, ans2); + } + + public static void main(String[] args) { + Scanner s = new Scanner(System.in); + int t = s.nextInt(); + for (int i = 0; i < t; i++) { + int n = s.nextInt(); + int m = s.nextInt(); + int x = s.nextInt(); + int[] a = new int[n]; + int[] b = new int[m]; + for (int j = 0; j < n; j++) { + a[j] = s.nextInt(); + } + for (int j = 0; j < m; j++) { + b[j] = s.nextInt(); + } + System.out.println(twoStacks(x, a, b)); + } + } + +} \ No newline at end of file diff --git a/lectures/19-stacks-n-queues/questions/ValidParenMinAdd.java b/lectures/19-stacks-n-queues/questions/ValidParenMinAdd.java new file mode 100644 index 000000000..47331c04b --- /dev/null +++ b/lectures/19-stacks-n-queues/questions/ValidParenMinAdd.java @@ -0,0 +1,18 @@ +import java.util.Stack; +class Solution { + public int minAddToMakeValid(String s) { + Stack stack = new Stack<>(); + for (char ch : s.toCharArray()) { + if (ch == ')') { + if (!stack.isEmpty() && stack.peek() == '(') { + stack.pop(); + } else { + stack.push(ch); + } + } else { + stack.push(ch); + } + } + return stack.size(); + } +} \ No newline at end of file diff --git a/lectures/19-stacks-n-queues/questions/ValidParenthesis.java b/lectures/19-stacks-n-queues/questions/ValidParenthesis.java new file mode 100644 index 000000000..930708768 --- /dev/null +++ b/lectures/19-stacks-n-queues/questions/ValidParenthesis.java @@ -0,0 +1,30 @@ +import java.util.Stack; + +class Solution { + public boolean isValid(String s) { + Stack stack = new Stack<>(); + + for (char ch : s.toCharArray()) { + if (ch == '(' || ch == '{' || ch == '[') { + stack.push(ch); + } else { + if (ch == ')') { + if (stack.isEmpty() || stack.pop() != '(') { + return false; + } + } + if (ch == '}') { + if (stack.isEmpty() || stack.pop() != '{') { + return false; + } + } + if (ch == ']') { + if (stack.isEmpty() || stack.pop() != '[') { + return false; + } + } + } + } + return stack.isEmpty(); + } +} \ No newline at end of file diff --git a/lectures/20-trees/code/AVL/.breakpoints b/lectures/20-trees/code/AVL/.breakpoints new file mode 100644 index 000000000..5cc232f02 --- /dev/null +++ b/lectures/20-trees/code/AVL/.breakpoints @@ -0,0 +1,3 @@ +{ + "files": {} +} \ No newline at end of file diff --git a/lectures/20-trees/code/AVL/.cache/replit/__replit_disk_meta.json b/lectures/20-trees/code/AVL/.cache/replit/__replit_disk_meta.json new file mode 100644 index 000000000..6b4fa05fa --- /dev/null +++ b/lectures/20-trees/code/AVL/.cache/replit/__replit_disk_meta.json @@ -0,0 +1 @@ +{"nonce":6822585830757037893,"last_updated":{"seconds":1690198025,"nanos":992471000}} diff --git a/lectures/20-trees/code/AVL/.cache/replit/modules.stamp b/lectures/20-trees/code/AVL/.cache/replit/modules.stamp new file mode 100644 index 000000000..c39d1108c --- /dev/null +++ b/lectures/20-trees/code/AVL/.cache/replit/modules.stamp @@ -0,0 +1 @@ +2jmj7l5rSw0yVb_vlWAYkK_YBwk= \ No newline at end of file diff --git a/lectures/20-trees/code/AVL/.cache/replit/nix/env.json b/lectures/20-trees/code/AVL/.cache/replit/nix/env.json new file mode 100644 index 000000000..b1bc56611 --- /dev/null +++ b/lectures/20-trees/code/AVL/.cache/replit/nix/env.json @@ -0,0 +1 @@ +{"entries":{"replit.nix":{"env":{"AR":"ar","AS":"as","CC":"gcc","CONFIG_SHELL":"/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin/bash","CXX":"g++","HOST_PATH":"/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/bin:/nix/store/6z9ag3ihc8mq2hzsw48lhbznvzny65nz-apache-maven-3.8.6/bin:/nix/store/m6gcpi1ii6rghy04cjwjddcavv7i90df-jdt-language-server-1.9.0/bin:/nix/store/84xs5alhs01zrbr4ywm05kxbjbp5590l-java-debug/bin:/nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1/bin:/nix/store/mydc6f4k2z73xlcz7ilif3v2lcaiqvza-findutils-4.9.0/bin:/nix/store/j9p3g8472iijd50vhdprx0nmk2fqn5gv-diffutils-3.8/bin:/nix/store/89zs7rms6x00xfq4dq6m7mjnhkr8a6r4-gnused-4.8/bin:/nix/store/86bp03jkmsl6f92w0yzg4s59g5mhxwmy-gnugrep-3.7/bin:/nix/store/hwcdqw4jrjnd37wxqgsd47hd0j8bnj09-gawk-5.1.1/bin:/nix/store/cfbhw8r8ags41vwqaz47r583d0p4h4a1-gnutar-1.34/bin:/nix/store/p3m1ndl1lapwrlh698bnb5lvvxh67378-gzip-1.12/bin:/nix/store/a8mhcagrsly7c7mpjrpsnaahk4aax056-bzip2-1.0.8-bin/bin:/nix/store/mblgz65m3zv9x548a3d5m96fj2pbwr09-gnumake-4.3/bin:/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin:/nix/store/v7ljksji50mg3w61dykaa3n3y79n6nil-patch-2.7.6/bin:/nix/store/zlcnmqq14jz5x9439jf937mvayyl63da-xz-5.2.7-bin/bin:/nix/store/y6aj732zm9m87c82fpvf103a1xb22blp-file-5.43/bin","JAVA_HOME":"/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0","LD":"ld","LOCALE_ARCHIVE":"/usr/lib/locale/locale-archive","NIX_BINTOOLS":"/nix/store/1d6ian3r8kdzspw8hacjhl3xkp40g1lj-binutils-wrapper-2.39","NIX_BINTOOLS_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu":"1","NIX_BUILD_CORES":"16","NIX_BUILD_TOP":"/tmp","NIX_CC":"/nix/store/dq0xwmsk1g0i2ayg6pb7y87na2knzylh-gcc-wrapper-11.3.0","NIX_CC_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu":"1","NIX_CFLAGS_COMPILE":" -frandom-seed=vzlvbz7had -isystem /nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/include -isystem /nix/store/0y971q54v6jm9ss243xhl4y0gnlsm9c8-zlib-1.2.13-dev/include -isystem /nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/include -isystem /nix/store/0y971q54v6jm9ss243xhl4y0gnlsm9c8-zlib-1.2.13-dev/include","NIX_ENFORCE_NO_NATIVE":"1","NIX_HARDENING_ENABLE":"fortify stackprotector pic strictoverflow format relro bindnow","NIX_INDENT_MAKE":"1","NIX_LDFLAGS":"-rpath /nix/store/vzlvbz7had654yd78xdypqh0sw6zr8x3-nix-shell/lib64 -rpath /nix/store/vzlvbz7had654yd78xdypqh0sw6zr8x3-nix-shell/lib -L/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/lib -L/nix/store/026hln0aq1hyshaxsdvhg0kmcm6yf45r-zlib-1.2.13/lib -L/nix/store/2h0a1ma7bp2vprkmh6n4n2k1hcn1z0x8-graalvm17-ce-22.3.0-lib/lib -L/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/lib -L/nix/store/026hln0aq1hyshaxsdvhg0kmcm6yf45r-zlib-1.2.13/lib -L/nix/store/2h0a1ma7bp2vprkmh6n4n2k1hcn1z0x8-graalvm17-ce-22.3.0-lib/lib","NIX_STORE":"/nix/store","NM":"nm","OBJCOPY":"objcopy","OBJDUMP":"objdump","PATH":"/nix/store/bap4d0lpcrhpwmpb8ayjcgkmvfj62lnq-bash-interactive-5.1-p16/bin:/nix/store/pr5n59mb4jzmfx6kanwxly0l07p861fg-patchelf-0.15.0/bin:/nix/store/dq0xwmsk1g0i2ayg6pb7y87na2knzylh-gcc-wrapper-11.3.0/bin:/nix/store/1gf2flfqnpqbr1b4p4qz2f72y42bs56r-gcc-11.3.0/bin:/nix/store/57xv61c5zi8pphjbcwxxjlgc34p61ic9-glibc-2.35-163-bin/bin:/nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1/bin:/nix/store/1d6ian3r8kdzspw8hacjhl3xkp40g1lj-binutils-wrapper-2.39/bin:/nix/store/039g378vc3pc3dvi9dzdlrd0i4q93qwf-binutils-2.39/bin:/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/bin:/nix/store/6z9ag3ihc8mq2hzsw48lhbznvzny65nz-apache-maven-3.8.6/bin:/nix/store/m6gcpi1ii6rghy04cjwjddcavv7i90df-jdt-language-server-1.9.0/bin:/nix/store/84xs5alhs01zrbr4ywm05kxbjbp5590l-java-debug/bin:/nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1/bin:/nix/store/mydc6f4k2z73xlcz7ilif3v2lcaiqvza-findutils-4.9.0/bin:/nix/store/j9p3g8472iijd50vhdprx0nmk2fqn5gv-diffutils-3.8/bin:/nix/store/89zs7rms6x00xfq4dq6m7mjnhkr8a6r4-gnused-4.8/bin:/nix/store/86bp03jkmsl6f92w0yzg4s59g5mhxwmy-gnugrep-3.7/bin:/nix/store/hwcdqw4jrjnd37wxqgsd47hd0j8bnj09-gawk-5.1.1/bin:/nix/store/cfbhw8r8ags41vwqaz47r583d0p4h4a1-gnutar-1.34/bin:/nix/store/p3m1ndl1lapwrlh698bnb5lvvxh67378-gzip-1.12/bin:/nix/store/a8mhcagrsly7c7mpjrpsnaahk4aax056-bzip2-1.0.8-bin/bin:/nix/store/mblgz65m3zv9x548a3d5m96fj2pbwr09-gnumake-4.3/bin:/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin:/nix/store/v7ljksji50mg3w61dykaa3n3y79n6nil-patch-2.7.6/bin:/nix/store/zlcnmqq14jz5x9439jf937mvayyl63da-xz-5.2.7-bin/bin:/nix/store/y6aj732zm9m87c82fpvf103a1xb22blp-file-5.43/bin","RANLIB":"ranlib","READELF":"readelf","SIZE":"size","SOURCE_DATE_EPOCH":"315532800","STRINGS":"strings","STRIP":"strip","XDG_DATA_DIRS":"/nix/store/pr5n59mb4jzmfx6kanwxly0l07p861fg-patchelf-0.15.0/share","_":"/nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1/bin/env","__ETC_PROFILE_SOURCED":"1","buildInputs":"/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0 /nix/store/6z9ag3ihc8mq2hzsw48lhbznvzny65nz-apache-maven-3.8.6 /nix/store/m6gcpi1ii6rghy04cjwjddcavv7i90df-jdt-language-server-1.9.0 /nix/store/84xs5alhs01zrbr4ywm05kxbjbp5590l-java-debug","buildPhase":"echo \"------------------------------------------------------------\" \u003e\u003e$out\necho \" WARNING: the existence of this path is not guaranteed.\" \u003e\u003e$out\necho \" It is an internal implementation detail for pkgs.mkShell.\" \u003e\u003e$out\necho \"------------------------------------------------------------\" \u003e\u003e$out\necho \u003e\u003e $out\n# Record all build inputs as runtime dependencies\nexport \u003e\u003e $out\n","builder":"/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin/bash","cmakeFlags":"","configureFlags":"","depsBuildBuild":"","depsBuildBuildPropagated":"","depsBuildTarget":"","depsBuildTargetPropagated":"","depsHostHost":"","depsHostHostPropagated":"","depsTargetTarget":"","depsTargetTargetPropagated":"","doCheck":"","doInstallCheck":"","mesonFlags":"","name":"nix-shell","nativeBuildInputs":"","out":"/nix/store/vzlvbz7had654yd78xdypqh0sw6zr8x3-nix-shell","outputs":"out","patches":"","phases":"buildPhase","propagatedBuildInputs":"","propagatedNativeBuildInputs":"","shell":"/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin/bash","shellHook":"","stdenv":"/nix/store/kmfaajdpyyyg319vfqni5jm9wkxjmf73-stdenv-linux","strictDeps":"","system":"x86_64-linux"},"dependencies":[{"path":"replit.nix","mod_time":"2023-05-12T19:41:48.477539597Z"}],"channel":"stable-22_11","channel_nix_path":"/nix/store/1hxr7x3df6jw0h175dkd2qybvkdscsj1-nixpkgs-stable-22_11-22.11.tar.gz/nixpkgs-stable-22_11"}}} \ No newline at end of file diff --git a/lectures/20-trees/code/AVL/.classpath b/lectures/20-trees/code/AVL/.classpath new file mode 100644 index 000000000..75b806fd7 --- /dev/null +++ b/lectures/20-trees/code/AVL/.classpath @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lectures/20-trees/code/AVL/.project b/lectures/20-trees/code/AVL/.project new file mode 100644 index 000000000..a2380fe36 --- /dev/null +++ b/lectures/20-trees/code/AVL/.project @@ -0,0 +1,34 @@ + + + myartifactid + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + + + 1679078569810 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + + diff --git a/lectures/20-trees/code/AVL/.replit b/lectures/20-trees/code/AVL/.replit new file mode 100644 index 000000000..48e2be7d3 --- /dev/null +++ b/lectures/20-trees/code/AVL/.replit @@ -0,0 +1,63 @@ +compile = "javac -classpath .:target/dependency/* -d . $(find . -type f -name '*.java')" +run = "java -classpath .:target/dependency/* Main" +entrypoint = "Main.java" +hidden = ["**/*.class"] + +[packager] +language = "java" + +[packager.features] +packageSearch = true + +[languages.java] +pattern = "**/*.java" + +[languages.java.languageServer] +start = "jdt-language-server" + +[unitTest] +language = "java" + +[nix] +channel = "stable-22_11" + +[debugger] +support = true + +[debugger.compile] +command = "javac -classpath .:/run_dir/junit-4.12.jar:target/dependency/* -g -d . $(find . -type f -name '*.java')" + +[debugger.interactive] +transport = "localhost:0" +connectTimeout = 60 +startCommand = "java-debug" + +[debugger.interactive.initializeMessage] +command = "initialize" +type = "request" + +[debugger.interactive.initializeMessage.arguments] +adapterID = "cppdbg" +clientID = "replit" +clientName = "replit.com" +columnsStartAt1 = true +linesStartAt1 = true +locale = "en-us" +pathFormat = "path" +supportsInvalidatedEvent = true +supportsProgressReporting = true +supportsRunInTerminalRequest = true +supportsVariablePaging = true +supportsVariableType = true + +[debugger.interactive.launchMessage] +command = "launch" +type = "request" + +[debugger.interactive.launchMessage.arguments] +classPaths = ["."] +mainClass = "Main" + +[deployment] +build = "javac -classpath .:target/dependency/* -d . $(find . -type f -name '*.java')" +run = "java -classpath .:target/dependency/* Main" \ No newline at end of file diff --git a/lectures/20-trees/code/AVL/.settings/org.eclipse.jdt.apt.core.prefs b/lectures/20-trees/code/AVL/.settings/org.eclipse.jdt.apt.core.prefs new file mode 100644 index 000000000..d4313d4b2 --- /dev/null +++ b/lectures/20-trees/code/AVL/.settings/org.eclipse.jdt.apt.core.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.apt.aptEnabled=false diff --git a/lectures/20-trees/code/AVL/.settings/org.eclipse.jdt.core.prefs b/lectures/20-trees/code/AVL/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..ac8e7500c --- /dev/null +++ b/lectures/20-trees/code/AVL/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,9 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore +org.eclipse.jdt.core.compiler.processAnnotations=disabled +org.eclipse.jdt.core.compiler.release=disabled +org.eclipse.jdt.core.compiler.source=1.5 diff --git a/lectures/20-trees/code/AVL/.settings/org.eclipse.m2e.core.prefs b/lectures/20-trees/code/AVL/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 000000000..f897a7f1c --- /dev/null +++ b/lectures/20-trees/code/AVL/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/lectures/20-trees/code/AVL/.upm/store.json b/lectures/20-trees/code/AVL/.upm/store.json new file mode 100644 index 000000000..c0ec20343 --- /dev/null +++ b/lectures/20-trees/code/AVL/.upm/store.json @@ -0,0 +1 @@ +{"version":2,"languages":{"java-maven":{"specfileHash":"3ff69d18804bae1a389cb7ea263f0c5b","lockfileHash":"3ff69d18804bae1a389cb7ea263f0c5b"}}} diff --git a/lectures/20-trees/code/AVL/AVL.java b/lectures/20-trees/code/AVL/AVL.java new file mode 100644 index 000000000..b3080fcd3 --- /dev/null +++ b/lectures/20-trees/code/AVL/AVL.java @@ -0,0 +1,162 @@ +class AVL { + + public class Node { + private int value; + private Node left; + private Node right; + private int height; + + public Node(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + } + + private Node root; + + public AVL() { + + } + + public int height() { + return height(root); + } + private int height(Node node) { + if (node == null) { + return -1; + } + return node.height; + } + + public void insert(int value) { + root = insert(value, root); + } + + private Node insert(int value, Node node) { + if (node == null) { + node = new Node(value); + return node; + } + + if (value < node.value) { + node.left = insert(value, node.left); + } + + if (value > node.value) { + node.right = insert(value, node.right); + } + + node.height = Math.max(height(node.left), height(node.right)) + 1; + return rotate(node); + } + + private Node rotate(Node node) { + if (height(node.left) - height(node.right) > 1) { + // left heavy + if(height(node.left.left) - height(node.left.right) > 0) { + // left left case + return rightRotate(node); + } + if(height(node.left.left) - height(node.left.right) < 0) { + // left right case + node.left = leftRotate(node.left); + return rightRotate(node); + } + } + + if (height(node.left) - height(node.right) < -1) { + // right heavy + if(height(node.right.left) - height(node.right.right) < 0) { + // right right case + return leftRotate(node); + } + if(height(node.right.left) - height(node.right.right) > 0) { + // left right case + node.right = rightRotate(node.right); + return leftRotate(node); + } + } + + return node; + } + + public Node rightRotate(Node p) { + Node c = p.left; + Node t = c.right; + + c.right = p; + p.left = t; + + p.height = Math.max(height(p.left), height(p.right) + 1); + c.height = Math.max(height(c.left), height(c.right) + 1); + + return c; + } + + public Node leftRotate(Node c) { + Node p = c.right; + Node t = p.left; + + p.left = c; + c.right = t; + + p.height = Math.max(height(p.left), height(p.right) + 1); + c.height = Math.max(height(c.left), height(c.right) + 1); + + return p; + } + + public void populate(int[] nums) { + for (int i = 0; i < nums.length; i++) { + this.insert(nums[i]); + } + } + + public void populatedSorted(int[] nums) { + populatedSorted(nums, 0, nums.length); + } + + private void populatedSorted(int[] nums, int start, int end) { + if (start >= end) { + return; + } + + int mid = (start + end) / 2; + + this.insert(nums[mid]); + populatedSorted(nums, start, mid); + populatedSorted(nums, mid + 1, end); + } + + public void display() { + display(this.root, "Root Node: "); + } + + private void display(Node node, String details) { + if (node == null) { + return; + } + System.out.println(details + node.value); + display(node.left, "Left child of " + node.value + " : "); + display(node.right, "Right child of " + node.value + " : "); + } + + public boolean isEmpty() { + return root == null; + } + + public boolean balanced() { + return balanced(root); + } + + private boolean balanced(Node node) { + if (node == null) { + return true; + } + return Math.abs(height(node.left) - height(node.right)) <= 1 && balanced(node.left) && balanced(node.right); + } + +} \ No newline at end of file diff --git a/lectures/20-trees/code/AVL/Main.java b/lectures/20-trees/code/AVL/Main.java new file mode 100644 index 000000000..596bd9902 --- /dev/null +++ b/lectures/20-trees/code/AVL/Main.java @@ -0,0 +1,11 @@ +class Main { + public static void main(String[] args) { + AVL tree = new AVL(); + + for(int i=0; i < 1000; i++) { + tree.insert(i); + } + + System.out.println(tree.height()); + } +} \ No newline at end of file diff --git a/lectures/20-trees/code/Advance questions/DoubleLinkedList.java b/lectures/20-trees/code/Advance questions/DoubleLinkedList.java new file mode 100644 index 000000000..a717c51ed --- /dev/null +++ b/lectures/20-trees/code/Advance questions/DoubleLinkedList.java @@ -0,0 +1,57 @@ +public class DoubleLinkedList { + LLNode head; + LLNode tail; + + public TreeNode convert(TreeNode root) { + if (root == null) { + return null; + } + + helper(root); + + return head; + } + + private void helper(TreeNode node) { + if(node == null) { + return null; + } + + helper(node.left); + + + LLNode newNode = new LLNode(node.val); + + if(head == null) { + head = newNode; + tail = newNode; + } else { + tail.next = newNode; + newNode.prev = tail; + tail = newNode; + } + + helper(node.right); + + } +} + +class LLNode { + int val; + LLNode prev; + LLNode next; + + public LLNode (int val) { + this.val = val; + } +} + +class TreeNode { + int val; + TreeNode left; + TreeNode right; + + public TreeNode (int val) { + this.val = val; + } +} diff --git a/lectures/20-trees/code/Advance questions/KthSmallest.java b/lectures/20-trees/code/Advance questions/KthSmallest.java new file mode 100644 index 000000000..e87e75b6e --- /dev/null +++ b/lectures/20-trees/code/Advance questions/KthSmallest.java @@ -0,0 +1,25 @@ +class KthSmallest { + public int kthSmallest(TreeNode root, int k) { + PriorityQueue minHeap = new PriorityQueue<>(); + helper(root, minHeap, k); + + // remove k elements + int ans = 0; + for(int i=0; i minHeap, int k) { + if (node == null) { + return; + } + + helper(node.left, minHeap, k); + + minHeap.offer(node.val); + + helper(node.right, minHeap, k); + } +} \ No newline at end of file diff --git a/lectures/20-trees/code/Advance questions/KthSmallest2.java b/lectures/20-trees/code/Advance questions/KthSmallest2.java new file mode 100644 index 000000000..3ae8eb0df --- /dev/null +++ b/lectures/20-trees/code/Advance questions/KthSmallest2.java @@ -0,0 +1,26 @@ +class KthSmallest { + private int k; + private int ans; + + public int kthSmallest(TreeNode root, int k) { + this.k = k; + helper(root); + return ans; + } + + private void helper(TreeNode node) { + if (node == null) { + return; + } + + helper(node.left); + + k--; + if(k==0) { + ans = node.val; + return; + } + + helper(node.right); + } +} \ No newline at end of file diff --git a/lectures/20-trees/code/Advance questions/Main.java b/lectures/20-trees/code/Advance questions/Main.java new file mode 100644 index 000000000..0b4de6ee8 --- /dev/null +++ b/lectures/20-trees/code/Advance questions/Main.java @@ -0,0 +1,5 @@ +class Main { + public static void main(String[] args) { + + } +} \ No newline at end of file diff --git a/lectures/20-trees/code/Advance questions/PreIn.java b/lectures/20-trees/code/Advance questions/PreIn.java new file mode 100644 index 000000000..3946af2c1 --- /dev/null +++ b/lectures/20-trees/code/Advance questions/PreIn.java @@ -0,0 +1,34 @@ +class PreIn { + + public TreeNode buildTree(int[] preOrder, int[] inOrder) { + HashMap map = new HashMap<>(); + + for(int i=0; i < inOrder.length; i++) { + map.put(inOrder[i], i); + } + + int[] index = {0}; + + return helper(preOrder, inOrder, 0, preOrder.length-1, map, index); + } + + public TreeNode helper(int[] preOrder, int[] inOrder, int left, int right, HashMap map, int[] index) { + if (left > right) { + return null; + } + + int current = preOrder[index[0]]; + index[0]++; + + TreeNode node = new TreeNode(current); + + if (left == right) { + return node; + } + + node.left = helper(preOrder, inOrder, left, index - 1, map, index); + node.right = helper(preOrder, inOrder, index + 1, right, map, index); + + return node; + } +} \ No newline at end of file diff --git a/lectures/20-trees/code/Advance questions/TwoNodeSwap.java b/lectures/20-trees/code/Advance questions/TwoNodeSwap.java new file mode 100644 index 000000000..6394d38b0 --- /dev/null +++ b/lectures/20-trees/code/Advance questions/TwoNodeSwap.java @@ -0,0 +1,53 @@ +import java.util.*; + +class Node { + int val; + Node left; + Node right; + public Node (int val) { + this.val = val; + } +} + +public class TwoNodeSwap { + Node first; + Node second; + Node prev; + + public void helper(Node root) { + iot(root); + + // swap + int temp = first.val; + first.val = second.val; + second.val = temp; + } + + private void iot(Node node) { + if(node == null) { + return; + } + + iot(node.left); + + if(prev != null && prev.val > node.val) { + if(first == null) { + first = prev; + } + second = node; + } + + prev = node; + + iot(node.right); + } + + public void printIOT(Node node) { + if(node == null) { + return; + } + printIOT(node.left); + System.out.print(node.val + " "); + printIOT(node.right); + } +} \ No newline at end of file diff --git a/lectures/20-trees/code/Advance questions/TwoSum.java b/lectures/20-trees/code/Advance questions/TwoSum.java new file mode 100644 index 000000000..40add1aad --- /dev/null +++ b/lectures/20-trees/code/Advance questions/TwoSum.java @@ -0,0 +1,17 @@ +class TwoSum { + public boolean findTarget(TreeNode root, int k) { + HashSet set = new HashSet<>(); + return helper(root, k, set); + } + private boolean helper(TreeNode node, int k, HashSet set) { + if(node == null) { + return false; + } + if(set.contains(k - node.val)) { + return true; + } + + set.add(node.val); + return helper(node.left, k, set) || helper(node.right, k , set); + } +} \ No newline at end of file diff --git a/lectures/20-trees/code/Advance questions/VerticalTraversal.java b/lectures/20-trees/code/Advance questions/VerticalTraversal.java new file mode 100644 index 000000000..64734a4f5 --- /dev/null +++ b/lectures/20-trees/code/Advance questions/VerticalTraversal.java @@ -0,0 +1,45 @@ +class VerticalTraversal { + public List> verticalTraversal(TreeNode node) { + List> ans = new ArrayList>(); + + if (node == null) { + return ans; + } + + int col = 0; + + Queue> queue = new ArrayDeque<>(); + Map> map = new HashMap(); + + queue.offer(new AbstractMap.SimpleEntry<>(node, col)); + + int min = 0; + int max = 0; + + while(!queue.isEmpty()) { + Map.Entry removed = queue.poll(); + node = removed.getKey(); + col = removed.getValue(); + + if(node != null) { + if(!map.containsKey(col)) { + map.put(col, new ArrayList()); + } + + map.get(col).add(node.val); + + min = Math.min(min, col); + max = Math.max(max, col); + + queue.offer(new AbstractMap.SimpleEntry<>(node.left, col-1)); + queue.offer(new AbstractMap.SimpleEntry<>(node.right, col+1)); + } + } + + for(int i=min; i <= max; i++) { + ans.add(map.get(i)); + } + + return ans; + } +} \ No newline at end of file diff --git a/lectures/20-trees/code/Advance questions/WordLadder.java b/lectures/20-trees/code/Advance questions/WordLadder.java new file mode 100644 index 000000000..c995e85cb --- /dev/null +++ b/lectures/20-trees/code/Advance questions/WordLadder.java @@ -0,0 +1,39 @@ +public class WordLadder { + public static int ladderLength(String beginWord, String endWord, List wordList) { + if (!wordList.contains(endWord)) + return 0; + + Set visited = new HashSet<>(); + Queue q = new LinkedList<>(); + q.offer(beginWord); + int length = 0; + + while (!q.isEmpty()) { + int size = q.size(); + length++; + + for (int i = 0; i < size; i++) { + String current = q.poll(); + + for (int j = 0; j < current.length(); j++) { + char[] temp = current.toCharArray(); + + for (char c = 'a'; c <= 'z'; c++) { + temp[j] = c; + String newWord = new String(temp); + + if (newWord.equals(endWord)) + return length + 1; + + if (wordList.contains(newWord) && !visited.contains(newWord)) { + q.offer(newWord); + visited.add(newWord); + } + } + } + } + } + + return 0; + } +} \ No newline at end of file diff --git a/lectures/20-trees/code/Questions/.breakpoints b/lectures/20-trees/code/Questions/.breakpoints new file mode 100644 index 000000000..5cc232f02 --- /dev/null +++ b/lectures/20-trees/code/Questions/.breakpoints @@ -0,0 +1,3 @@ +{ + "files": {} +} \ No newline at end of file diff --git a/lectures/20-trees/code/Questions/.cache/replit/__replit_disk_meta.json b/lectures/20-trees/code/Questions/.cache/replit/__replit_disk_meta.json new file mode 100644 index 000000000..a184cbc47 --- /dev/null +++ b/lectures/20-trees/code/Questions/.cache/replit/__replit_disk_meta.json @@ -0,0 +1 @@ +{"nonce":230126823490474653,"last_updated":{"seconds":1693514001,"nanos":185075000}} diff --git a/lectures/20-trees/code/Questions/.cache/replit/modules.stamp b/lectures/20-trees/code/Questions/.cache/replit/modules.stamp new file mode 100644 index 000000000..c39d1108c --- /dev/null +++ b/lectures/20-trees/code/Questions/.cache/replit/modules.stamp @@ -0,0 +1 @@ +2jmj7l5rSw0yVb_vlWAYkK_YBwk= \ No newline at end of file diff --git a/lectures/20-trees/code/Questions/.cache/replit/nix/env.json b/lectures/20-trees/code/Questions/.cache/replit/nix/env.json new file mode 100644 index 000000000..1464b456a --- /dev/null +++ b/lectures/20-trees/code/Questions/.cache/replit/nix/env.json @@ -0,0 +1 @@ +{"entries":{"replit.nix":{"env":{"AR":"ar","AS":"as","CC":"gcc","CONFIG_SHELL":"/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin/bash","CXX":"g++","HOST_PATH":"/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/bin:/nix/store/6z9ag3ihc8mq2hzsw48lhbznvzny65nz-apache-maven-3.8.6/bin:/nix/store/a7s9klvriqi68xz3qjc0qyfl5h86xc16-jdt-language-server-1.9.0/bin:/nix/store/48ifl2w60a3zp7yskbpnvn8jp9jdsb7k-java-debug/bin:/nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1/bin:/nix/store/mydc6f4k2z73xlcz7ilif3v2lcaiqvza-findutils-4.9.0/bin:/nix/store/j9p3g8472iijd50vhdprx0nmk2fqn5gv-diffutils-3.8/bin:/nix/store/89zs7rms6x00xfq4dq6m7mjnhkr8a6r4-gnused-4.8/bin:/nix/store/86bp03jkmsl6f92w0yzg4s59g5mhxwmy-gnugrep-3.7/bin:/nix/store/hwcdqw4jrjnd37wxqgsd47hd0j8bnj09-gawk-5.1.1/bin:/nix/store/cfbhw8r8ags41vwqaz47r583d0p4h4a1-gnutar-1.34/bin:/nix/store/p3m1ndl1lapwrlh698bnb5lvvxh67378-gzip-1.12/bin:/nix/store/a8mhcagrsly7c7mpjrpsnaahk4aax056-bzip2-1.0.8-bin/bin:/nix/store/mblgz65m3zv9x548a3d5m96fj2pbwr09-gnumake-4.3/bin:/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin:/nix/store/v7ljksji50mg3w61dykaa3n3y79n6nil-patch-2.7.6/bin:/nix/store/zlcnmqq14jz5x9439jf937mvayyl63da-xz-5.2.7-bin/bin:/nix/store/y6aj732zm9m87c82fpvf103a1xb22blp-file-5.43/bin","JAVA_HOME":"/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0","LD":"ld","LOCALE_ARCHIVE":"/usr/lib/locale/locale-archive","NIX_BINTOOLS":"/nix/store/1d6ian3r8kdzspw8hacjhl3xkp40g1lj-binutils-wrapper-2.39","NIX_BINTOOLS_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu":"1","NIX_BUILD_CORES":"16","NIX_BUILD_TOP":"/tmp","NIX_CC":"/nix/store/dq0xwmsk1g0i2ayg6pb7y87na2knzylh-gcc-wrapper-11.3.0","NIX_CC_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu":"1","NIX_CFLAGS_COMPILE":" -frandom-seed=jzy97cgd5n -isystem /nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/include -isystem /nix/store/0y971q54v6jm9ss243xhl4y0gnlsm9c8-zlib-1.2.13-dev/include -isystem /nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/include -isystem /nix/store/0y971q54v6jm9ss243xhl4y0gnlsm9c8-zlib-1.2.13-dev/include","NIX_ENFORCE_NO_NATIVE":"1","NIX_HARDENING_ENABLE":"fortify stackprotector pic strictoverflow format relro bindnow","NIX_INDENT_MAKE":"1","NIX_LDFLAGS":"-rpath /nix/store/jzy97cgd5naxlaqsllsvchv882ihalp4-nix-shell/lib64 -rpath /nix/store/jzy97cgd5naxlaqsllsvchv882ihalp4-nix-shell/lib -L/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/lib -L/nix/store/026hln0aq1hyshaxsdvhg0kmcm6yf45r-zlib-1.2.13/lib -L/nix/store/2h0a1ma7bp2vprkmh6n4n2k1hcn1z0x8-graalvm17-ce-22.3.0-lib/lib -L/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/lib -L/nix/store/026hln0aq1hyshaxsdvhg0kmcm6yf45r-zlib-1.2.13/lib -L/nix/store/2h0a1ma7bp2vprkmh6n4n2k1hcn1z0x8-graalvm17-ce-22.3.0-lib/lib","NIX_STORE":"/nix/store","NM":"nm","OBJCOPY":"objcopy","OBJDUMP":"objdump","PATH":"/nix/store/bap4d0lpcrhpwmpb8ayjcgkmvfj62lnq-bash-interactive-5.1-p16/bin:/nix/store/pr5n59mb4jzmfx6kanwxly0l07p861fg-patchelf-0.15.0/bin:/nix/store/dq0xwmsk1g0i2ayg6pb7y87na2knzylh-gcc-wrapper-11.3.0/bin:/nix/store/1gf2flfqnpqbr1b4p4qz2f72y42bs56r-gcc-11.3.0/bin:/nix/store/57xv61c5zi8pphjbcwxxjlgc34p61ic9-glibc-2.35-163-bin/bin:/nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1/bin:/nix/store/1d6ian3r8kdzspw8hacjhl3xkp40g1lj-binutils-wrapper-2.39/bin:/nix/store/039g378vc3pc3dvi9dzdlrd0i4q93qwf-binutils-2.39/bin:/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/bin:/nix/store/6z9ag3ihc8mq2hzsw48lhbznvzny65nz-apache-maven-3.8.6/bin:/nix/store/a7s9klvriqi68xz3qjc0qyfl5h86xc16-jdt-language-server-1.9.0/bin:/nix/store/48ifl2w60a3zp7yskbpnvn8jp9jdsb7k-java-debug/bin:/nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1/bin:/nix/store/mydc6f4k2z73xlcz7ilif3v2lcaiqvza-findutils-4.9.0/bin:/nix/store/j9p3g8472iijd50vhdprx0nmk2fqn5gv-diffutils-3.8/bin:/nix/store/89zs7rms6x00xfq4dq6m7mjnhkr8a6r4-gnused-4.8/bin:/nix/store/86bp03jkmsl6f92w0yzg4s59g5mhxwmy-gnugrep-3.7/bin:/nix/store/hwcdqw4jrjnd37wxqgsd47hd0j8bnj09-gawk-5.1.1/bin:/nix/store/cfbhw8r8ags41vwqaz47r583d0p4h4a1-gnutar-1.34/bin:/nix/store/p3m1ndl1lapwrlh698bnb5lvvxh67378-gzip-1.12/bin:/nix/store/a8mhcagrsly7c7mpjrpsnaahk4aax056-bzip2-1.0.8-bin/bin:/nix/store/mblgz65m3zv9x548a3d5m96fj2pbwr09-gnumake-4.3/bin:/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin:/nix/store/v7ljksji50mg3w61dykaa3n3y79n6nil-patch-2.7.6/bin:/nix/store/zlcnmqq14jz5x9439jf937mvayyl63da-xz-5.2.7-bin/bin:/nix/store/y6aj732zm9m87c82fpvf103a1xb22blp-file-5.43/bin","RANLIB":"ranlib","READELF":"readelf","SIZE":"size","SOURCE_DATE_EPOCH":"315532800","STRINGS":"strings","STRIP":"strip","XDG_DATA_DIRS":"/nix/store/pr5n59mb4jzmfx6kanwxly0l07p861fg-patchelf-0.15.0/share","_":"/nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1/bin/env","__ETC_PROFILE_SOURCED":"1","buildInputs":"/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0 /nix/store/6z9ag3ihc8mq2hzsw48lhbznvzny65nz-apache-maven-3.8.6 /nix/store/a7s9klvriqi68xz3qjc0qyfl5h86xc16-jdt-language-server-1.9.0 /nix/store/48ifl2w60a3zp7yskbpnvn8jp9jdsb7k-java-debug","buildPhase":"echo \"------------------------------------------------------------\" \u003e\u003e$out\necho \" WARNING: the existence of this path is not guaranteed.\" \u003e\u003e$out\necho \" It is an internal implementation detail for pkgs.mkShell.\" \u003e\u003e$out\necho \"------------------------------------------------------------\" \u003e\u003e$out\necho \u003e\u003e $out\n# Record all build inputs as runtime dependencies\nexport \u003e\u003e $out\n","builder":"/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin/bash","cmakeFlags":"","configureFlags":"","depsBuildBuild":"","depsBuildBuildPropagated":"","depsBuildTarget":"","depsBuildTargetPropagated":"","depsHostHost":"","depsHostHostPropagated":"","depsTargetTarget":"","depsTargetTargetPropagated":"","doCheck":"","doInstallCheck":"","mesonFlags":"","name":"nix-shell","nativeBuildInputs":"","out":"/nix/store/jzy97cgd5naxlaqsllsvchv882ihalp4-nix-shell","outputs":"out","patches":"","phases":"buildPhase","propagatedBuildInputs":"","propagatedNativeBuildInputs":"","shell":"/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin/bash","shellHook":"","stdenv":"/nix/store/kmfaajdpyyyg319vfqni5jm9wkxjmf73-stdenv-linux","strictDeps":"","system":"x86_64-linux"},"dependencies":[{"path":"replit.nix","mod_time":"2023-05-12T19:41:48.477539597Z"}],"channel":"stable-22_11","channel_nix_path":"/nix/store/g2zwsf4i26pngib77ask4m00n9pj2a03-nixpkgs-stable-22_11-22.11.tar.gz/nixpkgs-stable-22_11"}}} \ No newline at end of file diff --git a/lectures/20-trees/code/Questions/.classpath b/lectures/20-trees/code/Questions/.classpath new file mode 100644 index 000000000..75b806fd7 --- /dev/null +++ b/lectures/20-trees/code/Questions/.classpath @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lectures/20-trees/code/Questions/.project b/lectures/20-trees/code/Questions/.project new file mode 100644 index 000000000..a2380fe36 --- /dev/null +++ b/lectures/20-trees/code/Questions/.project @@ -0,0 +1,34 @@ + + + myartifactid + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + + + 1679078569810 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + + diff --git a/lectures/20-trees/code/Questions/.replit b/lectures/20-trees/code/Questions/.replit new file mode 100644 index 000000000..48e2be7d3 --- /dev/null +++ b/lectures/20-trees/code/Questions/.replit @@ -0,0 +1,63 @@ +compile = "javac -classpath .:target/dependency/* -d . $(find . -type f -name '*.java')" +run = "java -classpath .:target/dependency/* Main" +entrypoint = "Main.java" +hidden = ["**/*.class"] + +[packager] +language = "java" + +[packager.features] +packageSearch = true + +[languages.java] +pattern = "**/*.java" + +[languages.java.languageServer] +start = "jdt-language-server" + +[unitTest] +language = "java" + +[nix] +channel = "stable-22_11" + +[debugger] +support = true + +[debugger.compile] +command = "javac -classpath .:/run_dir/junit-4.12.jar:target/dependency/* -g -d . $(find . -type f -name '*.java')" + +[debugger.interactive] +transport = "localhost:0" +connectTimeout = 60 +startCommand = "java-debug" + +[debugger.interactive.initializeMessage] +command = "initialize" +type = "request" + +[debugger.interactive.initializeMessage.arguments] +adapterID = "cppdbg" +clientID = "replit" +clientName = "replit.com" +columnsStartAt1 = true +linesStartAt1 = true +locale = "en-us" +pathFormat = "path" +supportsInvalidatedEvent = true +supportsProgressReporting = true +supportsRunInTerminalRequest = true +supportsVariablePaging = true +supportsVariableType = true + +[debugger.interactive.launchMessage] +command = "launch" +type = "request" + +[debugger.interactive.launchMessage.arguments] +classPaths = ["."] +mainClass = "Main" + +[deployment] +build = "javac -classpath .:target/dependency/* -d . $(find . -type f -name '*.java')" +run = "java -classpath .:target/dependency/* Main" \ No newline at end of file diff --git a/lectures/20-trees/code/Questions/.settings/org.eclipse.jdt.apt.core.prefs b/lectures/20-trees/code/Questions/.settings/org.eclipse.jdt.apt.core.prefs new file mode 100644 index 000000000..d4313d4b2 --- /dev/null +++ b/lectures/20-trees/code/Questions/.settings/org.eclipse.jdt.apt.core.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.apt.aptEnabled=false diff --git a/lectures/20-trees/code/Questions/.settings/org.eclipse.jdt.core.prefs b/lectures/20-trees/code/Questions/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..ac8e7500c --- /dev/null +++ b/lectures/20-trees/code/Questions/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,9 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore +org.eclipse.jdt.core.compiler.processAnnotations=disabled +org.eclipse.jdt.core.compiler.release=disabled +org.eclipse.jdt.core.compiler.source=1.5 diff --git a/lectures/20-trees/code/Questions/.settings/org.eclipse.m2e.core.prefs b/lectures/20-trees/code/Questions/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 000000000..f897a7f1c --- /dev/null +++ b/lectures/20-trees/code/Questions/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/lectures/20-trees/code/Questions/.upm/store.json b/lectures/20-trees/code/Questions/.upm/store.json new file mode 100644 index 000000000..c0ec20343 --- /dev/null +++ b/lectures/20-trees/code/Questions/.upm/store.json @@ -0,0 +1 @@ +{"version":2,"languages":{"java-maven":{"specfileHash":"3ff69d18804bae1a389cb7ea263f0c5b","lockfileHash":"3ff69d18804bae1a389cb7ea263f0c5b"}}} diff --git a/lectures/20-trees/code/Questions/BFS.java b/lectures/20-trees/code/Questions/BFS.java new file mode 100644 index 000000000..0cb705dd7 --- /dev/null +++ b/lectures/20-trees/code/Questions/BFS.java @@ -0,0 +1,261 @@ +class BFS { + public List> levelOrder(TreeNode root) { + List> result = new ArrayList<>(); + + if (root == null) { + return result; + } + + Queue queue = new LinkedList<>(); + queue.offer(root); + + while (!queue.isEmpty()) { + int levelSize = queue.size(); + List currentLevel = new ArrayList<>(levelSize); + for (int i=0; i < levelSize; i++) { + TreeNode currentNode = queue.poll(); + currentLevel.add(currentNode.val); + if (currentNode.left != null) { + queue.offer(currentNode.left); + } + if (currentNode.right != null) { + queue.offer(currentNode.right); + } + } + result.add(currentLevel); + } + return result; + } + + public List rightSideView(TreeNode root) { + List result = new ArrayList<>(); + + if (root == null) { + return result; + } + + Queue queue = new LinkedList<>(); + queue.offer(root); + + while (!queue.isEmpty()) { + int levelSize = queue.size(); + + for (int i=0; i < levelSize; i++) { + TreeNode currentNode = queue.poll(); + + if (i == levelSize - 1) { + result.add(currentNode.val); + } + + if (currentNode.left != null) { + queue.offer(currentNode.left); + } + if (currentNode.right != null) { + queue.offer(currentNode.right); + } + } + } + return result; + } + + public List averageOfLevels(TreeNode root) { + List result = new ArrayList<>(); + + if (root == null) { + return result; + } + + Queue queue = new LinkedList<>(); + queue.offer(root); + + while (!queue.isEmpty()) { + int levelSize = queue.size(); + double averageLevel = 0; + for (int i=0; i < levelSize; i++) { + TreeNode currentNode = queue.poll(); + averageLevel += currentNode.val; + if (currentNode.left != null) { + queue.offer(currentNode.left); + } + if (currentNode.right != null) { + queue.offer(currentNode.right); + } + } + averageLevel = averageLevel / levelSize; + result.add(averageLevel); + } + return result; + } + + public TreeNode findSuccessor(TreeNode root, int key){ + if (root == null) { + return null; + } + + Queue queue = new LinkedList<>(); + queue.offer(root); + + while (!queue.isEmpty()) { + int levelSize = queue.size(); + TreeNode currentNode = queue.poll(); + if (currentNode.left != null) { + queue.offer(currentNode.left); + } + if (currentNode.right != null) { + queue.offer(currentNode.right); + } + if (currentNode.val = key) { + break; + } + } + return queue.peek(); + } + + public List> zigzagLevelOrder(TreeNode root) { + List> result = new ArrayList<>(); + + if (root == null) { + return result; + } + + Deque queue = new LinkedList<>(); + queue.add(root); + + boolean reverse = false; + + while (!queue.isEmpty()) { + int levelSize = queue.size(); + List currentLevel = new ArrayList<>(levelSize); + for (int i=0; i < levelSize; i++) { + if (!reverse) { + TreeNode currentNode = queue.pollFirst(); + currentLevel.add(currentNode.val); + if (currentNode.left != null) { + queue.addLast(currentNode.left); + } + if (currentNode.right != null) { + queue.addLast(currentNode.right); + } + } else { + TreeNode currentNode = queue.pollLast(); + currentLevel.add(currentNode.val); + if (currentNode.right != null) { + queue.addFirst(currentNode.right); + } + if (currentNode.left != null) { + queue.addFirst(currentNode.left); + } + } + } + reverse = !reverse; + result.add(currentLevel); + } + return result; + } + + + public Node connect(Node root) { + if (root == null){ + return null; + } + + Node leftMost = root; + + while (leftMost.left != null) { + Node current = leftMost; + while(current != null) { + current.left.next = current.right; + if(current.next != null) { + current.right.next = current.next.left; + } + current = current.next; + } + leftMost = leftMost.left; + } + return root; + } + + + public boolean isCousins(TreeNode root, int x, int y) { + TreeNode xx = findNode(root, x); + TreeNode yy = findNode(root, y); + + return ( + (level(root, xx, 0) == level(root, yy, 0)) && (!isSibling(root, xx, yy)) + ); + } + + TreeNode findNode(TreeNode node, int x) { + if (node == null) { + return null; + } + if (node.val == x) { + return node; + } + TreeNode n = findNode(node.left, x); + if (n != null) { + return n; + } + return findNode(node.right, x); + } + + boolean isSibling (TreeNode node, TreeNode x, TreeNode y) { + if (node == null) { + return false; + } + + return ( + (node.left == x && node.right == y) || (node.left == y && node.right == x) + || isSibling(node.left, x, y) || isSibling(node.right, x, y) + ); + } + + int level (TreeNode node, TreeNode x, int lev) { + if(node == null) { + return 0; + } + + if(node == x) { + return lev; + } + + int l = level(node.left, x, lev+1); + if (l != 0) { + return l; + } + return level(node.right, x, lev+1); + } + + public boolean isSymmetric(TreeNode root) { + Queue queue = new LinkedList<>(); + queue.add(root.left); + queue.add(root.right); + + while(!queue.isEmpty()) { + TreeNode left = queue.poll(); + TreeNode right = queue.poll(); + + if(left == null && right == null) { + continue; + } + + if(left == null || right == null) { + return false;; + } + + if (left.val != right.val) { + return false; + } + + queue.add(left.left); + queue.add(right.right); + queue.add(left.right); + queue.add(right.left); + + } + return true; + } + + + +} \ No newline at end of file diff --git a/lectures/20-trees/code/Questions/DFS.java b/lectures/20-trees/code/Questions/DFS.java new file mode 100644 index 000000000..864838493 --- /dev/null +++ b/lectures/20-trees/code/Questions/DFS.java @@ -0,0 +1,167 @@ +class DFS { + + // dfs using stack + void dfsStack(Node node) { + if(node == null) { + return; + } + Stack stack = new Stack<>(); + stack.push(node); + + while(!stack.isEmpty()) { + Node removed = stack.pop(); + System.out.print(removed.val + " "); + if(removed.right != null) { + stack.push(removed.right); + } + if(removed.left != null) { + stack.push(removed.left); + } + } + } + + int diameter = 0; + public int diameterOfBinaryTree(TreeNode root) { + height(root); + return diameter-1; + } + int height(TreeNode node) { + if(node == null) { + return 0; + } + + int leftHeight = height(node.left); + int rightHeight = height(node.right); + + int dia = leftHeight + rightHeight + 1; + diameter = Math.max(diameter, dia); + + return Math.max(leftHeight, rightHeight) + 1; + + } + + + public TreeNode invertTree(TreeNode root) { + if (root == null) { + return null; + } + + TreeNode left = invertTree(root.left); + TreeNode right = invertTree(root.right); + + root.left = right; + root.right = left; + + return root; + } + + public void flatten(TreeNode root) { + TreeNode current = root; + while (current != null) { + if (current.left != null) { + TreeNode temp = current.left; + while(temp.right != null) { + temp = temp.right; + } + + temp.right = current.right; + current.right = current.left; + current.left= null; + } + current = current.right; + } + + } + + public boolean isValidBST(TreeNode root) { + return helper(root, null, null); + } + public boolean helper(TreeNode node, Integer low, Integer high) { + if (node == null) { + return true; + } + + if (low != null && node.val <= low) { + return false; + } + + if(high != null && node.val >= high) { + return false; + } + + boolean leftTree = helper(node.left, low, node.val); + boolean rightTree = helper(node.right, node.val, high); + + return leftTree && rightTree; + + } + + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root == null) { + return null; + } + + if (root == p || root == q) { + return root; + } + + TreeNode left = lowestCommonAncestor(root.left, p, q); + TreeNode right = lowestCommonAncestor(root.right, p, q); + + if (left != null && right != null) { + return root; + } + + return left == null ? right : left; + + } + + int count = 0; + public int kthSmallest(TreeNode root, int k) { + return helper(root, k).val; + } + public TreeNode helper(TreeNode root, int k) { + if (root == null) { + return null; + } + + TreeNode left = helper(root.left, k); + + if (left != null) { + return left; + } + + count++; + + if(count == k) { + return root; + } + + return helper(root.right, k); + } + + public TreeNode buildTree(int[] preorder, int[] inorder) { + + if (preorder.length == 0) { + return null; + } + + int r = pre[0]; + int index = 0; + + for(int i=0; i= arr.length || node.val != arr[index]) { + return false; + } + if(node.left == null && node.right == null && index = arr.length - 1) { + return true; + } + return helper(node.left, arr, index + 1) || helper(node.right, arr, index + 1); + } + + int countPaths(Node node, int sum) { + List path = new ArrayList<>(); + return helper(node, sum, path); + } + int helper(Node node, int sum, List path) { + if(node == null) { + return 0; + } + + path.add(node.val); + int count = 0; + int s = 0; + // how many paths I can make + ListIterator itr = path.listIterator(path.size()); + while (itr.hashPrevious()) { + s += itr.previous(); + + if (s == sum) { + count++; + } + } + + count += helper(node.left, s, path) + helper(node.right, sum, path); + + // backtrack + path.remove(path.size() - 1); + return count; + + } + + // put in a list + List> findPaths(Node node, int sum) { + List> paths = new ArrayList<>(); + List path = new ArrayList<>(); + helper(node, sum, path); + return paths; + } + void helper(Node node, int sum, List path, List> paths) { + if(node == null) { + return 0; + } + + path.add(node.val); + + if (node.val == sum && node.left == null && node.right == null) { + paths.add(new ArrayList<>(path)); + } else { + helper(node.left, sum-node.val, path, paths); + helper(node.right, sum-node.val, path, paths); + } + + // backtrack + path.remove(path.size() - 1); + } +} \ No newline at end of file diff --git a/lectures/20-trees/code/Questions/SD.java b/lectures/20-trees/code/Questions/SD.java new file mode 100644 index 000000000..5bd2a4601 --- /dev/null +++ b/lectures/20-trees/code/Questions/SD.java @@ -0,0 +1,40 @@ +// https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ + +class SD { + public List serialize(Node node) { + List list = new ArrayList<>(); + helper(node, list); + return list; + } + void helper(Node node, List list) { + if (node == null) { + list.add("null"); + return; + } + + list.add(String.valueOf(node.val)); + + helper(node.left, list); + helper(node.right, list); + } + + Node deserialize(List list) { + Collections.reverse(list); + Node node = helper2(list); + return node; + } + Node helper(List list) { + String val = list.remove(list.size() - 1); + + if (val.charAt(0) == 'n') { + return null; + } + + Node node = new Node(Integer.parseInt(val)); + + node.left = helper2(list); + node.right = helper2(list); + + return node; + } +} \ No newline at end of file diff --git a/lectures/20-trees/code/Segment trees/Main.java b/lectures/20-trees/code/Segment trees/Main.java new file mode 100644 index 000000000..523ac9c01 --- /dev/null +++ b/lectures/20-trees/code/Segment trees/Main.java @@ -0,0 +1,9 @@ +class Main { + public static void main(String[] args) { + int[] arr = {3, 8, 6, 7, -2, -8, 4, 9}; + SegmentTree tree = new SegmentTree(arr); + // tree.display(); + + System.out.println(tree.query(1, 6)); + } +} \ No newline at end of file diff --git a/lectures/20-trees/code/Segment trees/SegmentTree.java b/lectures/20-trees/code/Segment trees/SegmentTree.java new file mode 100644 index 000000000..9332fcdcf --- /dev/null +++ b/lectures/20-trees/code/Segment trees/SegmentTree.java @@ -0,0 +1,111 @@ +class SegmentTree { + + private static class Node { + int data; + int startInterval; + int endInterval; + Node left; + Node right; + + public Node (int startInterval, int endInterval) { + this.startInterval = startInterval; + this.endInterval = endInterval; + } + } + + Node root; + + public SegmentTree(int[] arr) { + // create a tree using this array + this.root = constructTree(arr, 0, arr.length - 1); + } + + private Node constructTree(int[] arr, int start, int end) { + if(start == end) { + // leaf node + Node leaf = new Node(start, end); + leaf.data = arr[start]; + return leaf; + } + + // create new node with index you are at + Node node = new Node(start, end); + + int mid = (start + end) / 2; + + node.left = this.constructTree(arr, start, mid); + node.right = this.constructTree(arr, mid + 1, end); + + node.data = node.left.data + node.right.data; + return node; + } + + public void display() { + display(this.root); + } + private void display(Node node) { + String str = ""; + + if(node.left != null) { + str = str + "Interval=[" + node.left.startInterval + "-" + node.left.endInterval + "] and data: " + node.left.data + " => "; + } else { + str = str + "No left child"; + } + + // for current node + str = str + "Interval=[" + node.startInterval + "-" + node.endInterval + "] and data: " + node.data + " <= "; + + if(node.right != null) { + str = str + "Interval=[" + node.right.startInterval + "-" + node.right.endInterval + "] and data: " + node.right.data; + } else { + str = str + "No right child"; + } + + System.out.println(str + '\n'); + + // call recursion + if(node.left != null) { + display(node.left); + } + + if(node.right != null) { + display(node.right); + } + } + + // query + public int query(int qsi, int qei) { + return this.query(this.root, qsi, qei); + } + private int query(Node node, int qsi, int qei) { + if(node.startInterval >= qsi && node.endInterval <= qei) { + // node is completely lying inside query + return node.data; + } else if (node.startInterval > qei || node.endInterval < qsi) { + // completely outside + return 0; + } else { + return this.query(node.left, qsi, qei) + this.query(node.right, qsi, qei); + } + } + + // update + public void update(int index, int value) { + this.root.data = update(this.root, index, value); + } + private int update(Node node, int index, int value) { + if (index >= node.startInterval&& index <= node.endInterval){ + if(index == node.startInterval && index == node.endInterval) { + node.data = value; + return node.data; + } else { + int leftAns = update(node.left, index, value); + int rightAns = update(node.right, index, value); + node.data = leftAns + rightAns; + return node.data; + } + } + return node.data; + } + +} \ No newline at end of file diff --git a/lectures/20-trees/code/introduction/BST.java b/lectures/20-trees/code/introduction/BST.java new file mode 100644 index 000000000..0ab0f8f6a --- /dev/null +++ b/lectures/20-trees/code/introduction/BST.java @@ -0,0 +1,102 @@ +class BST { + public class Node { + private int value; + private Node left; + private Node right; + private int height; + + public Node(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + } + + private Node root; + + public BST() { + + } + + public int height(Node node) { + if (node == null) { + return -1; + } + return node.height; + } + + public boolean isEmpty() { + return root == null; + } + + public void insert(int value) { + root = insert(value, root); + } + + private Node insert(int value, Node node) { + if (node == null) { + node = new Node(value); + return node; + } + + if (value < node.value) { + node.left = insert(value, node.left); + } + + if (value > node.value) { + node.right = insert(value, node.right); + } + + node.height = Math.max(height(node.left), height(node.right)) + 1; + return node; + } + + public void populate(int[] nums) { + for (int i = 0; i < nums.length; i++) { + this.insert(nums[i]); + } + } + + public void populatedSorted(int[] nums) { + populatedSorted(nums, 0, nums.length); + } + + private void populatedSorted(int[] nums, int start, int end) { + if (start >= end) { + return; + } + + int mid = (start + end) / 2; + + this.insert(nums[mid]); + populatedSorted(nums, start, mid); + populatedSorted(nums, mid + 1, end); + } + + public boolean balanced() { + return balanced(root); + } + + private boolean balanced(Node node) { + if (node == null) { + return true; + } + return Math.abs(height(node.left) - height(node.right)) <= 1 && balanced(node.left) && balanced(node.right); + } + + public void display() { + display(this.root, "Root Node: "); + } + + private void display(Node node, String details) { + if (node == null) { + return; + } + System.out.println(details + node.value); + display(node.left, "Left child of " + node.value + " : "); + display(node.right, "Right child of " + node.value + " : "); + } + +} \ No newline at end of file diff --git a/lectures/20-trees/code/introduction/BinaryTree.java b/lectures/20-trees/code/introduction/BinaryTree.java new file mode 100644 index 000000000..366317961 --- /dev/null +++ b/lectures/20-trees/code/introduction/BinaryTree.java @@ -0,0 +1,124 @@ +import java.util.Scanner; + +class BinaryTree { + + public BinaryTree() { + + } + + private static class Node { + int value; + Node left; + Node right; + + public Node(int value) { + this.value = value; + } + } + + private Node root; + + // insert elements + public void populate(Scanner scanner) { + System.out.println("Enter the root Node: "); + int value = scanner.nextInt(); + root = new Node(value); + populate(scanner, root); + } + + private void populate(Scanner scanner, Node node) { + System.out.println("Do you want to enter left of " + node.value); + boolean left = scanner.nextBoolean(); + if (left) { + System.out.println("Enter the value of the left of " + node.value); + int value = scanner.nextInt(); + node.left = new Node(value); + populate(scanner, node.left); + } + + System.out.println("Do you want to enter right of " + node.value); + boolean right = scanner.nextBoolean(); + if (right) { + System.out.println("Enter the value of the right of " + node.value); + int value = scanner.nextInt(); + node.right = new Node(value); + populate(scanner, node.right); + } + + } + + public void display() { + display(this.root, ""); + } + + private void display(Node node, String indent) { + if (node == null) { + return; + } + System.out.println(indent + node.value); + display(node.left, indent + "\t"); + display(node.right, indent + "\t"); + } + + public void prettyDisplay() { + prettyDisplay(root, 0); + } + + private void prettyDisplay(Node node, int level) { + if (node == null) { + return; + } + + prettyDisplay(node.right, level + 1); + + if (level != 0) { + for (int i = 0; i < level - 1; i++) { + System.out.print("|\t\t"); + } + System.out.println("|------->" + node.value); + } else { + System.out.println(node.value); + } + prettyDisplay(node.left, level + 1); + } + + public void preOrder() { + preOrder(root); + } + + private void preOrder(Node node) { + if (node == null) { + return; + } + System.out.print(node.value + " "); + preOrder(node.left); + preOrder(node.right); + } + + public void inOrder() { + preOrder(root); + } + + private void inOrder(Node node) { + if (node == null) { + return; + } + preOrder(node.left); + System.out.print(node.value + " "); + preOrder(node.right); + } + + public void postOrder() { + preOrder(root); + } + + private void postOrder(Node node) { + if (node == null) { + return; + } + preOrder(node.left); + preOrder(node.right); + System.out.print(node.value + " "); + } + +} \ No newline at end of file diff --git a/lectures/20-trees/code/introduction/Main.java b/lectures/20-trees/code/introduction/Main.java new file mode 100644 index 000000000..e46da8921 --- /dev/null +++ b/lectures/20-trees/code/introduction/Main.java @@ -0,0 +1,15 @@ +import java.util.Scanner; + +public class Main { + public static void main(String[] args) { + // Scanner scanner = new Scanner(System.in); + // BinaryTree tree = new BinaryTree(); + // tree.populate(scanner); + // tree.prettyDisplay(); + + BST tree = new BST(); + int[] nums = { 5, 2, 7, 1, 4, 6, 9, 8, 3, 10 }; + tree.populate(nums); + tree.display(); + } +} \ No newline at end of file diff --git a/lectures/20-trees/notes/Advance questions 2.pdf b/lectures/20-trees/notes/Advance questions 2.pdf new file mode 100644 index 000000000..20680687c Binary files /dev/null and b/lectures/20-trees/notes/Advance questions 2.pdf differ diff --git a/lectures/20-trees/notes/Advance questions 3.pdf b/lectures/20-trees/notes/Advance questions 3.pdf new file mode 100644 index 000000000..aac841744 Binary files /dev/null and b/lectures/20-trees/notes/Advance questions 3.pdf differ diff --git a/lectures/20-trees/notes/Advance questions.pdf b/lectures/20-trees/notes/Advance questions.pdf new file mode 100644 index 000000000..85787854b Binary files /dev/null and b/lectures/20-trees/notes/Advance questions.pdf differ diff --git a/lectures/20-trees/notes/Tree questions.pdf b/lectures/20-trees/notes/Tree questions.pdf new file mode 100644 index 000000000..bc9177127 Binary files /dev/null and b/lectures/20-trees/notes/Tree questions.pdf differ diff --git a/lectures/20-trees/notes/Trees - 1.pdf b/lectures/20-trees/notes/Trees - 1.pdf new file mode 100644 index 000000000..c1417e26e Binary files /dev/null and b/lectures/20-trees/notes/Trees - 1.pdf differ diff --git a/lectures/20-trees/notes/Trees - 2 (AVL).pdf b/lectures/20-trees/notes/Trees - 2 (AVL).pdf new file mode 100644 index 000000000..ea57aaa85 Binary files /dev/null and b/lectures/20-trees/notes/Trees - 2 (AVL).pdf differ diff --git a/lectures/20-trees/notes/Trees - 3 (Segment).pdf b/lectures/20-trees/notes/Trees - 3 (Segment).pdf new file mode 100644 index 000000000..45aa4e709 Binary files /dev/null and b/lectures/20-trees/notes/Trees - 3 (Segment).pdf differ diff --git a/lectures/21-StringBuffer/code/Main.java b/lectures/21-StringBuffer/code/Main.java new file mode 100644 index 000000000..aafb3466f --- /dev/null +++ b/lectures/21-StringBuffer/code/Main.java @@ -0,0 +1,54 @@ +import java.util.Random; +import java.util.Arrays; +import java.text.DecimalFormat; + +class Main { + public static void main(String[] args) { + // constructor 1 + StringBuffer sb = new StringBuffer(); + System.out.println(sb.capacity()); + + // constructor 2 + StringBuffer sb2 = new StringBuffer("Kunal Kushwaha"); + + // constructor 3 + StringBuffer sb3 = new StringBuffer(30); + System.out.println(sb3.capacity()); + + + sb.append("WeMakeDevs"); + sb.append(" is nice!"); + + // sb.insert(2, " Rahul "); + + sb.replace(1, 5, "Kushwaha"); + + sb.delete(1, 5); + + // sb.reverse(); + + String str = sb.toString(); + System.out.println(str); + + int n = 20; + String name = RandomString.generate(n); + System.out.println(name); + + // remove whitespaces + + String sentence = "Hi h hjh hjkso siowi w "; + System.out.println(sentence); + + System.out.println(sentence.replaceAll("\\s", "")); + + // split + + String arr = "Kunal,Apoorv,Rahul,Snehal"; + String[] names = arr.split(","); + System.out.println(Arrays.toString(names)); + + // rounding off + DecimalFormat df = new DecimalFormat("00.0000"); + System.out.println(df.format(7.29)); + } +} \ No newline at end of file diff --git a/lectures/21-StringBuffer/code/RandomString.java b/lectures/21-StringBuffer/code/RandomString.java new file mode 100644 index 000000000..89f71a15a --- /dev/null +++ b/lectures/21-StringBuffer/code/RandomString.java @@ -0,0 +1,16 @@ +import java.util.Random; + +class RandomString { + static String generate(int size) { + StringBuffer sb = new StringBuffer(size); + + Random random = new Random(); + + for (int i=0; i < size; i++) { + int randomChar = 97 + (int)(random.nextFloat() * 26); + sb.append((char)randomChar); + } + + return sb.toString(); + } +} \ No newline at end of file diff --git a/lectures/21-StringBuffer/notes/StringBuffer.pdf b/lectures/21-StringBuffer/notes/StringBuffer.pdf new file mode 100644 index 000000000..0014a3622 Binary files /dev/null and b/lectures/21-StringBuffer/notes/StringBuffer.pdf differ diff --git a/lectures/22-large numbers/code/Factorial.java b/lectures/22-large numbers/code/Factorial.java new file mode 100644 index 000000000..093bcb794 --- /dev/null +++ b/lectures/22-large numbers/code/Factorial.java @@ -0,0 +1,14 @@ +import java.math.BigInteger; + +class Factorial { + + static BigInteger fact(int num) { + BigInteger ans = new BigInteger("1"); + + for (int i=2; i<= num; i++) { + ans = ans.multiply(BigInteger.valueOf(i)); + } + + return ans; + } +} \ No newline at end of file diff --git a/lectures/22-large numbers/code/Main.java b/lectures/22-large numbers/code/Main.java new file mode 100644 index 000000000..f9972657d --- /dev/null +++ b/lectures/22-large numbers/code/Main.java @@ -0,0 +1,66 @@ +import java.math.BigInteger; +import java.math.BigDecimal; + +class Main { + public static void main(String[] args) { + BD(); + } + + static void BD() { + double x = 0.03; + double y= 0.04; + // double ans = y-x; + // System.out.println(ans); + + BigDecimal X = new BigDecimal("0.03"); + BigDecimal Y = new BigDecimal("0.04"); + BigDecimal ans = Y.subtract(X); + // System.out.println(ans); + + BigDecimal a = new BigDecimal("456576345675.4546376"); + BigDecimal b = new BigDecimal("547634565352.986785764"); + + // operations + System.out.println(b.add(a)); + System.out.println(b.subtract(a)); + System.out.println(b.multiply(a)); + System.out.println(b.pow(2)); + System.out.println(b.negate()); + + // constants + BigDecimal con = BigDecimal.ONE; + + } + + + static void BI() { + int a = 30; + int b = 67; + + BigInteger B = BigInteger.valueOf(6); // convert int/long to BI + int c = B.intValue(); // convert BI to int + BigInteger C = new BigInteger("2345678654325678976543256789"); + BigInteger X = new BigInteger("4536789765432"); + + // constants + BigInteger D = BigInteger.TEN; + + // operations + BigInteger s = C.add(X); + + BigInteger m = C.multiply(X); + + BigInteger sub = C.subtract(X); + + BigInteger d = C.divide(X); + + BigInteger rem = C.remainder(X); + + if (X.compareTo(C) < 0) { + System.out.println("Yes"); + } + + System.out.println(Factorial.fact(100)); + } + +} \ No newline at end of file diff --git a/lectures/22-large numbers/notes/LargeNumbers.pdf b/lectures/22-large numbers/notes/LargeNumbers.pdf new file mode 100644 index 000000000..ee66ffb87 Binary files /dev/null and b/lectures/22-large numbers/notes/LargeNumbers.pdf differ diff --git a/lectures/23-file handling/code/Input.java b/lectures/23-file handling/code/Input.java new file mode 100644 index 000000000..de2387d52 --- /dev/null +++ b/lectures/23-file handling/code/Input.java @@ -0,0 +1,45 @@ +import java.io.*; + +class Input { + static void input() { + try (InputStreamReader isr = new InputStreamReader(System.in)) { + System.out.print("Enter some letters:"); + int letters = isr.read(); + while(isr.ready()) { + System.out.println((char) letters); + letters = isr.read(); + } + // isr.close(); + System.out.println(); + } catch (IOException e) { + System.out.println(e.getMessage()); + } + + try (FileReader fr = new FileReader("note.txt")) { + int letters = fr.read(); + while(fr.ready()) { + System.out.println((char)letters); + letters = fr.read(); + } + // fr.close(); + System.out.println(); + } catch (IOException e) { + System.out.println(e.getMessage()); + } + + // byte to char stream and then reading char stream + try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { + System.out.println("You typed: " + br.readLine()); + } catch (IOException e) { + System.out.println(e.getMessage()); + } + + try (BufferedReader br = new BufferedReader(new FileReader("note.txt"))) { + while (br.ready()) { + System.out.println(br.readLine()); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } +} \ No newline at end of file diff --git a/lectures/23-file handling/code/Main.java b/lectures/23-file handling/code/Main.java new file mode 100644 index 000000000..a7e59b3a9 --- /dev/null +++ b/lectures/23-file handling/code/Main.java @@ -0,0 +1,48 @@ +import java.io.*; +import java.io.IOException; +import java.util.Scanner; + +class Main { + public static void main(String[] args) { + + // create + try { + File fo = new File("new-file.txt"); + fo.createNewFile(); + } catch (IOException e) { + System.out.println(e.getMessage()); + } + + // write in the file + try { + FileWriter fw = new FileWriter("new-file.txt"); + fw.write("सर्वधर्मान्परित्यज्य मामेकं शरणं व्रज, अहं त्वां सर्वपापेभ्यो मोक्षयिष्यामि मा शुच:"); + fw.close(); + } catch (IOException e) { + System.out.println(e.getMessage()); + } + + // reading from a file + try (BufferedReader br = new BufferedReader(new FileReader("new-file.txt"))) { + while (br.ready()) { + System.out.println(br.readLine()); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + + // create + try { + File fo = new File("random.txt"); + fo.createNewFile(); + if(fo.delete()) { + System.out.println(fo.getName()); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + + + + } +} \ No newline at end of file diff --git a/lectures/23-file handling/code/Output.java b/lectures/23-file handling/code/Output.java new file mode 100644 index 000000000..6dbe68302 --- /dev/null +++ b/lectures/23-file handling/code/Output.java @@ -0,0 +1,34 @@ +import java.io.*; + +class Output { + static void output() { + // output + OutputStream os = System.out; + // os.write(😍); // range is exceeded + + try (OutputStreamWriter osw = new OutputStreamWriter(System.out)) { + osw.write("Hello World"); + osw.write(97); + osw.write(10); + osw.write('A'); + osw.write('\n'); + char[] arr = "hello world".toCharArray(); + osw.write(arr); + // osw.write(😍); + } catch (IOException e) { + System.out.println(e.getMessage()); + } + + try (FileWriter fw = new FileWriter("note.txt", true)) { + fw.write("this should be appended"); + } catch (IOException e) { + System.out.println(e.getMessage()); + } + + try (BufferedWriter bw = new BufferedWriter(new FileWriter("note.txt"))) { + bw.write("Hare Krishna"); + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } +} \ No newline at end of file diff --git a/lectures/23-file handling/code/new-file.txt b/lectures/23-file handling/code/new-file.txt new file mode 100644 index 000000000..0b2cc7f20 --- /dev/null +++ b/lectures/23-file handling/code/new-file.txt @@ -0,0 +1 @@ +सर्वधर्मान्परित्यज्य मामेकं शरणं व्रज, अहं त्वां सर्वपापेभ्यो मोक्षयिष्यामि मा शुच: \ No newline at end of file diff --git a/lectures/23-file handling/code/note.txt b/lectures/23-file handling/code/note.txt new file mode 100644 index 000000000..7b34bb337 --- /dev/null +++ b/lectures/23-file handling/code/note.txt @@ -0,0 +1 @@ +Hare Krishna \ No newline at end of file diff --git a/lectures/23-file handling/notes/File handling.pdf b/lectures/23-file handling/notes/File handling.pdf new file mode 100644 index 000000000..b70eef57e Binary files /dev/null and b/lectures/23-file handling/notes/File handling.pdf differ diff --git a/lectures/23-file handling/notes/notes.txt b/lectures/23-file handling/notes/notes.txt new file mode 100644 index 000000000..db89c9e13 --- /dev/null +++ b/lectures/23-file handling/notes/notes.txt @@ -0,0 +1,133 @@ +IOException : +An IOException is any unexpected problem the JVM encounters while attempting to run a program. +When an IOException is thrown, it means that whatever is throwing the exception (perhaps a try{}-catch block that reads +data from a file) can throw an IOException, for example if the file is not found, corrupted, etc, or when the file is +otherwise unable to be read, or any other of a list of issues that can occur with the IO package and it's extensions. + +Streams : +In its most basic form a stream simply represents a sequence of data (bytes or unicode characters) in some sort of a sequential queue. +Java programs perform I/O through streams. A stream is an abstraction that either produces or consumes information. +A stream is linked to a physical device by the Java I/O system. +Java implements streams within class hierarchies defined in the java.io package. +The same I/O classes and methods can be applied to different types of devices. + +Java defines two types of streams: +-Byte streams provide a convenient means for handling input and output of bytes. +Byte streams contain binary data this useful for things such as reading and writing to files - just imagine opening up an image file in a text editor, that is a good representation of byte data. +EXAMPLE : Use a byte stream ex : InputStream etc and type 'ᛞ'. This exceeds the 256 limit of 8-bit characters hence it will show some other +value. If we type 'ᛞ' in char-stream such as InputStreamReader it will show 'ᛞ' only. + + OutputStream os = System.out; + os.write('ᛞ'); // will not show anything (or garbage) cuz range exceeded. ᛞ is Unicode. + + +-Character streams provide a convenient means for handling input and output of characters. They use Unicode and, +therefore, can be internationalized, good candidate for things like keyboard input and console output. +Also, in some cases, character streams are more efficient than byte streams. + +Byte streams are defined by using two class hierarchies. +At the top are two abstract classes: InputStream and OutputStream. +Each of these abstract classes has several concrete subclasses that handle the differences among various devices, +such as disk files, network connections, and even memory buffers. +The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement. +Two of the most important methods are read( ) and write( ) + +Character streams are defined by using two class hierarchies. +At the top are two abstract classes: Reader and Writer. +Two of the most important methods are read( ) and write( ). + +The Predefined Streams : +System.out refers to the standard output stream. By default, this is the console. +System.in refers to standard input, which is the keyboard by default. +System.err refers to the standard error stream, which also is the console by default. +System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream. +These are byte streams. + +NOTE : Names of character streams typically end with Reader/Writer & names of byte streams end with InputStream/OutputStream. + +InputStreamReader Class : +EXTENDS READER : Abstract class for reading character streams. +int read() : The character read, as an integer in the range 0 to 65535 (0x00-0xffff), + or -1 if the end of the stream has been reached +Primarily it is used to convert byte streams to character streams. +java.io.InputStreamReader has several overloaded constructors with each taking an InputStream (like System.in, or FileInputStream) as the first parameter. +The InputStreamReader class has a method called close() that will close the stream and releases any system resources associated with it. +The close() method should always be called once you are done with the input stream. +In Java 7 a new feature called try-with-resources was introduced. +Specifically a resource is an object that must be closed after the program is finished with it. +The try-with-resources statement ensures that each resource is closed at the end of the statement. +How do we know if a class is a resource? Simple, if it implements java.lang.AutoCloseable, +the class can be considered a resource. + +try-with-resources : +The try-with-resources statement is a try statement that declares one or more resources. +A resource is an object that must be closed after the program is finished with it. +The try-with-resources statement ensures that each resource is closed at the end of the statement. +Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, +can be used as a resource. + +FileReader Class : +The purpose of the FileReader class is to simply read character based files. +The FileReader class implements AutoClosable so we can use the try-with-resources type exception handling. +It also interesting to note that the FileReader class does not define or override any public methods, +so it inherits all of its methods from its superclass InputStreamReader; InputStreamReader is a subclass of Reader +which is a subclass of Object and that describes the class hierarchy. + +Object -> Reader -> InputStreamReader -> FileReader + +BufferedReader Class : BufferedReader(Reader inputReader) +IT EXTENDS READER. HENCE HAS IT'S OWN read() which is same as InputStreamReader. +The BufferedReader class is used to read text from a character stream. +The BufferedReader class has the same read() method that both InputStreamReader and FileReader use to read a single byte at a time. +The BufferedReader class introduces a method named readLine() which will read an entire line of text which is a huge improvement. +The BufferedReader class implements AutoClosable so we can use the try-with-resources type exception handling. + +To obtain a character-based stream that is attached to the console, wrap System.in in a BufferedReader object. +InputStreamReader(InputStream inputStream) +BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); +NOTE : new InputStreamReader(System.in) converts byte stream into char stream. +AND then br is reading that char stream. Which is what we want! +After this statement executes, br is a character-based stream that is linked to the console through System.in. + +Writer Classes : + +OutputStreamWriter Class : +EXTENDS WRITER +Used to write to character streams. +The OutputStreamWriter class implements AutoClosable so we can use the try-with-resources type exception handling. +There are only four public methods in the OutputStreamWriter class: close(), flush(), getEncoding(), and write(). +The write() method has three overloaded versions : +-write(int a) : writes a single character to character stream. + Characters being written is contained in 16 lower bits of the ‘char’ integer value, + rest of the 16 higher bits are ignored by the method. +-write(String str) +-write(char cbuf[]) + +FileWriter Class : +EXTENDS OutputStreamWriter +The purpose of the FileWriter class is to simply write character based files. +The FileWriter class implements AutoClosable so we can use the try-with-resources type exception handling. +FileWriter class does not define or override any public methods, so it inherits all of its methods from its superclass OutputStreamWriter. + +Object -> Writer -> OutputStreamWriter -> FileWriter + +BufferedWriter Class : +The BufferedWriter class is used to write text to a character stream. +The BufferedWriter class has three overloaded versions of the write() method. +The BufferedWriter class introduces a method named newLine() which means that you will not have to hardcode in the "\r\n" into your output stream anymore. +The BufferedWriter class implements AutoClosable so we can use the try-with-resources type exception handling. + + +File Class : + +Consider this Windows hard coded path represented as a string: "c:\\Java\\BW\\Sample.txt". If a user attempted to run +your program on a Linux or UNIX OS, your program will fail miserably. That is because the directory separator is '/' in +UNIX as opposed to '\' in Windows. The file class provides us with several tools to dynamically create our directory +and file structure. + +Constructors: +File(File parent, String child) +File(String pathname) // not very useful for multi-platform +File(String parent, String child) +File(URI uri) + diff --git a/lectures/24-heaps/code/heaps-1/Heap.java b/lectures/24-heaps/code/heaps-1/Heap.java new file mode 100644 index 000000000..0c7c61325 --- /dev/null +++ b/lectures/24-heaps/code/heaps-1/Heap.java @@ -0,0 +1,85 @@ +import java.util.ArrayList; + +class Heap> { + + private ArrayList list; + + public Heap() { + list = new ArrayList<>(); + } + + private void swap(int first, int second) { + T temp = list.get(first); + list.set(first, list.get(second)); + list.set(second, temp); + } + + private int parent(int index) { + return (index - 1) / 2; + } + + private int left(int index) { + return index * 2 + 1; + } + + private int right(int index) { + return index * 2 + 2; + } + + public void insert(T value) { + list.add(value); + upheap(list.size() - 1); + } + private void upheap(int index) { + if(index == 0) { + return; + } + int p = parent(index); + if(list.get(index).compareTo(list.get(p)) < 0) { + swap(index, p); + upheap(p); + } + } + + public T remove() throws Exception { + if (list.isEmpty()) { + throw new Exception("Removing from an empty heap!"); + } + + T temp = list.get(0); + + T last = list.remove(list.size() - 1); + if (!list.isEmpty()) { + list.set(0, last); + downheap(0); + } + + return temp; + } + private void downheap(int index) { + int min = index; + int left = left(index); + int right = right(index); + + if(left < list.size() && list.get(min).compareTo(list.get(left)) > 0) { + min = left; + } + + if(right < list.size() && list.get(min).compareTo(list.get(right)) > 0) { + min = right; + } + + if(min != index) { + swap(min, index); + downheap(min); + } + } + + public ArrayList heapSort() throws Exception { + ArrayList data = new ArrayList<>(); + while(!list.isEmpty()) { + data.add(this.remove()); + } + return data; + } +} \ No newline at end of file diff --git a/lectures/24-heaps/code/heaps-1/Main.java b/lectures/24-heaps/code/heaps-1/Main.java new file mode 100644 index 000000000..0637a3650 --- /dev/null +++ b/lectures/24-heaps/code/heaps-1/Main.java @@ -0,0 +1,17 @@ +import java.util.ArrayList; + +class Main { + public static void main(String[] args) throws Exception{ + Heap heap = new Heap<>(); + + heap.insert(34); + heap.insert(45); + heap.insert(22); + heap.insert(89); + heap.insert(76); + + ArrayList list = heap.heapSort(); + System.out.println(list); + + } +} \ No newline at end of file diff --git a/lectures/24-heaps/notes/Heaps - 1.pdf b/lectures/24-heaps/notes/Heaps - 1.pdf new file mode 100644 index 000000000..4f8130689 Binary files /dev/null and b/lectures/24-heaps/notes/Heaps - 1.pdf differ diff --git a/lectures/25-hashmaps/code/Hashmaps introduction/HashMapFinal.java b/lectures/25-hashmaps/code/Hashmaps introduction/HashMapFinal.java new file mode 100644 index 000000000..36c4e7a72 --- /dev/null +++ b/lectures/25-hashmaps/code/Hashmaps introduction/HashMapFinal.java @@ -0,0 +1,119 @@ +import java.util.*; + +public class HashMapFinal { + ArrayList> list; + + private int size = 0; + + private float lf = 0.5f; + + public HashMapFinal() { + list = new ArrayList<>(); + for(int i=0; i < 10; i++) { + list.add(new LinkedList<>()); + } + } + + public void put(K key, V value) { + int hash = Math.abs(key.hashCode() % list.size()); + + LinkedList entities = list.get(hash); + + for (Entity entity : entities) { + if(entity.key.equals(key)) { + entity.value = value; + return; + } + } + + if((float)(size) / list.size() > lf) { + reHash(); + } + + entities.add(new Entity(key, value)); + + size++; + } + + private void reHash() { + System.out.println("We are now rehashing!"); + + ArrayList> old = list; + list = new ArrayList<>(); + + size = 0; + + for(int i=0; i()); + } + + for(LinkedList entries :old) { + for(Entity entry : entries) { + put(entry.key, entry.value); + } + } + } + + public V get(K key) { + int hash = Math.abs(key.hashCode() % list.size()); + LinkedList entities = list.get(hash); + for(Entity entity : entities) { + if(entity.key.equals(key)) { + return entity.value; + } + } + return null; + } + + public void remove(K key) { + int hash = Math.abs(key.hashCode() % list.size()); + LinkedList entities = list.get(hash); + + Entity target = null; + + for(Entity entity : entities) { + if(entity.key.equals(key)) { + target = entity; + break; + } + } + + entities.remove(target); + size--; + } + + public boolean containsKey(K key) { + return get(key) != null; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("{"); + for(LinkedList entities : list) { + for(Entity entity : entities) { + builder.append(entity.key); + builder.append(" = "); + builder.append(entity.value); + builder.append(" , "); + } + } + builder.append("}"); + + return builder.toString(); + } + + private class Entity { + K key; + V value; + + public Entity(K key, V value) { + this.key = key; + this.value = value; + } + } + + +} + + diff --git a/lectures/25-hashmaps/code/Hashmaps introduction/Main.java b/lectures/25-hashmaps/code/Hashmaps introduction/Main.java new file mode 100644 index 000000000..56e467013 --- /dev/null +++ b/lectures/25-hashmaps/code/Hashmaps introduction/Main.java @@ -0,0 +1,88 @@ +import java.util.*; + +class MapUsingHash { + + private Entity[] entities; + + public MapUsingHash() { + entities = new Entity[100]; + } + + public void put(String key, String value) { + int hash = Math.abs(key.hashCode() % entities.length); + entities[hash] = new Entity(key, value); // overriding + } + + public String get(String key) { + int hash = Math.abs(key.hashCode() % entities.length); + if(entities[hash] != null && entities[hash].key.equals(key)) { + return entities[hash].value; + } + return null; + } + + public void remove(String key) { + int hash = Math.abs(key.hashCode() % entities.length); + if(entities[hash] != null && entities[hash].key.equals(key)) { + entities[hash] = null; + } + } + + private class Entity { + String key; + String value; + + public Entity(String key, String value) { + this.key = key; + this.value = value; + } + } +} + + + +class Main { + public static void main(String[] args) { + // hashDemo(); + HashMapFinal map = new HashMapFinal<>(); + + map.put("Mango", "King of fruits"); + map.put("Apple", "A sweet red fruit"); + map.put("Litchi", "Kunal's fav fruit"); + + System.out.println(map); + + + } + + public static void hashDemo() { + // String name = "Rahul"; + + // Integer a = 4235678; + + // int code = a.hashCode(); + + // System.out.println(code); + + HashMap map = new HashMap<>(); + + map.put("Kunal", 89); + map.put("Karan", 99); + map.put("Rahul", 94); + + // System.out.println(map.get("Karan")); + // System.out.println(map.getOrDefault("Apoorv", 78)); + System.out.println(map.containsKey("Karan")); + + HashSet set = new HashSet<>(); + set.add(56); + set.add(9); + set.add(12); + set.add(43); + set.add(56); + set.add(2); + + System.out.println(set); + } + +} \ No newline at end of file diff --git a/lectures/25-hashmaps/code/KarpRabin/KarpRabin.java b/lectures/25-hashmaps/code/KarpRabin/KarpRabin.java new file mode 100644 index 000000000..61fa32d64 --- /dev/null +++ b/lectures/25-hashmaps/code/KarpRabin/KarpRabin.java @@ -0,0 +1,35 @@ +public class KarpRabin { + private final int PRIME = 101; + + private double calculateHash(String str) { + double hash = 0; + for(int i=0; i < str.length(); i++) { + hash += str.charAt(i) * Math.pow(PRIME, i); + } + return hash; + } + + private double updateHash(double prevHash, char oldChar, char newChar, int patternLength) { + double newHash = (prevHash - oldChar) / PRIME; + newHash = newHash + newChar * Math.pow(PRIME, patternLength - 1); + return newHash; + } + + public void search(String text, String pattern) { + int patternLength = pattern.length(); + double patternHash = calculateHash(pattern); + double textHash = calculateHash(text.substring(0, patternLength)); + + for(int i=0; i<= text.length() - patternLength; i++) { + if(textHash == patternHash) { + if(text.substring(i, i+patternLength).equals(pattern)) { + System.out.println("Pattern found at index " + i); + } + } + + if (i < text.length() - patternLength) { + textHash = updateHash(textHash, text.charAt(i), text.charAt(i + patternLength), patternLength); + } + } + } +} \ No newline at end of file diff --git a/lectures/25-hashmaps/code/KarpRabin/Main.java b/lectures/25-hashmaps/code/KarpRabin/Main.java new file mode 100644 index 000000000..fdbf81d69 --- /dev/null +++ b/lectures/25-hashmaps/code/KarpRabin/Main.java @@ -0,0 +1,6 @@ +class Main { + public static void main(String[] args) { + KarpRabin algo = new KarpRabin(); + algo.search("ApoorvKunalRahul", "Kunal"); + } +} \ No newline at end of file diff --git a/lectures/25-hashmaps/notes/Hashmaps introduction.pdf b/lectures/25-hashmaps/notes/Hashmaps introduction.pdf new file mode 100644 index 000000000..80cf2a499 Binary files /dev/null and b/lectures/25-hashmaps/notes/Hashmaps introduction.pdf differ diff --git a/lectures/25-hashmaps/notes/KarpRabin.pdf b/lectures/25-hashmaps/notes/KarpRabin.pdf new file mode 100644 index 000000000..1cbb0986b Binary files /dev/null and b/lectures/25-hashmaps/notes/KarpRabin.pdf differ diff --git a/lectures/26-advance-sorting/CountSort/CountSort.pdf b/lectures/26-advance-sorting/CountSort/CountSort.pdf new file mode 100644 index 000000000..f77225d24 Binary files /dev/null and b/lectures/26-advance-sorting/CountSort/CountSort.pdf differ diff --git a/lectures/26-advance-sorting/CountSort/Main.java b/lectures/26-advance-sorting/CountSort/Main.java new file mode 100644 index 000000000..408b2b7b1 --- /dev/null +++ b/lectures/26-advance-sorting/CountSort/Main.java @@ -0,0 +1,64 @@ +import java.util.*; + +class Main { + + public static void countSort(int[] array) { + if(array == null || array.length <= 1) { + return; + } + + int max = array[0]; + for(int num : array) { + if(num > max) { + max = num; + } + } + + int[] countArray = new int[max + 1]; + + for(int num : array) { + countArray[num]++; + } + + int index = 0; + for(int i=0; i<= max; i++) { + while(countArray[i] > 0) { + array[index] = i; + index++; + countArray[i]--; + } + } + + } + + public static void countSortHash(int[] arr) { + if(arr == null || arr.length <= 1) { + return; + } + + int max = Arrays.stream(arr).max().getAsInt(); + int min = Arrays.stream(arr).min().getAsInt(); + + Map countMap = new HashMap<>(); + + for(int num : arr) { + countMap.put(num, countMap.getOrDefault(num, 0) + 1); + } + + int index = 0; + for(int i=min; i<=max; i++) { + int count = countMap.getOrDefault(i, 0); + for(int j=0; j < count; j++) { + arr[index] = i; + index++; + } + } + + } + + public static void main(String[] args) { + int[] arr = {6, 3, 10, 9, 2, 4, 9, 7}; + countSortHash(arr); + System.out.println(Arrays.toString(arr)); + } +} \ No newline at end of file diff --git a/lectures/26-advance-sorting/RadixSort/Main.java b/lectures/26-advance-sorting/RadixSort/Main.java new file mode 100644 index 000000000..472e53591 --- /dev/null +++ b/lectures/26-advance-sorting/RadixSort/Main.java @@ -0,0 +1,51 @@ +import java.util.*; + +class Main { + + public static void radixSort(int[] arr) { + int max = Arrays.stream(arr).max().getAsInt(); + + // do count sort for every digit place + for(int exp = 1; max/exp > 0; exp *= 10) { + countSort(arr, exp); + } + } + + private static void countSort(int[] arr, int exp) { + int n = arr.length; + int[] output = new int[n]; + int[] count = new int[10]; + + Arrays.fill(count, 0); + + for(int i=0; i=0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + System.out.println("Output array " + Arrays.toString(output)); + + System.arraycopy(output, 0, arr, 0, n); + + } + + public static void main(String[] args) { + int[] arr = {29, 83, 471, 36, 91, 8}; + + System.out.println("Origin array: " + Arrays.toString(arr)); + radixSort(arr); + System.out.println("Sorted array: " + Arrays.toString(arr)); + } +} \ No newline at end of file diff --git a/lectures/26-advance-sorting/RadixSort/Radix sort.pdf b/lectures/26-advance-sorting/RadixSort/Radix sort.pdf new file mode 100644 index 000000000..a66413920 Binary files /dev/null and b/lectures/26-advance-sorting/RadixSort/Radix sort.pdf differ diff --git a/lectures/27-huffman-coding/code/Heap.java b/lectures/27-huffman-coding/code/Heap.java new file mode 100644 index 000000000..24d1e14d0 --- /dev/null +++ b/lectures/27-huffman-coding/code/Heap.java @@ -0,0 +1,98 @@ +import java.util.ArrayList; + +public class Heap>{ + + private ArrayList list; + + public Heap(){ + list = new ArrayList<>(); + } + + public void insert(T value){ + list.add(value); + upheap(list.size() - 1); + } + public int size(){ + return list.size(); + } + private void upheap(int index){ + + if(index == 0){ + return; + } + + int p = parent(index); + + if(list.get(index).compareTo(list.get(p)) < 0){ + swap(index, p); + upheap(p); + } + } + + public T remove() throws Exception{ + if(list.isEmpty()){ + throw new Exception("Removing from empty Heap"); + } + T temp = list.get(0); + + T last = list.remove(list.size() - 1); + + if(!list.isEmpty()){ + list.set(0, last); + + downheap(0); + } + return temp; + } + + private void downheap(int index) { + + int min = index; + int left = left(index); + int right = right(index); + + // check is left < min + if(left < list.size() && list.get(min).compareTo(list.get(left)) > 0){ + min = left; + } + // check if right < min + if(right < list.size() && list.get(min).compareTo(list.get(right)) > 0){ + min = right; + } + + if(min != index){ + swap(min, index); + + downheap(min); + } + } + + private void swap(int first, int second) { + T temp = list.get(first); + list.set(first, list.get(second)); + list.set(second, temp); + } + + private int parent(int index){ + return (index - 1) / 2; + } + + private int left(int index){ + return index * 2 + 1; + } + + private int right(int index){ + return index * 2 + 2; + } + + public ArrayList heapSort() throws Exception { + + ArrayList data = new ArrayList<>(); + + while(!list.isEmpty()){ + data.add(this.remove()); + } + return data; + } + +} diff --git a/lectures/27-huffman-coding/code/HuffmanCoder.java b/lectures/27-huffman-coding/code/HuffmanCoder.java new file mode 100644 index 000000000..d62d6e02f --- /dev/null +++ b/lectures/27-huffman-coding/code/HuffmanCoder.java @@ -0,0 +1,103 @@ +import java.util.*; + +class HuffmanCoder { + HashMap encoder; + HashMap decoder; + + private class Node implements Comparable { + Character data; + int cost; // frequency + Node left; + Node right; + + public Node(Character data, int cost) { + this.data = data; + this.cost = cost; + this.left = null; + this.right = null; + } + + @Override + public int compareTo(Node other) { + return this.cost - other.cost; + } + } + + public HuffmanCoder(String feeder) throws Exception { + HashMap fmap = new HashMap<>(); + + for(int i=0; i < feeder.length(); i++) { + char cc = feeder.charAt(i); + if(fmap.containsKey(cc)) { + int ov = fmap.get(cc); + ov += 1; + fmap.put(cc, ov); + } else { + fmap.put(cc, 1); + } + } + + Heap minHeap = new Heap<>(); + Set> entrySet = fmap.entrySet(); + + for(Map.Entry entry : entrySet) { + Node node = new Node(entry.getKey(), entry.getValue()); + minHeap.insert(node); + } + + while(minHeap.size() != 1) { + Node first = minHeap.remove(); + Node second = minHeap.remove(); + + Node newNode = new Node('\0', first.cost + second.cost); + newNode.left = first; + newNode.right = second; + + minHeap.insert(newNode); + } + + Node ft = minHeap.remove(); + + this.encoder = new HashMap<>(); + this.decoder = new HashMap<>(); + + this.initEncoderDecoder(ft, ""); + } + + private void initEncoderDecoder(Node node, String osf) { + if(node == null) { + return; + } + if(node.left == null && node.right == null) { + this.encoder.put(node.data, osf); + this.decoder.put(osf, node.data); + } + initEncoderDecoder(node.left, osf+"0"); + initEncoderDecoder(node.right, osf+"1"); + } + + public String encode(String source) { + String ans = ""; + + // Bitset can be used: like an array but with a bit at each index + + for(int i=0; i