├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── hackerrank-data-structures.iml
├── python
├── heap
│ └── minimum-average-waiting-time.py
├── stacks
│ └── largest-rectangle.py
└── trees
│ └── balanced-forest.py
└── src
├── Test.java
├── advanced
└── PairSums.java
├── arrays
├── ArrayManipulation.java
├── ArraysDS.java
├── DynamicArray.java
├── LeftRotation.java
├── SparseArrays.java
└── TwoDArrays.java
├── disjoint_set
├── ComponentsInAGraph.java
└── KunduAndTree.java
├── heap
├── FindTheRunningMedian.java
├── JesseAndCookies.java
├── MinimumAverageWaitingTime.java
└── QHEAP1.java
├── helper
└── Input.java
├── linkedlist
├── Compare2LinkedList.java
├── CycleDetection.java
├── DeleteANode.java
├── DeleteDuplicateValueNodesFromSortedLinkedList.java
├── FindMergePointOf2Lists.java
├── GetNodeValue.java
├── InsertANodeInSortedDoublyLinkedList.java
├── InsertNodeAtHeadOfLinkedList.java
├── InsertNodeAtSpecificPosition.java
├── InsertNodeAtTailOfLinkedList.java
├── Merge2SortedLinkedList.java
├── Node.java
├── PrintElementsOfLinkedList.java
├── PrintInReverse.java
├── ReverseALinkedList.java
├── ReverseDoublyLinkedList.java
└── SinglyLinkedListNode.java
├── mcq
├── Data Structure MCQ 1.md
├── Data Structure MCQ 2.md
└── Data Structure MCQ 3.md
├── queues
├── CastleOnTheGrid.java
├── DownToZeroII.java
├── QueriesWithFixedLength.java
├── QueueUsingTwoStacks.java
└── TruckTourProblem.java
├── stacks
├── BalancedBrackets.java
├── EqualStacks.java
├── GameOfTwoStacks.java
├── LargestRectangle.java
├── MaximumElement.java
├── PoisonousPlants.java
├── SimpleTextEditor.java
├── Waiter.java
└── poisonous-plants.txt
├── trees
├── BST_Insertion.java
├── CustomTree.java
├── HeightOfBinaryTree.java
├── InorderTraversal.java
├── IsThisBinarySearchTree.java
├── KitysCalculationOnATree.cpp
├── LevelOrderTraversal.java
├── LowestCommonAncestor.java
├── Node.java
├── PostOrderTraversal.java
├── PreorderTraversal.java
├── SquareTenTree.cpp
├── SwapNodes_Algo.java
├── Tree.java
├── TreeHuffmanDecoding.java
└── TreesTopView.java
└── trie
└── Contacts.java
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | out
3 | dist
4 | __pycache__
5 | *.iml
6 | python/__pycache__
7 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing Guidelines
2 |
3 | This project aims to create a common source for all Data Structure questions on HackerRank and values every single
4 | contribution made by the community.
5 |
6 | We aim to solve all questions in the HackerRank Data Structures domain in as many languages as possible to show the
7 | different code styles and approaches that can be used to solve the same problem.
8 |
9 | Contributing is very simple. Simply identify a question from the [README](README.md) file that has yet to be solved in
10 | a programming language of your choice.
11 |
12 | Solve that question and make sure that all tests pass on HackerRank and then create a pull request with the
13 | added solution and updated readme.
14 |
15 |
16 | ## Style Guide
17 | We wish that other people and understand and learn from the cde that is given in this repository,
18 | hence code that is legible, properly indented with good function names and variable names, with clear
19 | flow that makes understanding the algorithm easy will be highly appreciated.
20 |
21 | The submitted code must also pass all test cases of the given problem on HackerRank (obviously 😉).
22 | Happy Coding 🐱👤
23 |
24 |
25 | ## Pull Request Process
26 |
27 | 1. Fork this repository to your github account and then clone your forked repository to your machine.
28 | 2. Say you solve some problem called __Rita & Stacks__ in the _Stacks_ sub domain on
29 | HackerRank using your favorite programming language, say Python then simple add a new file called
30 | `rita-and-stacks.py` in the `stacks` directory.
31 | 3. In the [README](README.md) file, add a Python logo along with an empty link.
32 | 4. Updating the link for the solution will be done by the Project maintainers (aka. [anishLearnsToCode]())
33 |
34 |
35 | ## Programming Language Logos
36 | To add a logo in the [README](README.md) table simply add a link with an embedded picture as
37 | ```markdown
38 | [](this link will be filled by the author if the pull request is accepted)
39 | ```
40 |
41 | For the icon link refer to the table below to obtain the link for a specific programming language:
42 |
43 | | Programming Language | Icon | Icon Link|
44 | |:--------------------:|:----:|:----:|
45 | | Java |  | https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png |
46 | | Python |  | https://img.icons8.com/color/35/000000/python.png |
47 | | C |  | https://img.icons8.com/color/35/000000/c-programming.png |
48 | | C++ |  | https://img.icons8.com/color/35/000000/c-plus-plus-logo.png |
49 | | C# |  | https://img.icons8.com/color/35/000000/c-sharp-logo.png |
50 | | JavaScript |  | https://img.icons8.com/color/40/000000/javascript.png |
51 | | TypeScript |  | https://img.icons8.com/color/40/000000/typescript.png |
52 | | Ruby |  | https://img.icons8.com/office/35/000000/ruby-programming-language.png |
53 | | Scala |  | https://img.icons8.com/office/35/000000/ruby-programming-language.png |
54 | | PGH |  | https://img.icons8.com/officel/40/000000/php-logo.png |
55 | | Swift |  | https://img.icons8.com/fluent/40/000000/swift.png |
56 | | Markdown |  | https://img.icons8.com/office/35/000000/markdown.png |
57 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright 2020 anishLearnsToCode
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
4 | documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
5 | rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
6 | persons to whom the Software is furnished to do so, subject to the following conditions:
7 |
8 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
9 | Software.
10 |
11 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
12 | WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
13 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
15 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # HackerRank Data Structures Solutions
2 |
3 | 
4 | 
5 | 
6 | 
7 | 
8 | [](CONTRIBUTING.md)
9 | [](https://github.com/anishLearnsToCode/competitive-programming)
10 | [](https://www.hackerrank.com/anishviewer)
11 |
12 | This repository contains solutions to the
13 | [Data Structures domain](https://www.hackerrank.com/domains/data-structures) part of HackerRank.
14 | The Data Structures Domain Falls under a broader Problem Solving Skill Set in HackerRank
15 | which consists of both
16 | [Data Structures](https://www.hackerrank.com/domains/data-structures)
17 | and [Algorithms](https://www.hackerrank.com/domains/algorithms).
18 |
19 | The Data Structures Domain is further Divided into the following sub-domains.
20 | To Contribute have a look at
21 | [Contributing.md](Contributing.md)
22 | and happy coding 😀 🐱💻.
23 |
24 | ## Sub Domains & Problems (+Solutions) in the Data Structures Domain
25 |
26 | ⚡ Quick Links:
27 | [Arrays](#arrays-) |
28 | [Linked Lists](#linked-lists-) |
29 | [Trees](#trees-) |
30 | [Balanced Trees](#balanced-trees-) |
31 | [Stacks](#stacks-) |
32 | [Queues](#queues-) |
33 | [Heap](#heap-) |
34 | [Disjoint Set](#disjoint-set-) |
35 | [Multiple Choice](#multiple-choice-) |
36 | [Trie](#trie-) |
37 | [Advanced](#advanced-) |
38 |
39 | ### Arrays 
40 |
41 | | Problem | Difficulty Level | Solution Link |
42 | |---------|------------------|:-------------:|
43 | | [Arrays - DS](https://www.hackerrank.com/challenges/arrays-ds) | Easy | [](src/arrays/ArraysDS.java) |
44 | | [2D Arrays - DS](https://www.hackerrank.com/challenges/2d-array) | Easy | [](src/arrays/TwoDArrays.java) |
45 | | [Dynamic Array](https://www.hackerrank.com/challenges/dynamic-array) | Easy | [](src/arrays/DynamicArray.java) |
46 | | [Left Rotation](https://www.hackerrank.com/challenges/array-left-rotation) | Easy | [](src/arrays/LeftRotation.java) |
47 | | [Sparse Arrays](https://www.hackerrank.com/challenges/arrays-ds) | Medium | [](src/arrays/SparseArrays.java) |
48 | | [Array Manipulation](https://www.hackerrank.com/challenges/crush) | Hard | [](src/arrays/ArrayManipulation.java) |
49 |
50 | ### Linked Lists 
51 | | Problem | Difficulty Level | Solution Link |
52 | |---------|------------------|:-------------:|
53 | | [Print the Elements of a Linked List](https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list) | Easy | [](src/linkedlist/PrintElementsOfLinkedList.java) |
54 | | [Insert a Node at the Tail of a Linked List](https://www.hackerrank.com/challenges/insert-a-node-at-the-tail-of-a-linked-list) | Easy | [](src/linkedlist/InsertNodeAtTailOfLinkedList.java) |
55 | | [Insert a Node at the head of a Linked List](https://www.hackerrank.com/challenges/insert-a-node-at-the-head-of-a-linked-list) | Easy | [](src/linkedlist/InsertNodeAtHeadOfLinkedList.java) |
56 | | [Insert a Node at a specific position in a Linked List](https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list) | Easy | [](src/linkedlist/InsertNodeAtSpecificPosition.java) |
57 | | [Delete a Node](https://www.hackerrank.com/challenges/delete-a-node-from-a-linked-list) | Easy | [](src/linkedlist/DeleteANode.java) |
58 | | [Print in Reverse](https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list-in-reverse) | Easy | [](src/linkedlist/PrintInReverse.java) |
59 | | [Reverse a Linked List](https://www.hackerrank.com/challenges/reverse-a-linked-list) | Easy | [](src/linkedlist/ReverseALinkedList.java) |
60 | | [Compare two Linked Lists](https://www.hackerrank.com/challenges/compare-two-linked-lists) | Easy | [](src/linkedlist/Compare2LinkedList.java) |
61 | | [Merge two sorted Linked Lists](https://www.hackerrank.com/challenges/merge-two-sorted-linked-lists) | Easy | [](src/linkedlist/Merge2SortedLinkedList.java) |
62 | | [Get Node Value](https://www.hackerrank.com/challenges/get-the-value-of-the-node-at-a-specific-position-from-the-tail) | Easy | [](src/linkedlist/GetNodeValue.java) |
63 | | [Delete Duplicate Value Nodes from a sorted Linked List](https://www.hackerrank.com/challenges/delete-duplicate-value-nodes-from-a-sorted-linked-list) | Easy | [](src/linkedlist/DeleteDuplicateValueNodesFromSortedLinkedList.java) |
64 | | [Cycle Detection](https://www.hackerrank.com/challenges/detect-whether-a-linked-list-contains-a-cycle) | Medium | [](src/linkedlist/CycleDetection.java) |
65 | | [Find Merge Points of Two Lists](https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists) | Easy | [](src/linkedlist/FindMergePointOf2Lists.java) |
66 | | [Inserting a Node Into a Sorted Double Linked List](https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list) | Easy | [](src/linkedlist/InsertANodeInSortedDoublyLinkedList.java) |
67 | | [Reverse a Doubly Linked List](https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list) | Easy | [](src/linkedlist/ReverseDoublyLinkedList.java) |
68 |
69 | ### Trees 
70 |
71 | | Problem | Difficulty Level | Solution Link |
72 | |---------|------------------|:-------------:|
73 | | [Tree: Preorder Traversal](https://www.hackerrank.com/challenges/tree-preorder-traversal) | Easy | [](src/trees/PreorderTraversal.java) |
74 | | [Tree: Postorder Traversal](https://www.hackerrank.com/challenges/tree-postorder-traversal) | Easy | [](src/trees/PostOrderTraversal.java) |
75 | | [Tree: Inorder Traversal](https://www.hackerrank.com/challenges/tree-inorder-traversal) | Easy | [](src/trees/InorderTraversal.java) |
76 | | [Tree: Height of Binary Tree](https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree) | Easy | [](src/trees/HeightOfBinaryTree.java) |
77 | | [Tree: Level Order Traversal](https://www.hackerrank.com/challenges/tree-level-order-traversal) | Easy | [](src/trees/LevelOrderTraversal.java) |
78 | | [Binary Search Tree: Insertion](https://www.hackerrank.com/challenges/binary-search-tree-insertion) | Easy | [](src/trees/BST_Insertion.java) |
79 | | [Tree: Huffman Decoding](https://www.hackerrank.com/challenges/tree-huffman-decoding) | Medium | [](src/trees/TreeHuffmanDecoding.java) |
80 | | [Binary Search Tree: Lowest Common Ancestor](https://www.hackerrank.com/challenges/binary-search-tree-lowest-common-ancestor) | Easy | [](src/trees/LowestCommonAncestor.java) |
81 | | [Swap Nodes [Algo]](https://www.hackerrank.com/challenges/swap-nodes-algo) | Medium | [](src/trees/SwapNodes_Algo.java) |
82 | | [Is There a Binary Search Tree](https://www.hackerrank.com/challenges/is-binary-search-tree) | Medium | [](src/trees/IsThisBinarySearchTree.java) |
83 | | [Tree: Top View](https://www.hackerrank.com/challenges/tree-top-view) | Easy | [](src/trees/TreesTopView.java) |
84 | | [Kitty's Calculations on a Tree](https://www.hackerrank.com/challenges/kittys-calculations-on-a-tree) | Advanced | [](src/trees/KitysCalculationOnATree.cpp) |
85 | | [Square Ten Tree](https://www.hackerrank.com/challenges/square-ten-tree) | Hard |[](src/trees/SquareTenTree.cpp) |
86 | | [Balanced Forest](https://www.hackerrank.com/challenges/balanced-forest) | Hard | [](python/trees/balanced-forest.py) |
87 | | [Jenny's Subtrees](https://www.hackerrank.com/challenges/jenny-subtrees) | Hard | |
88 | | [Tree Coordinates](https://www.hackerrank.com/challenges/tree-coordinates) | Expert | |
89 | | [Array Pairs](https://www.hackerrank.com/challenges/array-pairs) | Advanced | |
90 |
91 |
92 | ### Balanced Trees 
93 |
94 | | Problem | Difficulty Level | Solution Link |
95 | |---------|------------------|---------------|
96 | | [Self Balancing Tree](https://www.hackerrank.com/challenges/self-balancing-tree) | Medium | |
97 | | [Array and Simple Queries](https://www.hackerrank.com/challenges/array-and-simple-queries) | Hard | |
98 | | [Median Updates](https://www.hackerrank.com/challenges/median) | Hard | |
99 |
100 |
101 | ### Stacks 
102 |
103 | | Problem | Difficulty Level | Solution Link |
104 | |---------|------------------|:-------------:|
105 | | [Maximum Element](https://www.hackerrank.com/challenges/maximum-element) | Easy | [](src/stacks/MaximumElement.java) |
106 | | [Balanced Brackets](https://www.hackerrank.com/challenges/balanced-brackets) | Medium | [](src/stacks/BalancedBrackets.java) |
107 | | [Equal Stacks](https://www.hackerrank.com/challenges/equal-stacks) | Easy | [](src/stacks/EqualStacks.java) |
108 | | [Game of Two Stacks](https://www.hackerrank.com/challenges/game-of-two-stacks) | Medium | [](src/stacks/GameOfTwoStacks.java) |
109 | | [Simple Text Editor](https://www.hackerrank.com/challenges/simple-text-editor) | Medium | [](src/stacks/SimpleTextEditor.java) |
110 | | [Waiter](https://www.hackerrank.com/challenges/waiter) | Medium | [](src/stacks/Waiter.java) |
111 | | [Largest Rectangle](https://www.hackerrank.com/challenges/largest-rectangle) | Medium | [](src/stacks/LargestRectangle.java) [](python/stacks/largest-rectangle.py) |
112 | | [Poisonous Plants](https://www.hackerrank.com/challenges/poisonous-plants) | Hard | [](src/stacks/PoisonousPlants.java) |
113 | | [AND xor OR](https://www.hackerrank.com/challenges/and-xor-or) | Hard | |
114 |
115 |
116 | ### Queues 
117 | | Problem | Difficulty Level | Solution Link |
118 | |---------|------------------|---------------|
119 | | [Queue Using Two Stacks](https://www.hackerrank.com/challenges/queue-using-two-stacks) | Medium | [](src/queues/QueueUsingTwoStacks.java) |
120 | | [Castle on The Grid](https://www.hackerrank.com/challenges/castle-on-the-grid) | Medium | [](src/queues/CastleOnTheGrid.java) |
121 | | [Down to Zero II](https://www.hackerrank.com/challenges/down-to-zero-ii) | Medium | [](src/queues/DownToZeroII.java) |
122 | | [Truck Tour](https://www.hackerrank.com/challenges/truck-tour) | Hard | [](src/queues/TruckTourProblem.java) |
123 | | [Queries with Fixed Length](https://www.hackerrank.com/challenges/queries-with-fixed-length) | Hard | [](src/queues/QueriesWithFixedLength.java) |
124 |
125 |
126 | ### Heap 
127 |
128 | | Problem | Difficulty Level | Solution Link |
129 | |---------|------------------|---------------|
130 | | [QHEAP1](https://www.hackerrank.com/challenges/qheap1) | Easy | [](src/heap/QHEAP1.java) |
131 | | [Jessie and Cookies](https://www.hackerrank.com/challenges/jesse-and-cookies) | Easy | [](src/heap/JesseAndCookies.java) |
132 | | [Find the Running Median](https://www.hackerrank.com/challenges/find-the-running-median) | Hard | [](src/heap/FindTheRunningMedian.java) |
133 | | [Minimum Average Wait Time](https://www.hackerrank.com/challenges/minimum-average-waiting-time) | Hard | [](python/heap/minimum-average-waiting-time.py) |
134 |
135 |
136 | ### Disjoint Set 
137 |
138 | | Problem | Difficulty Level | Solution Link |
139 | |---------|------------------|---------------|
140 | | [Components In A Graph](https://www.hackerrank.com/challenges/components-in-graph) | Medium | [](src/disjoint_set/ComponentsInAGraph.java) |
141 | | [Kundu and Tree](https://www.hackerrank.com/challenges/kundu-and-tree) | Hard | |
142 | | [Super Maximum Cost Queries](https://www.hackerrank.com/challenges/maximum-cost-queries) | Hard | |
143 | | [Merging Communities](https://www.hackerrank.com/challenges/merging-communities) | Hard | |
144 |
145 |
146 | ### Multiple Choice 
147 |
148 | | Problem | Difficulty Level | Solution Link |
149 | |---------|------------------|:-------------:|
150 | | [Data Structures MCQ1](https://www.hackerrank.com/challenges/how-well-do-you-know-trees) | Multiple Choice Question | [](src/mcq/Data%20Structure%20MCQ%201.md) |
151 | | [Data Structures MCQ2](https://www.hackerrank.com/challenges/are-you-an-expert-on-data-structures) | Multiple Choice Question | [](src/mcq/Data%20Structure%20MCQ%202.md) |
152 | | [Data Structures MCQ3](https://www.hackerrank.com/challenges/are-you-an-expert-on-data-structures-1) | Multiple Choice Question | [](src/mcq/Data%20Structure%20MCQ%203.md) |
153 |
154 |
155 | ### Trie 
156 |
157 | | Problem | Difficulty Level | Solution Link |
158 | |---------|------------------|:-------------:|
159 | | [Contacts]() | Medium | [](src/trie/Contacts.java) |
160 | | [No Prefix Set](https://www.hackerrank.com/challenges/no-prefix-set) | Hard | |
161 |
162 |
163 | ### Advanced 
164 |
165 | | Problem | Difficulty Level | Solution Link |
166 | |---------|------------------|---------------|
167 | | [Kindergarten Adventures](https://www.hackerrank.com/challenges/kindergarten-adventures) | Medium | |
168 | | [Mr. X and his Shots](https://www.hackerrank.com/challenges/x-and-his-shots) | Medium | |
169 | | [Cube Summation](https://www.hackerrank.com/challenges/cube-summation) | Hard | |
170 | | [Direct Connections](https://www.hackerrank.com/challenges/direct-connections) | Hard | |
171 | | [Subsequence Weighting](https://www.hackerrank.com/challenges/subsequence-weighting) | Advanced | |
172 | | [Jim and the Skyscrapers](https://www.hackerrank.com/challenges/jim-and-the-skyscrapers) | Medium | |
173 | | [Palindromic Subsets](https://www.hackerrank.com/challenges/palindromic-subsets) | Hard | |
174 | | [Counting On A Tree](https://www.hackerrank.com/challenges/counting-on-a-tree) | Expert | |
175 | | [Polynomial Division](https://www.hackerrank.com/challenges/polynomial-division) | Hard |
176 | | [Costly Intervals](https://www.hackerrank.com/challenges/costly-intervals) | Hard |
177 | | [The Strange Function](https://www.hackerrank.com/challenges/the-strange-function) | Hard |
178 | | [Self-Driving Bus](https://www.hackerrank.com/challenges/self-driving-bus) | Advanced |
179 | | [Unique Colors](https://www.hackerrank.com/challenges/unique-colors) | Advanced |
180 | | [Fibonacci Numbers Tree](https://www.hackerrank.com/challenges/fibonacci-numbers-tree) | Expert |
181 | | [Pair Sums](https://www.hackerrank.com/challenges/pair-sums) | Expert |
182 | | [Functional Palindromes](https://www.hackerrank.com/challenges/functional-palindromes) | Advanced |
183 | | [Lazy White Falcon](https://www.hackerrank.com/challenges/lazy-white-falcon) | Hard |
184 | | [Ticket To Ride](https://www.hackerrank.com/challenges/ticket-to-ride) | Expert |
185 | | [Heavy Light White Falcon](https://www.hackerrank.com/challenges/heavy-light-white-falcon) | Hard |
186 | | [Sum of The Maximums](https://www.hackerrank.com/challenges/little-alexey-and-sum-of-maximums) | Advanced |
187 | | [Number Game On A Tree](https://www.hackerrank.com/challenges/number-game-on-a-tree) | Expert |
188 | | [Heavy Light 2 White Falcon](https://www.hackerrank.com/challenges/heavy-light-2-white-falcon) | Hard |
189 | | [Library Query](https://www.hackerrank.com/challenges/library-query) | Advanced |
190 | | [Starfleet](https://www.hackerrank.com/challenges/starfleet) | Advanced |
191 | | [Almost Equal - Advanced](https://www.hackerrank.com/challenges/almost-equal-advanced) | Expert |
192 | | [Almost Sorted Interval](https://www.hackerrank.com/challenges/almost-sorted-interval) | Expert |
193 | | [Burger Happiness](https://www.hackerrank.com/challenges/burger-happiness) | Hard |
194 | | [Roy and Alpha Beta Trees](https://www.hackerrank.com/challenges/roy-and-alpha-beta-trees) | Hard |
195 | | [Coloring Tree](https://www.hackerrank.com/challenges/coloring-tree) | Hard |
196 | | [Recalling Early Days GP With Trees](https://www.hackerrank.com/challenges/recalling-early-days-gp-with-trees) | Hard |
197 | | [Swaps and Sums](https://www.hackerrank.com/challenges/swaps-and-sum) | Advanced |
198 | | [Arithmetic Progressions](https://www.hackerrank.com/challenges/arithmetic-progressions) | Advanced |
199 | | [Coolguy And Two Subsequences](https://www.hackerrank.com/challenges/coolguy-and-two-subsequences) | Advanced |
200 | | [White Falcon and Tree](https://www.hackerrank.com/challenges/white-falcon-and-tree) | Hard |
201 | | [Subtrees and Paths](https://www.hackerrank.com/challenges/subtrees-and-paths) | Advanced |
202 | | [Triplets](https://www.hackerrank.com/challenges/triplets) | Advanced |
203 | | [Beautiful Segments](https://www.hackerrank.com/challenges/beautiful-segments) | Expert | |
204 | | [Divisibility](https://www.hackerrank.com/challenges/ab0) | Expert |
205 | | [BST Maintenance](https://www.hackerrank.com/challenges/bst-maintenance) | Advanced |
206 | | [Find Maximum Index Product](https://www.hackerrank.com/challenges/find-maximum-index-product) | Medium |
207 | | [Taxicab Driver's Problem](https://www.hackerrank.com/challenges/taxicab-drivers-problem) | Advanced |
208 | | [Jaggu Playing With Balloons](https://www.hackerrank.com/challenges/jagia-playing-with-numbers) | Advanced |
209 | | [Dynamic Summation](https://www.hackerrank.com/challenges/dynamic-summation) | Hard |
210 | | [Two Array Problem](https://www.hackerrank.com/challenges/weird-queries) | Hard | |
211 | | [Rooted Tree](https://www.hackerrank.com/challenges/rooted-tree) | Hard | |
212 | | [The Crazy Helix](https://www.hackerrank.com/challenges/helix) | Advanced | |
213 | | [Network Administration](https://www.hackerrank.com/challenges/net-admin) | Hard | |
214 | | [Easy Addition](https://www.hackerrank.com/challenges/easy-addition) | Expert | |
215 | | [Find The Permutation]() | Expert | |
216 | | [Company Retreat](https://www.hackerrank.com/challenges/company-retreat) | Advanced | |
217 | | [Box Operations](https://www.hackerrank.com/challenges/box-operations) | Expert | |
218 | | [Max Transform](https://www.hackerrank.com/challenges/max-transform) | Expert | |
219 | | [Array and Queries](https://www.hackerrank.com/challenges/array-and-queries-1) | Hard | |
220 |
--------------------------------------------------------------------------------
/hackerrank-data-structures.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/python/heap/minimum-average-waiting-time.py:
--------------------------------------------------------------------------------
1 | from heapq import heappush, heappop
2 |
3 | tasks = []
4 |
5 | N = int(input())
6 |
7 | for _ in range(N):
8 | arrival, cook_time = map(int, input().split())
9 | tasks.append((arrival, cook_time))
10 |
11 | tasks.sort(reverse=True)
12 | print(tasks)
13 |
14 | pq = []
15 | time_waiting = 0
16 | current_time = 0
17 |
18 | while tasks or pq:
19 | while tasks and tasks[-1][0] <= current_time:
20 | heappush(pq, tasks.pop()[::-1])
21 | if pq:
22 | current_task = heappop(pq)
23 | current_time += current_task[0]
24 | time_waiting += current_time - current_task[1]
25 | else:
26 | heappush(pq, tasks.pop()[::-1])
27 | current_time = pq[0][1]
28 |
29 | print(time_waiting // N)
30 |
--------------------------------------------------------------------------------
/python/stacks/largest-rectangle.py:
--------------------------------------------------------------------------------
1 | def calculate_area(element, stack, index):
2 | start_index = -1 if len(stack) == 0 else stack[len(stack) - 1][1]
3 | return element * (index - start_index - 1)
4 |
5 |
6 | N = int(input())
7 | heights = list(map(int, input().split()))
8 | heights.append(0)
9 |
10 | stack = []
11 | area = 0
12 | for index in range(len(heights)):
13 | while len(stack) != 0 and heights[index] < stack[len(stack) - 1][0]:
14 | data = stack.pop()
15 | area = max(area, calculate_area(data[0], stack, index))
16 | stack.append((heights[index], index))
17 |
18 | print(area)
19 |
--------------------------------------------------------------------------------
/python/trees/balanced-forest.py:
--------------------------------------------------------------------------------
1 | #!/bin/python3
2 |
3 | import math
4 | import os
5 |
6 | class TreeNode:
7 | def __init__(self, value, children):
8 | self.value = value
9 | self.children = children
10 | self.total_sum = None
11 |
12 | def __repr__(self):
13 | return "TreeNode(%s, %s)" % (self.value, self.total_sum)
14 |
15 | def build_tree(tree_values, tree_edges):
16 | tree_nodes = [TreeNode(v, set()) for v in tree_values]
17 | for node_from, node_to in tree_edges:
18 | # The tree input is undirected so I am adding both as children and parent
19 | # I am later cleaning it up while doing DFS over the tree
20 | tree_nodes[node_from - 1].children.add(tree_nodes[node_to - 1])
21 | tree_nodes[node_to - 1].children.add(tree_nodes[node_from - 1])
22 | return tree_nodes[0]
23 |
24 | def is_even_number(value):
25 | return not value & 1
26 |
27 | def populate_tree_sums(root):
28 | stack = (root, None)
29 | visited = set()
30 |
31 | while stack:
32 | selected_node = stack[0]
33 |
34 | if selected_node not in visited:
35 | visited.add(selected_node)
36 | for child in selected_node.children:
37 | #remove non children, this cleans out the "bad" inputs
38 | #the tree has undirected edges so when we convert it back to a
39 | #proper tree it's easier to work with...
40 | child.children.remove(selected_node)
41 | #populate the stack:
42 | stack = (child, stack)
43 | else:
44 | stack = stack[-1] # pop stack
45 | #calculate the total sum of the current node before going up the tree
46 | selected_node.total_sum = sum(
47 | map(
48 | lambda tn: tn.total_sum,
49 | selected_node.children
50 | )
51 | ) + selected_node.value
52 |
53 | def find_best_balanced_forest(root):
54 | stack = (root, None)
55 | #visited - visited nodes
56 | #visited_sums - sums that are currently visited
57 | #root complement sums complement sums (total_value - parent) on the way to the
58 | #current node, the cardinality of root complement sums is increased when going
59 | #down the tree and decreased when going up the tree, it is okay to do that
60 | #because the sums are always unique in the root_complement_sums
61 | visited, visited_sums, root_complement_sums = set(), set(), set()
62 | min_result_value = math.inf
63 |
64 | while stack:
65 | selected_node = stack[0]
66 |
67 | if selected_node not in visited:
68 | visited.add(selected_node)
69 |
70 | #populate stack with children all at once:
71 | for child in selected_node.children:
72 | stack = (child, stack)
73 |
74 | #this is a complement sum: TOTAL - current_sum
75 | #I need to calculate it while going down the tree so when I go up
76 | #I will use those values in the root_complement_sums to check for
77 | #existance
78 | selected_sum_comp = root.total_sum - selected_node.total_sum
79 | root_complement_sums.add(selected_sum_comp)
80 |
81 | # Yes, no bitwise shifts, I present what I want to get accomplished,
82 | # but I don't care how it is accomplished
83 | # selected_node.total_sum * 3 >= root.total_sum is checking that
84 | # that if the cut is made in selected subtree and the visited subtree
85 | # (in case the comp or sum exists in the visited sums)
86 | # the remaining subtree sum is equal or less than the sums
87 | # (which are equal) of the current and the visited subtrees
88 | # this is just part of the requirement - I can balance the remaining
89 | # tree only with 0 or positive elements
90 | if (
91 | (selected_node.total_sum * 2) in visited_sums or
92 | (root.total_sum - selected_node.total_sum * 2) in visited_sums
93 | ) and selected_node.total_sum * 3 >= root.total_sum:
94 |
95 | #get the candidate value and update min_result_value if it's less
96 | candidate_value = selected_node.total_sum * 3 - root.total_sum
97 | if candidate_value < min_result_value:
98 | min_result_value = candidate_value
99 | else:
100 | # This is a case where two even halfs are found.
101 | if (selected_node.total_sum * 2) == root.total_sum:
102 | candidate_value = selected_node.total_sum
103 | # In this case a balanced forest is these two halfs + a new node as
104 | # a separate tree with the same value as the half of the existing
105 | # tree sum
106 | if candidate_value < min_result_value:
107 | min_result_value = candidate_value
108 |
109 | # check visited sums and root complements
110 | # root complements are the sums on the way from root to the selected
111 | # nodes taken from it's parents of if we have a tree
112 | # (1)
113 | # / | \
114 | # / | \
115 | # / | \
116 | # (2) (3) (4)
117 | # / \ | /\
118 | # (5)(6) (7) (8)(9)
119 | #
120 | #
121 | # If I am at the node 8, I have the {TOTAL - (8).sum, TOTAL - (4).sum }
122 | # If I am at the node 9, I have the {TOTAL - (9).sum, TOTAL - (4).sum }
123 | # If I am at the node 2, I have the {TOTAL - (2).sum }
124 | if (
125 | (
126 | selected_node.total_sum in visited_sums or
127 | selected_node.total_sum in root_complement_sums
128 | ) and selected_node.total_sum * 3 >= root.total_sum
129 | ):
130 | # candidate split:
131 | candidate_value = selected_node.total_sum * 3 - root.total_sum
132 | if candidate_value < min_result_value:
133 | min_result_value = candidate_value
134 |
135 | selected_sum_comp = root.total_sum - selected_node.total_sum
136 | if is_even_number(selected_sum_comp):
137 | #I am not trying to impress anyone with bitwise shifts here:
138 | selected_sum_comp_half = selected_sum_comp // 2
139 | if selected_sum_comp_half > selected_node.total_sum and (
140 | selected_sum_comp_half in visited_sums or
141 | selected_sum_comp_half in root_complement_sums
142 | ):
143 | #same candidate value
144 | candidate_value = selected_sum_comp_half - selected_node.total_sum
145 | if candidate_value < min_result_value:
146 | min_result_value = candidate_value
147 |
148 | #remove selected complement from root while going up the tree
149 | root_complement_sums.remove(selected_sum_comp)
150 | #added to the visited sums while going up the tree
151 | visited_sums.add(selected_node.total_sum)
152 |
153 | #stack pop:
154 | stack = stack[-1]
155 |
156 | if min_result_value == math.inf:
157 | min_result_value = -1
158 | return min_result_value
159 |
160 | # Complete the balancedForest function below.
161 | def balancedForest(tree_values, tree_edges):
162 | root = build_tree(tree_values, tree_edges)
163 | populate_tree_sums(root)
164 | return find_best_balanced_forest(root)
165 |
166 |
167 | if __name__ == '__main__':
168 | fptr = open(os.environ['OUTPUT_PATH'], 'w')
169 |
170 | q = int(input())
171 |
172 | for q_itr in range(q):
173 | n = int(input())
174 |
175 | c = list(map(int, input().rstrip().split()))
176 |
177 | edges = []
178 |
179 | for _ in range(n - 1):
180 | edges.append(list(map(int, input().rstrip().split())))
181 |
182 | result = balancedForest(c, edges)
183 |
184 | fptr.write(str(result) + '\n')
185 |
186 | fptr.close()
187 |
--------------------------------------------------------------------------------
/src/Test.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class Test {
4 | public static void main(String[] args) {
5 | Scanner s = new Scanner(System.in);
6 | int size = s.nextInt();
7 | int arr[] = new int[size];
8 | for(int index =0 ; index= 0 ; sum += array[index], index--) {
19 | result += array[index] * sum;
20 | }
21 | System.out.println(result);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/arrays/ArrayManipulation.java:
--------------------------------------------------------------------------------
1 | package arrays;
2 |
3 | import java.util.Scanner;
4 |
5 | public class ArrayManipulation {
6 | private static final Scanner SCANNER = new Scanner(System.in);
7 |
8 | public static void main(String[] args) {
9 | int length = SCANNER.nextInt();
10 | int queries = SCANNER.nextInt();
11 | long[] array = new long[length + 2];
12 |
13 | while (queries-- > 0) {
14 | int startIndex = SCANNER.nextInt();
15 | int endIndex = SCANNER.nextInt();
16 | int element = SCANNER.nextInt();
17 | array[startIndex] += element;
18 | array[endIndex + 1] -= element;
19 | }
20 |
21 | long sum = 0, max = Integer.MIN_VALUE;
22 | for (long element : array) {
23 | sum += element;
24 | max = Math.max(max, sum);
25 | }
26 | System.out.println(max);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/arrays/ArraysDS.java:
--------------------------------------------------------------------------------
1 | package arrays;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 |
6 | public class ArraysDS {
7 | private static Scanner scanner = new Scanner(System.in);
8 |
9 | public static void main(String[] args) {
10 | int length = scanner.nextInt();
11 | int[] array = getArray(length);
12 | System.out.println(Arrays.toString(reverse(array)));
13 | }
14 |
15 | private static int[] getArray(int length) {
16 | int[] array = new int[length];
17 | for (int index = 0 ; index < array.length ; index++) {
18 | array[index] = scanner.nextInt();
19 | }
20 | return array;
21 | }
22 |
23 | private static int[] reverse(int[] array) {
24 | int[] result = new int[array.length];
25 | for (int index = 0 ; index < array.length ; index++) {
26 | result[index] = array[array.length - 1 - index];
27 | }
28 | return result;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/arrays/DynamicArray.java:
--------------------------------------------------------------------------------
1 | package arrays;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashMap;
5 | import java.util.Scanner;
6 |
7 | public class DynamicArray {
8 |
9 | private static final Scanner s = new Scanner(System.in);
10 | private static final HashMap> seqList = new HashMap<>();
11 | private static int lastAnswer = 0, N;
12 |
13 | public static void main(String[] args) {
14 | int queries;
15 |
16 | N = s.nextInt();
17 | queries = s.nextInt();
18 |
19 | performQueries(queries);
20 | }
21 |
22 | private static void performQueries(int queries) {
23 | int n, x, y;
24 |
25 | for(int i=0 ; i smallList = seqList.get(index);
41 | smallList.add(y);
42 | seqList.put(index, smallList);
43 | } else {
44 | ArrayList smallList = new ArrayList<>();
45 | smallList.add(y);
46 | seqList.put(index, smallList);
47 | }
48 | }
49 |
50 | private static void performQuery2(int x, int y){
51 | int index = indexOf(x);
52 | ArrayList smallList = seqList.get(index);
53 | lastAnswer = smallList.get(y%smallList.size());
54 | System.out.println(lastAnswer);
55 | }
56 |
57 | private static int indexOf(int x){
58 | return (x^lastAnswer)%N ;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/arrays/LeftRotation.java:
--------------------------------------------------------------------------------
1 | package arrays;
2 |
3 | import java.util.Scanner;
4 |
5 | public class LeftRotation {
6 |
7 | private static final Scanner SCANNER = new Scanner(System.in);
8 | private static int arr[];
9 |
10 | public static void main(String[] args) {
11 | int size = SCANNER.nextInt();
12 | int leftRotations = SCANNER.nextInt();
13 |
14 | arr = new int[size];
15 | input(arr);
16 |
17 | rotate(leftRotations);
18 | print(arr);
19 | }
20 |
21 | private static void rotate(int leftRotations){
22 | leftRotations = leftRotations % arr.length;
23 | int rightRotations = arr.length - leftRotations;
24 | int rotations = Math.min(leftRotations, rightRotations);
25 |
26 | if(rotations == leftRotations)
27 | leftRotate(rotations);
28 | else
29 | rightRotate(rotations);
30 | }
31 |
32 | private static void leftRotate(int rotations){
33 | for(int i=0 ; i0 ; i--){
51 | arr[i] = arr[i-1];
52 | }
53 | arr[0] = last;
54 | }
55 |
56 | private static void print(int arr[]){
57 | for(int index =0 ; index frequencyMap = new HashMap<>();
10 | private static Scanner s = new Scanner(System.in);
11 |
12 | public static void main(String[] args) {
13 | int size = s.nextInt();
14 | arr = new String[size];
15 | input();
16 | hashing();
17 |
18 | int queries = s.nextInt();
19 | computeQueries(queries);
20 | }
21 |
22 | private static void computeQueries(int queries){
23 | for(int i=0 ; i> disjointSets = graph.disjointSets();
30 | int minimum = min(disjointSets);
31 | int maximum = max(disjointSets);
32 | System.out.println(minimum + " " + maximum);
33 | }
34 |
35 | private static int min(List> sets) {
36 | int result = Integer.MAX_VALUE;
37 | for (Set set : sets) {
38 | if (set.size() == 1) {
39 | continue;
40 | }
41 | result = Math.min(result, set.size());
42 | }
43 | return result;
44 | }
45 |
46 | private static int max(List> sets) {
47 | int result = Integer.MIN_VALUE;
48 | for (Set set : sets) {
49 | if (set.size() == 1) {
50 | continue;
51 | }
52 | result = Math.max(result, set.size());
53 | }
54 | return result;
55 | }
56 |
57 | private static class Graph {
58 | private final Map vertices;
59 |
60 | private static class Vertex {
61 | int data;
62 | Set edges = new HashSet<>();
63 |
64 | Vertex(int data) {
65 | this.data = data;
66 | }
67 |
68 | void addEdge(Vertex to) {
69 | this.edges.add(to);
70 | }
71 | }
72 |
73 | Graph(int size) {
74 | vertices = new HashMap<>(size);
75 | for (int number = 1 ; number <= size ; number++) {
76 | addVertex(number);
77 | }
78 | }
79 |
80 | private void addVertex(int data) {
81 | this.vertices.put(data, new Vertex(data));
82 | }
83 |
84 | private void addEdge(int from, int to) {
85 | Vertex fromVertex = vertices.get(from);
86 | Vertex toVertex = vertices.get(to);
87 | fromVertex.addEdge(toVertex);
88 | toVertex.addEdge(fromVertex);
89 | }
90 |
91 | private List> disjointSets() {
92 | List> disjointSets = new ArrayList<>();
93 | Set visited = new HashSet<>();
94 | for (Vertex vertex : this.vertices.values()) {
95 | if (visited.contains(vertex)) {
96 | continue;
97 | }
98 |
99 | Set disjointSet = new HashSet<>();
100 | Queue queue = new LinkedList<>();
101 | queue.add(vertex);
102 |
103 | while (!queue.isEmpty()) {
104 | Vertex top = queue.poll();
105 | if (visited.contains(top)) {
106 | continue;
107 | }
108 | visited.add(top);
109 | disjointSet.add(top);
110 |
111 | queue.addAll(top.edges);
112 | }
113 | disjointSets.add(disjointSet);
114 | }
115 | return disjointSets;
116 | }
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/src/disjoint_set/KunduAndTree.java:
--------------------------------------------------------------------------------
1 | // https://www.hackerrank.com/challenges/kundu-and-tree/problem
2 |
3 | package disjoint_set;
4 |
5 | public class KunduAndTree {
6 | public static void main(String[] args) {
7 |
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/src/heap/FindTheRunningMedian.java:
--------------------------------------------------------------------------------
1 | package heap;
2 |
3 | import java.util.Comparator;
4 | import java.util.PriorityQueue;
5 | import java.util.Queue;
6 | import java.util.Scanner;
7 |
8 | public class FindTheRunningMedian {
9 | private static final Scanner scanner = new Scanner(System.in);
10 |
11 | public static void main(String[] args) {
12 | int length = scanner.nextInt();
13 | int[] array = getArray(length);
14 | printMedians(array);
15 | }
16 |
17 | private static int[] getArray(int length) {
18 | int[] array = new int[length];
19 | for (int index = 0 ; index < array.length ; index++) {
20 | array[index] = scanner.nextInt();
21 | }
22 | return array;
23 | }
24 |
25 | private static void printMedians(int[] array) {
26 | Queue lowerHalf = new PriorityQueue<>(Comparator.reverseOrder());
27 | Queue upperHalf = new PriorityQueue<>();
28 | for (int number : array) {
29 | addToHeap(lowerHalf, upperHalf, number);
30 | redolenceHeaps(lowerHalf, upperHalf);
31 | double median = getMedian(lowerHalf, upperHalf);
32 | System.out.println(String.format("%.1f", median));
33 | }
34 | }
35 |
36 | private static void addToHeap(Queue lowerHalf, Queue upperHalf, int number) {
37 | if (lowerHalf.isEmpty() || number < lowerHalf.peek()) {
38 | lowerHalf.add(number);
39 | } else {
40 | upperHalf.add(number);
41 | }
42 | }
43 |
44 | private static void redolenceHeaps(Queue lowerHalf, Queue upperHalf) {
45 | Queue larger = lowerHalf.size() < upperHalf.size() ? upperHalf : lowerHalf ;
46 | Queue smaller = lowerHalf.size() < upperHalf.size() ? lowerHalf : upperHalf ;
47 |
48 | while (larger.size() - smaller.size() >= 2) {
49 | smaller.add(larger.poll());
50 | }
51 | }
52 |
53 | private static double getMedian(Queue lowerHalf, Queue upperHalf) {
54 | if (lowerHalf.size() == upperHalf.size()) {
55 | return ((double) lowerHalf.peek() + upperHalf.peek()) / 2;
56 | } else {
57 | return lowerHalf.size() > upperHalf.size() ? lowerHalf.peek() : upperHalf.peek();
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/heap/JesseAndCookies.java:
--------------------------------------------------------------------------------
1 | // https://www.hackerrank.com/challenges/jesse-and-cookies/problem
2 |
3 | package heap;
4 |
5 | import java.util.PriorityQueue;
6 | import java.util.Queue;
7 | import java.util.Scanner;
8 |
9 | public class JesseAndCookies {
10 | public static void main(String[] args) {
11 | Scanner scanner = new Scanner(System.in);
12 | int length = scanner.nextInt();
13 | int threshold = scanner.nextInt();
14 | Queue minHeap = new PriorityQueue<>();
15 | while (length-- > 0) {
16 | minHeap.add(scanner.nextLong());
17 | }
18 | System.out.println(minimumOperations(minHeap, threshold));
19 | }
20 |
21 | private static int minimumOperations(Queue minHeap, int threshold) {
22 | int operations = 0;
23 | while (minHeap.peek() < threshold && minHeap.size() >= 2) {
24 | long cookie = minHeap.poll() + 2 * minHeap.poll();
25 | minHeap.add(cookie);
26 | operations++;
27 | }
28 |
29 | return minHeap.peek() >= threshold ? operations : -1 ;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/heap/MinimumAverageWaitingTime.java:
--------------------------------------------------------------------------------
1 | package heap;
2 |
3 | import java.util.Comparator;
4 | import java.util.PriorityQueue;
5 | import java.util.Queue;
6 | import java.util.Scanner;
7 |
8 | public class MinimumAverageWaitingTime {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 | int length = scanner.nextInt();
12 | Queue customers = new PriorityQueue<>(Comparator.comparing(Customer::getArrivalTime));
13 | while (length-- > 0) {
14 | int arrivalTime = scanner.nextInt();
15 | int processingTime = scanner.nextInt();
16 | customers.add(new Customer(arrivalTime, processingTime));
17 | }
18 | System.out.println(minimumAverageWaitingTime(customers));
19 | }
20 |
21 | private static long minimumAverageWaitingTime(Queue customers) {
22 | Queue processQueue = new PriorityQueue<>(
23 | Comparator.comparing(Customer::getProcessingTime)
24 | );
25 | processQueue.add(new Customer(0, 0));
26 |
27 | int totalCustomers = customers.size();
28 | int currentTime = 0;
29 | long waitingTime = 0;
30 |
31 | while (!processQueue.isEmpty()) {
32 | Customer customer = processQueue.poll();
33 | currentTime += customer.processingTime ;
34 | waitingTime += currentTime - customer.arrivalTime;
35 |
36 | while (!customers.isEmpty() && customers.peek().arrivalTime <= currentTime) {
37 | processQueue.add(customers.poll());
38 | }
39 |
40 | if (processQueue.isEmpty() && !customers.isEmpty()) {
41 | currentTime = customers.peek().arrivalTime;
42 | processQueue.add(new Customer(currentTime, 0));
43 | }
44 | }
45 |
46 | return waitingTime / totalCustomers;
47 | }
48 |
49 | private static class Customer {
50 | int arrivalTime;
51 | int processingTime;
52 |
53 | Customer(int arrivalTime, int processingTime) {
54 | this.arrivalTime = arrivalTime;
55 | this.processingTime = processingTime;
56 | }
57 |
58 | public int getArrivalTime() {
59 | return arrivalTime;
60 | }
61 |
62 | public int getProcessingTime() {
63 | return processingTime;
64 | }
65 |
66 | @Override
67 | public String toString() {
68 | return "Customer{" +
69 | "arrivalTime=" + arrivalTime +
70 | ", processingTime=" + processingTime +
71 | '}';
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/src/heap/QHEAP1.java:
--------------------------------------------------------------------------------
1 | // https://www.hackerrank.com/challenges/qheap1/problem
2 |
3 | package heap;
4 |
5 | import java.util.PriorityQueue;
6 | import java.util.Queue;
7 | import java.util.Scanner;
8 |
9 | public class QHEAP1 {
10 | public static void main(String[] args) {
11 | Scanner scanner = new Scanner(System.in);
12 | int queries = scanner.nextInt();
13 | Queue minHeap = new PriorityQueue<>();
14 | while (queries-- > 0) {
15 | int command = scanner.nextInt();
16 | if (command == 1) {
17 | int element = scanner.nextInt();
18 | minHeap.add(element);
19 | } else if (command == 2) {
20 | int element = scanner.nextInt();
21 | minHeap.remove(element);
22 | } else {
23 | System.out.println(minHeap.peek());
24 | }
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/helper/Input.java:
--------------------------------------------------------------------------------
1 | package helper;
2 |
3 | import java.util.Scanner;
4 |
5 | public class Input {
6 | private static final Scanner SCANNER = new Scanner(System.in);
7 |
8 | public static int[][] getMatrix(int rows, int columns) {
9 | int[][] data = new int[rows][columns];
10 | for (int row = 0 ; row < rows ; row++) {
11 | for (int column = 0 ; column < columns ; column++) {
12 | data[row][column] = SCANNER.nextInt();
13 | }
14 | }
15 | return data;
16 | }
17 |
18 | public static int getLength() {
19 | return SCANNER.nextInt();
20 | }
21 |
22 | public static int[] getArray() {
23 | return getArray(getLength());
24 | }
25 |
26 | public static int[] getArray(int length) {
27 | int[] array = new int[length];
28 | for (int index = 0 ; index < array.length ; index++) {
29 | array[index] = SCANNER.nextInt();
30 | }
31 | return array;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/linkedlist/Compare2LinkedList.java:
--------------------------------------------------------------------------------
1 | package linkedlist;
2 |
3 | import java.util.Scanner;
4 |
5 | public class Compare2LinkedList {
6 | public static void main(String[] args) {
7 | Scanner s = new Scanner(System.in);
8 | Node head1 = new Node();
9 | head1.input(1);
10 | Node head2 = new Node();
11 | head2.input(1);
12 |
13 | head1.print();
14 | head2.print();
15 |
16 | int ans = compare(head1, head2);
17 | System.out.println("\n" + ans);
18 | }
19 |
20 | private static int compare(Node head1, Node head2){
21 | Node temp1 = head1, temp2 = head2;
22 |
23 | if(head1.size() != head1.size())
24 | return 0;
25 |
26 | while (temp1 != null && temp2 != null){
27 | if(temp1.data != temp2.data)
28 | return 0;
29 | temp1 = temp1.next;
30 | temp2 = temp2.next;
31 | }
32 |
33 | return 1;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/linkedlist/CycleDetection.java:
--------------------------------------------------------------------------------
1 | package linkedlist;
2 |
3 | import java.util.HashMap;
4 |
5 | public class CycleDetection {
6 | public static void main(String[] args) {
7 | Node head = new Node();
8 | head.input(1);
9 |
10 | boolean ans = containsCycle(head);
11 | System.out.println(ans);
12 | }
13 |
14 | private static boolean containsCycle(Node head){
15 | HashMap map = new HashMap<>();
16 | Node temp = head;
17 |
18 | while (temp != null){
19 | if(map.containsKey(temp))
20 | return true;
21 | else map.put(temp, 1);
22 |
23 | temp = temp.next;
24 | }
25 |
26 | return false;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/linkedlist/DeleteANode.java:
--------------------------------------------------------------------------------
1 | package linkedlist;
2 |
3 | public class DeleteANode {
4 | static SinglyLinkedListNode deleteNode(SinglyLinkedListNode head, int position) {
5 | if (position == 0) {
6 | return head.next;
7 | }
8 |
9 | SinglyLinkedListNode current= head;
10 | while (position-- > 1) {
11 | current = current.next;
12 | }
13 | current.next = current.next.next;
14 | return head;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/linkedlist/DeleteDuplicateValueNodesFromSortedLinkedList.java:
--------------------------------------------------------------------------------
1 | package linkedlist;
2 |
3 | public class DeleteDuplicateValueNodesFromSortedLinkedList {
4 | public static void main(String[] args) {
5 | Node head = new Node();
6 | head.input(1);
7 | head.print();
8 |
9 | removeDuplicateNodes(head);
10 | System.out.println(); head.print();
11 | }
12 |
13 | private static void removeDuplicateNodes(Node head){
14 |
15 | Node temp = head.next, first = head;
16 | int nodeData = head.data;
17 |
18 | while (temp != null){
19 | if(temp.data == nodeData){
20 | first.next = temp.next;
21 | temp = temp.next;
22 | } else {
23 | nodeData = temp.data;
24 | first = first.next;
25 | temp = temp.next;
26 | }
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/linkedlist/FindMergePointOf2Lists.java:
--------------------------------------------------------------------------------
1 | package linkedlist;
2 |
3 | import java.util.HashMap;
4 |
5 | public class FindMergePointOf2Lists {
6 | public static void main(String[] args) {
7 | Node head1 = new Node();
8 | head1.input(1);
9 | Node head2 = new Node();
10 | head2.input(1);
11 |
12 | head1.print();
13 | System.out.println("");
14 | head2.print();
15 |
16 | int ans = firstCommonNode(head1, head2);
17 | System.out.println(ans);
18 | }
19 |
20 | private static int firstCommonNode(Node head1, Node head2){
21 | HashMap map = new HashMap<>();
22 | Node temp1 = head1;
23 | while (temp1 != null){
24 | map.put(temp1, 1);
25 | temp1 = temp1.next;
26 | }
27 |
28 | temp1 = head2;
29 | while (temp1 != null){
30 | if(map.containsKey(temp1))
31 | break;
32 |
33 | temp1 = temp1.next;
34 | }
35 |
36 | return temp1.data;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/linkedlist/GetNodeValue.java:
--------------------------------------------------------------------------------
1 | package linkedlist;
2 |
3 | import java.util.Scanner;
4 |
5 | public class GetNodeValue {
6 | public static void main(String[] args) {
7 | Scanner s = new Scanner(System.in);
8 | Node head = new Node();
9 | head.input(1);
10 | int position = s.nextInt();
11 | Node ans = nodeFromTail(head, position);
12 | System.out.println(ans.data);
13 | }
14 |
15 | private static Node nodeFromTail(Node head, int position){
16 | int length = head.size();
17 | Node temp = head;
18 | for(int i=0 ; i 1) {
13 | current = current.next;
14 | }
15 | SinglyLinkedListNode node = new SinglyLinkedListNode(data);
16 | node.next = current.next;
17 | current.next = node;
18 | return head;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/linkedlist/InsertNodeAtTailOfLinkedList.java:
--------------------------------------------------------------------------------
1 | package linkedlist;
2 |
3 | public class InsertNodeAtTailOfLinkedList {
4 | static SinglyLinkedListNode insertNodeAtTail(SinglyLinkedListNode head, int data) {
5 | if (head == null) {
6 | head = new SinglyLinkedListNode(data);
7 | return head;
8 | }
9 |
10 | SinglyLinkedListNode current = head;
11 | while (current.next != null) {
12 | current = current.next;
13 | }
14 | current.next = new SinglyLinkedListNode(data);
15 |
16 | return head;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/linkedlist/Merge2SortedLinkedList.java:
--------------------------------------------------------------------------------
1 | package linkedlist;
2 |
3 | import java.util.Scanner;
4 |
5 | public class Merge2SortedLinkedList {
6 | public static void main(String[] args) {
7 | Scanner s = new Scanner(System.in);
8 | Node head1 = new Node(), head2 = new Node();
9 | head1.input(1);
10 | head2.input(1);
11 |
12 | head1.print();
13 | System.out.println("");
14 | head2.print();
15 |
16 | Node head = merge(head1, head2);
17 | System.out.println("");
18 | head.print();
19 | }
20 |
21 | private static Node merge(Node head1, Node head2){
22 | Node ans = new Node(2);
23 | Node temp1, temp2, ansTemp;
24 | for(temp1 = head1, temp2 = head2, ansTemp = ans ; temp1 != null && temp2 != null ; ){
25 | if(temp1.data <= temp2.data){
26 | ansTemp.next = new Node(temp1.data);
27 | ansTemp = ansTemp.next;
28 | temp1 = temp1.next;
29 | } else {
30 | ansTemp.next = new Node(temp2.data);
31 | ansTemp = ansTemp.next;
32 | temp2 = temp2.next;
33 | }
34 | }
35 |
36 | if(temp1 == null){
37 | while (temp2 != null){
38 | ansTemp.next = new Node(temp2.data);
39 | ansTemp = ansTemp.next;
40 | temp2 = temp2.next;
41 | }
42 | } else {
43 | while (temp1 != null){
44 | ansTemp.next = new Node(temp1.data);
45 | ansTemp = ansTemp.next;
46 | temp1 = temp1.next;
47 | }
48 | }
49 |
50 | return ans.next;
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/linkedlist/Node.java:
--------------------------------------------------------------------------------
1 | package linkedlist;
2 |
3 | import java.util.Scanner;
4 |
5 | public class Node {
6 | int data;
7 | Node next;
8 |
9 | Node(int data){
10 | this.data = data;
11 | }
12 | Node(){ }
13 |
14 | public void input(int dat){
15 | this.data = dat;
16 | Node temp = this;
17 | Scanner s = new Scanner(System.in);
18 | while (data != -1){
19 | int data = s.nextInt();
20 | if(data == -1) {
21 | break;
22 | }
23 |
24 | Node newNode = new Node(data);
25 | temp.next = newNode;
26 | temp = temp.next;
27 | }
28 | }
29 |
30 | public void print(){
31 | Node temp = this;
32 | while (temp != null){
33 | System.out.print(temp.data + " ");
34 | temp = temp.next;
35 | }
36 | }
37 |
38 | public int size(){
39 | int count;
40 | Node temp = this;
41 | for(count=0 ; temp != null; count++){
42 | temp = temp.next;
43 | }
44 | return count;
45 | }
46 | }
47 |
48 |
49 | class DoublyLL{
50 | int data;
51 | DoublyLL next;
52 | DoublyLL prev;
53 |
54 | public void print(){
55 | DoublyLL temp = this;
56 | while (temp != null){
57 | System.out.print(temp.data + " ");
58 | temp = temp.next;
59 | }
60 | }
61 |
62 | public void input(){
63 | DoublyLL temp = this;
64 | Scanner s = new Scanner(System.in);
65 | while (data != -1){
66 |
67 | int data = s.nextInt();
68 |
69 | if(data == -1) {
70 | temp = null;
71 | break;
72 | }
73 |
74 | temp.data = data;
75 | temp.next = new DoublyLL();
76 | temp.next.prev = temp;
77 | temp = temp.next;
78 | }
79 | }
80 |
81 | DoublyLL(int data){
82 | this.data = data;
83 | }
84 | DoublyLL(DoublyLL node){
85 | this.data = node.data;
86 | }
87 | DoublyLL(Node node){
88 | this.data = node.data;
89 | }
90 | DoublyLL(){}
91 | }
92 |
--------------------------------------------------------------------------------
/src/linkedlist/PrintElementsOfLinkedList.java:
--------------------------------------------------------------------------------
1 | package linkedlist;
2 |
3 | public class PrintElementsOfLinkedList {
4 | static void printLinkedList(SinglyLinkedListNode head) {
5 | if (head != null) {
6 | System.out.println(head.data);
7 | printLinkedList(head.next);
8 | }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/linkedlist/PrintInReverse.java:
--------------------------------------------------------------------------------
1 | package linkedlist;
2 |
3 | import java.util.Scanner;
4 |
5 | public class PrintInReverse {
6 | public static void main(String[] args) {
7 | Scanner s = new Scanner(System.in);
8 | Node head = new Node();
9 | head.input(1);
10 | head.print();
11 |
12 | head = reverseLL(head);
13 | System.out.println("");
14 | head.print();
15 | }
16 |
17 | private static Node reverseLL(Node head){
18 | if(head.size() <= 1)
19 | return head;
20 | else if (head.size() == 2) {
21 | Node temp = head.next;
22 | temp.next = head;
23 | head.next = null;
24 | return temp;
25 | }
26 |
27 | Node first, second, third;
28 | for(first = head, second = first.next, third = second.next, first.next = null ; third != null ; first = second, second = third, third = third.next){
29 | second.next = first;
30 | }
31 | second.next = first;
32 | return second;
33 | }
34 | }
--------------------------------------------------------------------------------
/src/linkedlist/ReverseALinkedList.java:
--------------------------------------------------------------------------------
1 | package linkedlist;
2 |
3 | public class ReverseALinkedList {
4 | static SinglyLinkedListNode reverse(SinglyLinkedListNode head) {
5 | SinglyLinkedListNode current = null;
6 |
7 | for (SinglyLinkedListNode iter = head ; iter != null ; iter = iter.next) {
8 | SinglyLinkedListNode node = new SinglyLinkedListNode(iter.data);
9 | node.next = current;
10 | current = node;
11 | }
12 | return current;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/linkedlist/ReverseDoublyLinkedList.java:
--------------------------------------------------------------------------------
1 | package linkedlist;
2 |
3 | public class ReverseDoublyLinkedList {
4 | public static void main(String[] args) {
5 | DoublyLL head = new DoublyLL();
6 | head.input();
7 | head.print();
8 |
9 | head = reverse(head);
10 | System.out.println("");
11 | head.print();
12 | }
13 |
14 | private static DoublyLL reverse(DoublyLL head){
15 | if(size(head) <= 1){
16 | return head;
17 | }
18 |
19 | DoublyLL first = head, temp = head.next;
20 | while (temp != null){
21 | first.next = (first.prev == null ? null : first.prev) ;
22 | first.prev = temp;
23 |
24 | temp = temp.next;
25 | first = first.prev;
26 | }
27 |
28 | first.next = first.prev;
29 | first.prev = null;
30 |
31 | return first;
32 | }
33 |
34 | private static int size(DoublyLL head){
35 | int count=0;
36 | DoublyLL temp = head;
37 |
38 | while (temp != null){
39 | count++;
40 | temp = temp.next;
41 | }
42 |
43 | return count;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/linkedlist/SinglyLinkedListNode.java:
--------------------------------------------------------------------------------
1 | package linkedlist;
2 |
3 | public class SinglyLinkedListNode {
4 | int data;
5 | SinglyLinkedListNode next;
6 |
7 | SinglyLinkedListNode(int data) {
8 | this.data = data;
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/mcq/Data Structure MCQ 1.md:
--------------------------------------------------------------------------------
1 | __Question:__ If We have a Tree of `n` Nodes, how many Edges will it have?
2 |
3 | __Answer:__ `n - 1`
4 |
--------------------------------------------------------------------------------
/src/mcq/Data Structure MCQ 2.md:
--------------------------------------------------------------------------------
1 | __Question:__ Which of the Following data structures can handle updates and queries in
2 | `log(n)` time on an array?
3 |
4 | __Answer:__ Segment Tree
5 |
--------------------------------------------------------------------------------
/src/mcq/Data Structure MCQ 3.md:
--------------------------------------------------------------------------------
1 | __Question:__ Of the following data structures, which has a Last in First Out ordering?
2 | In other words, the one that came in last will be the first to be popped.
3 |
4 | __Answer:__ Stack
5 |
--------------------------------------------------------------------------------
/src/queues/CastleOnTheGrid.java:
--------------------------------------------------------------------------------
1 | // https://www.hackerrank.com/challenges/castle-on-the-grid/problem
2 |
3 | package queues;
4 |
5 | import java.util.HashMap;
6 | import java.util.LinkedList;
7 | import java.util.Map;
8 | import java.util.Objects;
9 | import java.util.Queue;
10 | import java.util.Scanner;
11 |
12 | public class CastleOnTheGrid {
13 | private static final Scanner scanner = new Scanner(System.in);
14 |
15 | public static void main(String[] args) {
16 | int length = scanner.nextInt();
17 | String[] grid = getGrid(length);
18 | int startX = scanner.nextInt();
19 | int startY = scanner.nextInt();
20 | int endX = scanner.nextInt();
21 | int endY = scanner.nextInt();
22 | Grid solution = new Grid(grid, new Position(startX, startY), new Position(endX, endY));
23 | System.out.println(solution.shortestPath());
24 | }
25 |
26 | private static class Position {
27 | private final int x;
28 | private final int y;
29 |
30 | Position(int x, int y) {
31 | this.x = x;
32 | this.y = y;
33 | }
34 |
35 | boolean notBlocked(String[] grid) {
36 | return grid[x].charAt(y) != 'X';
37 | }
38 |
39 | boolean isValidPosition(String[] grid) {
40 | return x < grid.length
41 | && x >= 0
42 | && y < grid[0].length()
43 | && y >= 0;
44 | }
45 |
46 | Position goUp() {
47 | return new Position(x - 1, y);
48 | }
49 |
50 | Position goRight() {
51 | return new Position(x, y + 1);
52 | }
53 |
54 | Position goDown() {
55 | return new Position(x + 1, y);
56 | }
57 |
58 | Position goLeft() {
59 | return new Position(x, y - 1);
60 | }
61 |
62 | @Override
63 | public boolean equals(Object o) {
64 | if (this == o) return true;
65 | if (o == null || getClass() != o.getClass()) return false;
66 | Position position = (Position) o;
67 | return x == position.x && y == position.y;
68 | }
69 |
70 | @Override
71 | public int hashCode() {
72 | return Objects.hash(x, y);
73 | }
74 |
75 | @Override
76 | public String toString() {
77 | return "(" +
78 | "" + x +
79 | ", " + y +
80 | ')';
81 | }
82 | }
83 |
84 | private static class Grid {
85 | private final String[] grid;
86 | private final Position source;
87 | private final Position destination;
88 | private final LateralMovement up = new UpLateralMovement();
89 | private final LateralMovement right = new RightLateralMovement();
90 | private final LateralMovement down = new DownLateralMovement();
91 | private final LateralMovement left = new LeftLateralMovement();
92 |
93 | Grid(String[] grid, Position source, Position destination) {
94 | this.grid = grid;
95 | this.source = source;
96 | this.destination = destination;
97 | }
98 |
99 | int shortestPath() {
100 | Map prefixPositions = new HashMap<>();
101 | prefixPositions.put(source, source);
102 | Queue queue = new LinkedList<>();
103 | queue.add(source);
104 |
105 | while (!queue.isEmpty()) {
106 | Position top = queue.poll();
107 | if (top.equals(destination)) {
108 | break;
109 | }
110 |
111 | addLateralVerticesToQueue(top, prefixPositions, queue);
112 | }
113 |
114 | return shortestPath(prefixPositions);
115 | }
116 |
117 | private abstract class LateralMovement {
118 | private void addLateralVerticesToQueue(Position position, Map prefixes, Queue queue) {
119 | Position current = position;
120 | while (current.isValidPosition(grid) && current.notBlocked(grid)) {
121 | if (!prefixes.containsKey(current)) {
122 | prefixes.put(current, position);
123 | queue.add(current);
124 | }
125 | current = lateralVertice(current);
126 | }
127 | }
128 |
129 | abstract Position lateralVertice(Position position);
130 | }
131 |
132 | private class UpLateralMovement extends LateralMovement {
133 | @Override
134 | Position lateralVertice(Position position) {
135 | return position.goUp();
136 | }
137 | }
138 |
139 | private class RightLateralMovement extends LateralMovement {
140 | @Override
141 | Position lateralVertice(Position position) {
142 | return position.goRight();
143 | }
144 | }
145 |
146 | private class DownLateralMovement extends LateralMovement {
147 | @Override
148 | Position lateralVertice(Position position) {
149 | return position.goDown();
150 | }
151 | }
152 |
153 | private class LeftLateralMovement extends LateralMovement {
154 | @Override
155 | Position lateralVertice(Position position) {
156 | return position.goLeft();
157 | }
158 | }
159 |
160 | private void addLateralVerticesToQueue(Position position, Map prefixes, Queue queue) {
161 | up.addLateralVerticesToQueue(position, prefixes, queue);
162 | right.addLateralVerticesToQueue(position, prefixes, queue);
163 | down.addLateralVerticesToQueue(position, prefixes, queue);
164 | left.addLateralVerticesToQueue(position, prefixes, queue);
165 | }
166 |
167 | private int shortestPath(Map prefixPositions) {
168 | return shortestPath(prefixPositions, this.destination);
169 | }
170 |
171 | private int shortestPath(Map prefixPositions, Position position) {
172 | if (position.equals(this.source)) {
173 | return 0;
174 | }
175 |
176 | return 1 + shortestPath(prefixPositions, prefixPositions.get(position));
177 | }
178 | }
179 |
180 | private static String[] getGrid(int length) {
181 | String[] array = new String[length];
182 | for (int index = 0 ; index < length ; index++) {
183 | array[index] = scanner.next();
184 | }
185 | return array;
186 | }
187 | }
188 |
--------------------------------------------------------------------------------
/src/queues/DownToZeroII.java:
--------------------------------------------------------------------------------
1 | package queues;
2 |
3 | import java.util.Scanner;
4 |
5 | public class DownToZeroII {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | int queries = scanner.nextInt();
9 | while (queries-- > 0) {
10 | int number = scanner.nextInt();
11 | System.out.println(ReductionSteps.minimumSteps(number));
12 | }
13 | }
14 |
15 | private static class ReductionSteps {
16 | private static final int length = 1_000_001;
17 | private static final int[] result = new int[length];
18 |
19 | static {
20 | result[0] = 0;
21 | result[1] = 1;
22 | result[2] = 2;
23 | result[3] = 3;
24 |
25 | for (int index = 2 ; index < length ; index++) {
26 | if (result[index] == 0 || result[index] > (result[index - 1] + 1)) {
27 | result[index] = result[index - 1] + 1;
28 | }
29 |
30 | for (int j = 2 ; j <= index && j * index < length ; j++) {
31 | if (result[index * j] == 0 || result[index * j] > (result[index] + 1)) {
32 | result[index * j] = result[index] + 1;
33 | }
34 | }
35 | }
36 | }
37 |
38 | private static int minimumSteps(int number) {
39 | return result[number];
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/queues/QueriesWithFixedLength.java:
--------------------------------------------------------------------------------
1 | package queues;
2 |
3 | import java.util.LinkedList;
4 | import java.util.Queue;
5 | import java.util.Scanner;
6 |
7 | public class QueriesWithFixedLength {
8 | private static final Scanner scanner = new Scanner(System.in);
9 |
10 | public static void main(String[] args) {
11 | int length = scanner.nextInt();
12 | int queries = scanner.nextInt();
13 | int[] array = getArray(length);
14 |
15 | while (queries-- > 0) {
16 | int query = scanner.nextInt();
17 | System.out.println(minimumIn(array, query));
18 | }
19 | }
20 |
21 | private static int minimumIn(int[] array, int subLength) {
22 | Queue window = new LinkedList<>();
23 | addElementsIn(window, subLength, array);
24 | int maximum = window.stream().max(Integer::compareTo).get();
25 | int minimum = maximum;
26 |
27 | for (int index = subLength ; index < array.length ; index++) {
28 | int removed = window.poll();
29 | int inserted = array[index];
30 | if (inserted >= maximum) {
31 | maximum = inserted;
32 | } else if (removed == maximum) {
33 | maximum = window.stream().max(Integer::compareTo).get();
34 | }
35 | window.add(inserted);
36 | minimum = Math.min(minimum, maximum);
37 | }
38 |
39 | return minimum;
40 | }
41 |
42 | private static void addElementsIn(Queue window, int length, int[] array) {
43 | for (int index = 0 ; index < length ; index++) {
44 | window.add(array[index]);
45 | }
46 | }
47 |
48 | private static int[] getArray(int length) {
49 | int[] array = new int[length];
50 | for (int index = 0 ; index < array.length ; index++) {
51 | array[index] = scanner.nextInt();
52 | }
53 | return array;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/queues/QueueUsingTwoStacks.java:
--------------------------------------------------------------------------------
1 | package queues;
2 |
3 | import java.util.LinkedList;
4 | import java.util.Scanner;
5 |
6 | public class QueueUsingTwoStacks {
7 |
8 | private static Scanner in = new Scanner(System.in);
9 |
10 | public static void main(String[] args) {
11 | int queries = in.nextInt();
12 | performQueries(queries);
13 | }
14 |
15 | private static void performQueries(int queries){
16 | LinkedList linkedList = new LinkedList<>();
17 |
18 | while (queries-- > 0){
19 | int type = in.nextInt();
20 | if(type == 1){
21 | int data = in.nextInt();
22 | linkedList.add(data);
23 | } else if(type == 2){
24 | linkedList.pop();
25 | } else {
26 | System.out.println(linkedList.peek());
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/queues/TruckTourProblem.java:
--------------------------------------------------------------------------------
1 | package queues;
2 |
3 | import java.util.Scanner;
4 |
5 | public class TruckTourProblem {
6 | public static void main(String[] args) {
7 | Scanner scanner = new Scanner(System.in);
8 | int length = scanner.nextInt();
9 | int[] petrol = new int[length];
10 | int[] distance = new int[length];
11 | for (int index = 0 ; index < length ; index++) {
12 | petrol[index] = scanner.nextInt();
13 | distance[index] = scanner.nextInt();
14 | }
15 |
16 | System.out.println(startIndex(petrol, distance));
17 | }
18 |
19 | private static int startIndex(int[] petrol, int[] distance) {
20 | int mod = petrol.length;
21 | for (int index = 0 ; index < petrol.length - 1 ; index++) {
22 | int current = 0, count = 0;
23 | boolean answer = true;
24 | for (int j = index ; count < 2; j = (j + 1) % mod) {
25 | if (j == index) {
26 | count++;
27 | }
28 |
29 | current += (petrol[j] - distance[j]);
30 |
31 | if (current < 0) {
32 | answer = false;
33 | break;
34 | }
35 | }
36 |
37 | if (answer) {
38 | return index;
39 | }
40 | }
41 | return mod - 1;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/stacks/BalancedBrackets.java:
--------------------------------------------------------------------------------
1 | // https://www.hackerrank.com/challenges/balanced-brackets/problem
2 |
3 | package stacks;
4 |
5 | import java.util.Scanner;
6 | import java.util.Stack;
7 |
8 | public class BalancedBrackets {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 | int queries = scanner.nextInt();
12 |
13 | while (queries-- > 0) {
14 | String string = scanner.next();
15 | System.out.println(isBalanced(string));
16 | }
17 | }
18 |
19 | private static String isBalanced(String string) {
20 | return isBalancedBrackets(string) ? "YES" : "NO" ;
21 | }
22 |
23 | private static boolean isBalancedBrackets(String string) {
24 | Stack brackets = new Stack<>();
25 | for (int index = 0 ; index < string.length() ; index++) {
26 | char character = string.charAt(index);
27 | if (isOpeningBrace(character)) {
28 | brackets.push(character);
29 | } else if (isClosingBrace(character)) {
30 | if (!brackets.isEmpty() && brackets.peek() == inverse(character)) {
31 | brackets.pop();
32 | } else {
33 | return false;
34 | }
35 | }
36 | }
37 |
38 | return brackets.isEmpty();
39 | }
40 |
41 | private static boolean isOpeningBrace(char character) {
42 | return character == '(' || character == '{' || character == '[';
43 | }
44 |
45 | private static boolean isClosingBrace(char character) {
46 | return character == ')' || character == '}' || character == ']';
47 | }
48 |
49 | private static char inverse(char character) {
50 | switch (character) {
51 | case '(' : return ')';
52 | case '{' : return '}';
53 | case '[' : return ']';
54 | case ')' : return '(';
55 | case '}' : return '{';
56 | case ']' : return '[';
57 | }
58 | return '-';
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/stacks/EqualStacks.java:
--------------------------------------------------------------------------------
1 | // https://www.hackerrank.com/challenges/equal-stacks/problem
2 |
3 | package stacks;
4 |
5 | import java.util.ArrayList;
6 | import java.util.Scanner;
7 | import java.util.Stack;
8 |
9 | public class EqualStacks {
10 | public static void main(String[] args) {
11 | Scanner scanner = new Scanner(System.in);
12 | int[] blocks = new int[3], sum = new int[3];
13 |
14 | for (int index = 0 ; index < blocks.length ; index++) {
15 | blocks[index] = scanner.nextInt();
16 | }
17 |
18 | ArrayList> stacks = new ArrayList<>();
19 | for (int index = 0 ; index < blocks.length ; index++) {
20 | int[] array = new int[blocks[index]];
21 | for (int count = 0 ; count < blocks[index] ; count++) {
22 | int element = scanner.nextInt();
23 | array[count] = element;
24 | sum[index] += element;
25 | }
26 | stacks.add(stackFrom(array));
27 | }
28 |
29 | while (!equal(sum)) {
30 | int maxStackIndex = maxIndex(sum);
31 | sum[maxStackIndex] -= stacks.get(maxStackIndex).pop();
32 | }
33 |
34 | System.out.println(sum[0]);
35 | }
36 |
37 | private static Stack stackFrom(int[] array) {
38 | Stack stack = new Stack<>();
39 | for (int index = array.length - 1 ; index >= 0 ; index--) {
40 | stack.push(array[index]);
41 | }
42 | return stack;
43 | }
44 |
45 | private static boolean equal(int[] array) {
46 | int element = array[0];
47 | for (int index = 1 ; index < array.length ; index++) {
48 | if (array[index] != element) {
49 | return false;
50 | }
51 | }
52 |
53 | return true;
54 | }
55 |
56 | private static int maxIndex(int[] array) {
57 | int max = array[0], result = 0;
58 | for (int index = 1 ; index < array.length ; index++) {
59 | if (array[index] > max) {
60 | max = array[index];
61 | result = index;
62 | }
63 | }
64 |
65 | return result;
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/stacks/GameOfTwoStacks.java:
--------------------------------------------------------------------------------
1 | package stacks;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Scanner;
5 | import java.util.Stack;
6 |
7 | public class GameOfTwoStacks {
8 |
9 | private static Scanner in = new Scanner(System.in);
10 |
11 | public static void main(String[] args) {
12 | int games = in.nextInt();
13 | while (games-- > 0){
14 | runGame();
15 | }
16 | }
17 |
18 | private static void runGame(){
19 | int n = in.nextInt();
20 | int m = in.nextInt();
21 | long maxSum = in.nextLong();
22 |
23 | int arr[] = new int[n];
24 | for(int index = 0 ; index left = new Stack<>();
28 | addToStack(left, arr);
29 |
30 | arr = new int[m];
31 | for(int index = 0 ; index right = new Stack<>();
35 | addToStack(right, arr);
36 |
37 | //print(left);
38 | //print(right);
39 |
40 | int maxElementsRemoved = maxElementsRemovedFromStack(left, right, maxSum);
41 | System.out.println(maxElementsRemoved);
42 | }
43 |
44 | private static int maxElementsRemovedFromStack(Stack left, Stack right, long sum){
45 | ArrayList leftList = indexing(left, sum);
46 | ArrayList rightList = indexing(right, sum);
47 |
48 | if(leftList.size() > rightList.size()){
49 | ArrayList tempList = leftList;
50 | leftList = rightList;
51 | rightList = tempList;
52 | }
53 | print(leftList);
54 | print(rightList);
55 |
56 | if(leftList.size() == 0)
57 | return (rightList.size() == 0) ? 0 : rightList.get(rightList.size()-1).pieces;
58 |
59 | int maxPieces = rightList.get(rightList.size()-1).pieces;
60 |
61 | for(int index = 0 ; index sum) break;
64 |
65 | long otherSum = sum - currentSum;
66 | int otherIndex = parse(binarySearch(rightList, otherSum), otherSum, rightList.get(0).sum);
67 | maxPieces = (otherIndex != -1) ? Math.max(maxPieces, leftList.get(index).pieces + rightList.get(otherIndex).pieces) :
68 | Math.max(maxPieces, leftList.get(index).pieces);
69 | }
70 |
71 | return maxPieces;
72 | }
73 |
74 | private static int parse(int index, long element, long first){
75 | if(index == 0 && element < first)
76 | return -1;
77 |
78 | return index;
79 | }
80 |
81 | private static int binarySearch(ArrayList list, long element){
82 | int tail, head;
83 | for(tail =0, head = list.size() ; tail < head-1 ; ){
84 | if(list.get((tail + head)/2).sum == element)
85 | return (tail+head)/2;
86 |
87 | else if(list.get((tail + head)/2).sum < element){
88 | tail = (tail+head)/2;
89 | }
90 | else {
91 | head = (head + tail)/2;
92 | }
93 | }
94 |
95 | return (tail + head)/2;
96 | }
97 |
98 | private static ArrayList indexing(Stack stack, long sum){
99 | ArrayList list = new ArrayList<>();
100 | if(stack.elementAt(stack.size()-1) <= sum)
101 | list.add(new Element(stack.elementAt(stack.size()-1), 1));
102 | else {
103 | return new ArrayList();
104 | }
105 |
106 | int maxElements = 0;
107 | Long currentSum = (long)stack.peek();
108 |
109 | for(int index = stack.size()-2 ; index>=0 ; index--){
110 | int element = stack.elementAt(index);
111 | if(currentSum + element > sum) break;
112 |
113 | int previousPieces = list.get(list.size()-1).pieces;
114 | if(list.get(list.size()-1).sum == currentSum + element){
115 | list.remove(list.size()-1);
116 | list.add(new Element(currentSum , previousPieces + 1));
117 | } else {
118 | list.add(new Element(currentSum + element, previousPieces + 1));
119 | }
120 | currentSum += element;
121 | }
122 |
123 | return list;
124 | }
125 |
126 | private static void addToStack(Stack stack, int arr[]){
127 | for(int index = arr.length -1 ; index>=0 ; index--){
128 | stack.push(arr[index]);
129 | }
130 | }
131 |
132 | private static void print(Stack stack){
133 | System.out.println("");
134 | for(int index = 0 ; index list){
140 | System.out.println("");
141 | for(int index = 0 ; index stack = new Stack<>();
17 | long area = 0;
18 |
19 | for (int index = 0 ; index < heights.length ; index++) {
20 | while (!stack.isEmpty() && (heights[index] < stack.peek().element)) {
21 | Info top = stack.pop();
22 | area = Math.max(area, calculateArea(top.element, stack, index));
23 | }
24 | stack.push(new Info(heights[index], index));
25 | }
26 |
27 | while (!stack.isEmpty()) {
28 | Info top = stack.pop();
29 | area = Math.max(area,calculateArea(top.element, stack, heights.length));
30 | }
31 |
32 | return area;
33 | }
34 |
35 | private static long calculateArea(int element, Stack stack, int index) {
36 | int startIndex = stack.isEmpty() ? -1 : stack.peek().index;
37 | return element * (index - startIndex - 1);
38 | }
39 |
40 | private static class Info {
41 | int element;
42 | int index;
43 |
44 | Info(int element, int index) {
45 | this.element = element;
46 | this.index = index;
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/stacks/MaximumElement.java:
--------------------------------------------------------------------------------
1 | // https://www.hackerrank.com/challenges/maximum-element/problem
2 |
3 | package stacks;
4 |
5 | import java.util.Comparator;
6 | import java.util.PriorityQueue;
7 | import java.util.Scanner;
8 | import java.util.Stack;
9 |
10 | public class MaximumElement {
11 | public static void main(String[] args) {
12 | Scanner scanner = new Scanner(System.in);
13 | int queries = scanner.nextInt();
14 | PriorityQueue queue = new PriorityQueue<>((o1, o2) -> Integer.compare(o2, o1));
15 | Stack stack = new Stack<>();
16 |
17 | while (queries-- > 0) {
18 | int type = scanner.nextInt();
19 | if (type == 1) {
20 | int element = scanner.nextInt();
21 | stack.add(element);
22 | queue.add(element);
23 | } else if (type == 2) {
24 | int element = stack.pop();
25 | queue.remove(element);
26 | } else {
27 | System.out.println(queue.peek());
28 | }
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/stacks/PoisonousPlants.java:
--------------------------------------------------------------------------------
1 | // https://www.hackerrank.com/challenges/poisonous-plants/problem
2 |
3 | package stacks;
4 |
5 | import helper.Input;
6 | import java.util.Stack;
7 |
8 | public class PoisonousPlants {
9 | public static void main(String[] args) {
10 | int[] plants = Input.getArray();
11 | System.out.println(daysToSafety(plants));
12 | }
13 |
14 | private static int daysToSafety(int[] plants) {
15 | int minimumDays = 0;
16 | Stack stack = new Stack<>();
17 | stack.push(new Info(plants[0], 0, false, 0));
18 | for (int index = 1, days = 0 ; index < plants.length ; index++) {
19 | if (plants[index] > stack.peek().element) {
20 | stack.push(new Info(plants[index], index, true, days + 1));
21 | minimumDays = Math.max(minimumDays, days + 1);
22 | days = 0;
23 | } else {
24 | if (!stack.peek().removable) {
25 | stack.push(new Info(plants[index], index, false, 0));
26 | days = 0;
27 | } else {
28 | int barrier = stack.peek().days;
29 | while (stack.peek().removable && stack.peek().days <= barrier) {
30 | Info info = stack.pop();
31 | days = info.days;
32 | minimumDays = Math.max(minimumDays, days);
33 | }
34 | index--;
35 | }
36 | }
37 | }
38 | return minimumDays;
39 | }
40 |
41 | private static class Info {
42 | int element;
43 | int index;
44 | boolean removable;
45 | int days;
46 |
47 | Info(int element, int index, boolean removable, int days) {
48 | this.element = element;
49 | this.index = index;
50 | this.removable = removable;
51 | this.days = days;
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/stacks/SimpleTextEditor.java:
--------------------------------------------------------------------------------
1 | package stacks;
2 |
3 | import java.util.Scanner;
4 | import java.util.Stack;
5 |
6 | public class SimpleTextEditor {
7 | private static Scanner in = new Scanner(System.in);
8 |
9 | public static void main(String args[]){
10 | int queries = in.nextInt();
11 | performQueries(queries);
12 | }
13 |
14 | private static void performQueries(int queries){
15 | Stack stack = new Stack<>();
16 | stack.push("");
17 |
18 | while (queries-- > 0){
19 | int queryType = in.nextInt();
20 |
21 | if(queryType == 1){
22 | String string = in.next();
23 | stack.push(stack.peek() + string);
24 | } else if(queryType == 2){
25 | int k = in.nextInt();
26 | stack.push(stack.peek().substring(0, stack.peek().length()-k));
27 | } else if(queryType == 3){
28 | int k = in.nextInt();
29 | System.out.println(stack.peek().charAt(k-1));
30 | } else {
31 | stack.pop();
32 | }
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/stacks/Waiter.java:
--------------------------------------------------------------------------------
1 | package stacks;
2 |
3 | import java.util.Scanner;
4 | import java.util.Stack;
5 |
6 | public class Waiter {
7 | private static Scanner in = new Scanner(System.in);
8 |
9 | public static void main(String[] args) {
10 | int size = in.nextInt();
11 | int iteration = in.nextInt();
12 | Stack mainStack = new Stack<>();
13 |
14 | for (int index = 0; index < size; index++) {
15 | int data = in.nextInt();
16 | mainStack.push(data);
17 | }
18 |
19 | performOperations(mainStack, iteration);
20 | }
21 |
22 | private static void performOperations(Stack mainStack, int iteration) {
23 | Stack secondaryStack = new Stack<>();
24 | Stack[] b = new Stack[iteration];
25 | int prime[] = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,
26 | 137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,
27 | 277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,
28 | 439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,
29 | 607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,
30 | 773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,
31 | 967,971,977,983,991,997,1009,1013,1019,1021,1031,1033,1039,1049,1051,1061,1063,1069,1087,1091,1093,1097,
32 | 1103,1109,1117,1123,1129,1151,1153,1163,1171,1181,1187,1193,1201,1213,1217,1223,1229,1231,1237,1249,1259,
33 | 1277,1279,1283,1289,1291,1297,1301,1303,1307,1319,1321,1327,1361,1367,1373,1381,1399,1409,1423,1427,1429,
34 | 1433,1439,1447,1451,1453,1459,1471,1481,1483,1487,1489,1493,1499,1511,1523,1531,1543,1549,1553,1559,1567,
35 | 1571,1579,1583,1597,1601,1607,1609,1613,1619,1621,1627,1637,1657,1663,1667,1669,1693,1697,1699,1709,1721,
36 | 1723,1733,1741,1747,1753,1759,1777,1783,1787,1789,1801,1811,1823,1831,1847,1861,1867,1871,1873,1877,1879,
37 | 1889,1901,1907,1913,1931,1933,1949,1951,1973,1979,1987,1993,1997,1999,2003,2011,2017,2027,2029,2039,2053,
38 | 2063,2069,2081,2083,2087,2089,2099,2111,2113,2129,2131,2137,2141,2143,2153,2161,2179,2203,2207,2213,2221,
39 | 2237,2239,2243,2251,2267,2269,2273,2281,2287,2293,2297,2309,2311,2333,2339,2341,2347,2351,2357,2371,2377,
40 | 2381,2383,2389,2393,2399,2411,2417,2423,2437,2441,2447,2459,2467,2473,2477,2503,2521,2531,2539,2543,2549,
41 | 2551,2557,2579,2591,2593,2609,2617,2621,2633,2647,2657,2659,2663,2671,2677,2683,2687,2689,2693,2699,2707,
42 | 2711,2713,2719,2729,2731,2741,2749,2753,2767,2777,2789,2791,2797,2801,2803,2819,2833,2837,2843,2851,2857,
43 | 2861,2879,2887,2897,2903,2909,2917,2927,2939,2953,2957,2963,2969,2971,2999,3001,3011,3019,3023,3037,3041,
44 | 3049,3061,3067,3079,3083,3089,3109,3119,3121,3137,3163,3167,3169,3181,3187,3191,3203,3209,3217,3221,3229,
45 | 3251,3253,3257,3259,3271,3299,3301,3307,3313,3319,3323,3329,3331,3343,3347,3359,3361,3371,3373,3389,3391,
46 | 3407,3413,3433,3449,3457,3461,3463,3467,3469,3491,3499,3511,3517,3527,3529,3533,3539,3541,3547,3557,3559,
47 | 3571,3581,3583,3593,3607,3613,3617,3623,3631,3637,3643,3659,3671,3673,3677,3691,3697,3701,3709,3719,3727,
48 | 3733,3739,3761,3767,3769,3779,3793,3797,3803,3821,3823,3833,3847,3851,3853,3863,3877,3881,3889,3907,3911,
49 | 3917,3919,3923,3929,3931,3943,3947,3967,3989,4001,4003,4007,4013,4019,4021,4027,4049,4051,4057,4073,4079,
50 | 4091,4093,4099,4111,4127,4129,4133,4139,4153,4157,4159,4177,4201,4211,4217,4219,4229,4231,4241,4243,4253,
51 | 4259,4261,4271,4273,4283,4289,4297,4327,4337,4339,4349,4357,4363,4373,4391,4397,4409,4421,4423,4441,4447,
52 | 4451,4457,4463,4481,4483,4493,4507,4513,4517,4519,4523,4547,4549,4561,4567,4583,4591,4597,4603,4621,4637,
53 | 4639,4643,4649,4651,4657,4663,4673,4679,4691,4703,4721,4723,4729,4733,4751,4759,4783,4787,4789,4793,4799,
54 | 4801,4813,4817,4831,4861,4871,4877,4889,4903,4909,4919,4931,4933,4937,4943,4951,4957,4967,4969,4973,4987,
55 | 4993,4999,5003,5009,5011,5021,5023,5039,5051,5059,5077,5081,5087,5099,5101,5107,5113,5119,5147,5153,5167,
56 | 5171,5179,5189,5197,5209,5227,5231,5233,5237,5261,5273,5279,5281,5297,5303,5309,5323,5333,5347,5351,5381,
57 | 5387,5393,5399,5407,5413,5417,5419,5431,5437,5441,5443,5449,5471,5477,5479,5483,5501,5503,5507,5519,5521,
58 | 5527,5531,5557,5563,5569,5573,5581,5591,5623,5639,5641,5647,5651,5653,5657,5659,5669,5683,5689,5693,5701,
59 | 5711,5717,5737,5741,5743,5749,5779,5783,5791,5801,5807,5813,5821,5827,5839,5843,5849,5851,5857,5861,5867,
60 | 5869,5879,5881,5897,5903,5923,5927,5939,5953,5981,5987,6007,6011,6029,6037,6043,6047,6053,6067,6073,6079,
61 | 6089,6091,6101,6113,6121,6131,6133,6143,6151,6163,6173,6197,6199,6203,6211,6217,6221,6229,6247,6257,6263,
62 | 6269,6271,6277,6287,6299,6301,6311,6317,6323,6329,6337,6343,6353,6359,6361,6367,6373,6379,6389,6397,6421,
63 | 6427,6449,6451,6469,6473,6481,6491,6521,6529,6547,6551,6553,6563,6569,6571,6577,6581,6599,6607,6619,6637,
64 | 6653,6659,6661,6673,6679,6689,6691,6701,6703,6709,6719,6733,6737,6761,6763,6779,6781,6791,6793,6803,6823,
65 | 6827,6829,6833,6841,6857,6863,6869,6871,6883,6899,6907,6911,6917,6947,6949,6959,6961,6967,6971,6977,6983,
66 | 6991,6997,7001,7013,7019,7027,7039,7043,7057,7069,7079,7103,7109,7121,7127,7129,7151,7159,7177,7187,7193,
67 | 7207,7211,7213,7219,7229,7237,7243,7247,7253,7283,7297,7307,7309,7321,7331,7333,7349,7351,7369,7393,7411,
68 | 7417,7433,7451,7457,7459,7477,7481,7487,7489,7499,7507,7517,7523,7529,7537,7541,7547,7549,7559,7561,7573,
69 | 7577,7583,7589,7591,7603,7607,7621,7639,7643,7649,7669,7673,7681,7687,7691,7699,7703,7717,7723,7727,7741,
70 | 7753,7757,7759,7789,7793,7817,7823,7829,7841,7853,7867,7873,7877,7879,7883,7901,7907,7919,7927,7933,7937,
71 | 7949,7951,7963,7993,8009,8011,8017,8039,8053,8059,8069,8081,8087,8089,8093,8101,8111,8117,8123,8147,8161,
72 | 8167,8171,8179,8191,8209,8219,8221,8231,8233,8237,8243,8263,8269,8273,8287,8291,8293,8297,8311,8317,8329,
73 | 8353,8363,8369,8377,8387,8389,8419,8423,8429,8431,8443,8447,8461,8467,8501,8513,8521,8527,8537,8539,8543,
74 | 8563,8573,8581,8597,8599,8609,8623,8627,8629,8641,8647,8663,8669,8677,8681,8689,8693,8699,8707,8713,8719,
75 | 8731,8737,8741,8747,8753,8761,8779,8783,8803,8807,8819,8821,8831,8837,8839,8849,8861,8863,8867,8887,8893,
76 | 8923,8929,8933,8941,8951,8963,8969,8971,8999,9001,9007,9011,9013,9029,9041,9043,9049,9059,9067,9091,9103,
77 | 9109,9127,9133,9137,9151,9157,9161,9173,9181,9187,9199,9203,9209,9221,9227,9239,9241,9257,9277,9281,9283,
78 | 9293,9311,9319,9323,9337,9341,9343,9349,9371,9377,9391,9397,9403,9413,9419,9421,9431,9433,9437,9439,9461,
79 | 9463,9467,9473,9479,9491,9497,9511,9521,9533,9539,9547,9551,9587,9601,9613,9619,9623,9629,9631,9643,9649,
80 | 9661,9677,9679,9689,9697,9719,9721,9733 };
81 |
82 | for(int iterator =0 ; iterator();
84 | while (!mainStack.isEmpty()){
85 | int element = mainStack.pop();
86 | if (element % prime[iterator] == 0)
87 | b[iterator].push(element);
88 | else secondaryStack.push(element);
89 | }
90 | Stack tempStack = mainStack;
91 | mainStack = secondaryStack;
92 | secondaryStack = tempStack;
93 | }
94 |
95 | printStacks(mainStack, b);
96 | }
97 |
98 | private static void printStacks(Stack mainStack, Stack[] b){
99 | for(int index=0 ; index stack){
106 | while (!stack.isEmpty()){
107 | System.out.println(stack.pop());
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/src/stacks/poisonous-plants.txt:
--------------------------------------------------------------------------------
1 | Input 00
2 | 7
3 | 6 5 8 4 7 10 9
4 | Output 00
5 | 2
6 |
7 | Input 7
8 | 8
9 | 3 1 10 7 3 5 6 6
10 | Output 7
11 | 3
12 |
13 | Input 29
14 | 4
15 | 3 2 5 4
16 | Output 29
17 | 2
18 |
19 |
20 | Input 30
21 | 7
22 | 4 3 7 5 6 4 2
23 | Output 30
24 | 3
--------------------------------------------------------------------------------
/src/trees/BST_Insertion.java:
--------------------------------------------------------------------------------
1 | package trees;
2 |
3 | import java.util.Scanner;
4 |
5 | public class BST_Insertion {
6 |
7 | public static void main(String[] args) {
8 | Tree root = new Tree<>();
9 | root.input();
10 | root.print();
11 |
12 | Scanner s = new Scanner(System.in);
13 | int data = s.nextInt();
14 |
15 | root = insert(root, data);
16 | System.out.println();
17 | root.print();
18 | }
19 |
20 | private static Tree insert(Tree root, int data){
21 | if(root == null){
22 | Tree obj = new Tree<>(data);
23 | return obj;
24 | }
25 |
26 | if(data < root.data){
27 | if(root.left != null) insert(root.left, data);
28 | else {
29 | root.left = new Tree<>(data);
30 | return root;
31 | }
32 | } else {
33 | if(root.right != null) insert(root.right, data);
34 | else {
35 | root.right = new Tree<>(data);
36 | return root;
37 | }
38 | }
39 |
40 | return root;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/trees/CustomTree.java:
--------------------------------------------------------------------------------
1 | package trees;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashMap;
5 | import java.util.Scanner;
6 |
7 | class CustomTree {
8 | private Scanner s = new Scanner(System.in);
9 |
10 | T data;
11 | int frequency;
12 | CustomTree left;
13 | CustomTree right;
14 |
15 | CustomTree(){}
16 | CustomTree(T data){
17 | this.data = data;
18 | }
19 |
20 | public void input(){
21 | input(this);
22 | }
23 |
24 | private CustomTree input(CustomTree root){
25 | System.out.print("Enter Data : ");
26 | int data = s.nextInt();
27 |
28 | if(data != -1)
29 | root.data = data;
30 | else return null;
31 |
32 | root.left = input(new CustomTree());
33 | root.right = input(new CustomTree());
34 |
35 | return root;
36 | }
37 |
38 | public void print(){
39 | print(this);
40 | }
41 |
42 | private void print(CustomTree root){
43 | if(root == null)
44 | return;
45 |
46 | System.out.println(root.data + " : " +
47 | (root.left == null ? "NULL " : root.left.data) + " " + (root.right == null ? "NULL " : root.right.data) );
48 |
49 | print(root.left);
50 | print(root.right);
51 | }
52 | }
53 |
54 | class MultipleDataTree {
55 | A data;
56 | B frequency;
57 | MultipleDataTree left;
58 | MultipleDataTree right;
59 |
60 | MultipleDataTree(){}
61 | MultipleDataTree(A data){
62 | this.data = data;
63 | }
64 | MultipleDataTree(A data, B frequency){
65 | this.frequency = frequency;
66 | this.data = data;
67 | }
68 | }
69 |
70 | class Vertex {
71 | ArrayList edgeList;
72 | int data;
73 |
74 | Vertex(int data){
75 | this.data = data;
76 | edgeList = new ArrayList<>();
77 | }
78 | Vertex(){}
79 |
80 | public void addEdge(Edge edge){
81 | edgeList.add(edge);
82 | }
83 | }
84 |
85 | class Edge{
86 | Vertex to, from;
87 | int connectionData;
88 |
89 | Edge(){}
90 | Edge(int connectionData){
91 | this.connectionData = connectionData;
92 | to = new Vertex();
93 | from = new Vertex();
94 | }
95 | Edge(int connectionData, Vertex to, Vertex from){
96 | this.connectionData = connectionData;
97 | this.to = to;
98 | this.from = from;
99 | }
100 | }
101 |
102 | class graph{
103 | private HashMap vertexMap = new HashMap<>();
104 | private HashMap vertexObjectHashMap;
105 | private int vertices;
106 |
107 | graph(){
108 | vertexMap = new HashMap<>();
109 | vertexObjectHashMap = new HashMap<>();
110 | vertices = 0;
111 | }
112 |
113 | public boolean addVertex(int data) {
114 | if(vertexMap.containsKey(data))
115 | return false;
116 |
117 | Vertex vertex = new Vertex(data);
118 | vertexMap.put(data, vertex);
119 | vertexObjectHashMap.put(vertex, new Object());
120 | vertices++;
121 | return true;
122 | }
123 |
124 | public boolean removeVertex(int data){
125 | if(vertexMap.containsKey(data)){
126 | vertexMap.remove(data);
127 | vertices--;
128 | return true;
129 | }
130 | return false;
131 | }
132 |
133 | public boolean removeVertex(Vertex vertex){
134 | if(vertexObjectHashMap.containsKey(vertex)){
135 | vertexObjectHashMap.remove(vertex);
136 | vertices--;
137 | return true;
138 | }
139 | return false;
140 | }
141 |
142 | public boolean addEdge(int connectionData, Vertex to, Vertex from){
143 | Edge edge = new Edge(connectionData, to, from);
144 | to.addEdge(edge);
145 | from.addEdge(edge);
146 | return true;
147 | }
148 |
149 | public boolean addEdge(int connectionData, int vertexData1, int vertexData2){
150 | Edge edge = new Edge(connectionData, vertexMap.get(vertexData1), vertexMap.get(vertexData2));
151 |
152 | if(vertexMap.containsKey(vertexData1)) vertexMap.get(vertexData1).addEdge(edge);
153 | else return false;
154 |
155 | if(vertexMap.containsKey(vertexData2)) vertexMap.get(vertexData2).addEdge(edge);
156 | else return false;
157 |
158 | return true;
159 | }
160 |
161 | public Vertex getVertex(int data){
162 | if(vertexMap.containsKey(data))
163 | return vertexMap.get(data);
164 |
165 | return new Vertex();
166 | }
167 |
168 | public void print(){
169 | print(getVertex(1));
170 | }
171 |
172 | private static void print(Vertex vertex){
173 | if(vertex == null)
174 | return;
175 |
176 | System.out.println(vertex.data + " : ");
177 | for(int index = 0 ; index root = new CustomTree<>();
6 | root.input();
7 | root.print();
8 |
9 | boolean ans = isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
10 | System.out.println(ans);
11 | }
12 |
13 | private static boolean isBST(CustomTree root, int minValue, int maxValue){
14 | if(root == null)
15 | return true;
16 |
17 | boolean left, right;
18 |
19 | if(root.left != null) left = (root.left.data < root.data) && (root.left.data > minValue);
20 | else left = true;
21 |
22 | if(root.right != null) right = (root.right.data > root.data) && (root.right.data < maxValue);
23 | else right = true;
24 |
25 | return left && right && isBST(root.left, minValue, root.data) && isBST(root.right, root.data, maxValue);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/trees/KitysCalculationOnATree.cpp:
--------------------------------------------------------------------------------
1 | // Solution Provided by Jesse Sparks
2 | // See GitHub: https://github.com/jsparks125
3 |
4 | #include
5 | #include
6 | #include
7 | #include