├── .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 | [![Python](icon-link)](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 | ![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png) | https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png | 46 | | Python | ![Python](https://img.icons8.com/color/35/000000/python.png) | https://img.icons8.com/color/35/000000/python.png | 47 | | C | ![C](https://img.icons8.com/color/35/000000/c-programming.png) | https://img.icons8.com/color/35/000000/c-programming.png | 48 | | C++ | ![C++](https://img.icons8.com/color/35/000000/c-plus-plus-logo.png) | https://img.icons8.com/color/35/000000/c-plus-plus-logo.png | 49 | | C# | ![C#](https://img.icons8.com/color/35/000000/c-sharp-logo.png) | https://img.icons8.com/color/35/000000/c-sharp-logo.png | 50 | | JavaScript | ![JavaScript](https://img.icons8.com/color/40/000000/javascript.png) | https://img.icons8.com/color/40/000000/javascript.png | 51 | | TypeScript | ![TypeScript](https://img.icons8.com/color/40/000000/typescript.png) | https://img.icons8.com/color/40/000000/typescript.png | 52 | | Ruby | ![Ruby](https://img.icons8.com/office/35/000000/ruby-programming-language.png) | https://img.icons8.com/office/35/000000/ruby-programming-language.png | 53 | | Scala | ![Scala](https://img.icons8.com/dusk/35/000000/scala.png) | https://img.icons8.com/office/35/000000/ruby-programming-language.png | 54 | | PGH | ![PHP](https://img.icons8.com/officel/40/000000/php-logo.png) | https://img.icons8.com/officel/40/000000/php-logo.png | 55 | | Swift | ![Swift](https://img.icons8.com/fluent/40/000000/swift.png) | https://img.icons8.com/fluent/40/000000/swift.png | 56 | | Markdown | ![Markdown](https://img.icons8.com/office/35/000000/markdown.png) | 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 | ![problems-solved](https://img.shields.io/badge/Problems%20Solved-57/121-1f425f.svg) 4 | ![java](https://img.shields.io/badge/Java-51/121-1abc9c.svg) 5 | ![python](https://img.shields.io/badge/Python-3/121-1abc9c.svg) 6 | ![cpp](https://img.shields.io/badge/C++-2/121-1abc9c.svg) 7 | ![md](https://img.shields.io/badge/Markdown-3/3-1abc9c.svg) 8 | [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md) 9 | [![cp](https://img.shields.io/badge/also%20see-Competitve%20Programming-1f72ff.svg)](https://github.com/anishLearnsToCode/competitive-programming) 10 | [![cp](https://img.shields.io/badge/also%20see-My%20Hackerrank%20Profile-1f72ff.svg)](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 ![problems-solved](https://img.shields.io/badge/Solved-6/6-1abc9c.svg) 40 | 41 | | Problem | Difficulty Level | Solution Link | 42 | |---------|------------------|:-------------:| 43 | | [Arrays - DS](https://www.hackerrank.com/challenges/arrays-ds) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/arrays/ArraysDS.java) | 44 | | [2D Arrays - DS](https://www.hackerrank.com/challenges/2d-array) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/arrays/TwoDArrays.java) | 45 | | [Dynamic Array](https://www.hackerrank.com/challenges/dynamic-array) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/arrays/DynamicArray.java) | 46 | | [Left Rotation](https://www.hackerrank.com/challenges/array-left-rotation) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/arrays/LeftRotation.java) | 47 | | [Sparse Arrays](https://www.hackerrank.com/challenges/arrays-ds) | Medium | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/arrays/SparseArrays.java) | 48 | | [Array Manipulation](https://www.hackerrank.com/challenges/crush) | Hard | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/arrays/ArrayManipulation.java) | 49 | 50 | ### Linked Lists ![problems-solved](https://img.shields.io/badge/Solved-15/15-1abc9c.svg) 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 | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](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 | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](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 | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](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 | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/linkedlist/InsertNodeAtSpecificPosition.java) | 57 | | [Delete a Node](https://www.hackerrank.com/challenges/delete-a-node-from-a-linked-list) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/linkedlist/DeleteANode.java) | 58 | | [Print in Reverse](https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list-in-reverse) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/linkedlist/PrintInReverse.java) | 59 | | [Reverse a Linked List](https://www.hackerrank.com/challenges/reverse-a-linked-list) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/linkedlist/ReverseALinkedList.java) | 60 | | [Compare two Linked Lists](https://www.hackerrank.com/challenges/compare-two-linked-lists) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/linkedlist/Compare2LinkedList.java) | 61 | | [Merge two sorted Linked Lists](https://www.hackerrank.com/challenges/merge-two-sorted-linked-lists) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](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 | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](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 | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/linkedlist/DeleteDuplicateValueNodesFromSortedLinkedList.java) | 64 | | [Cycle Detection](https://www.hackerrank.com/challenges/detect-whether-a-linked-list-contains-a-cycle) | Medium | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](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 | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](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 | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/linkedlist/InsertANodeInSortedDoublyLinkedList.java) | 67 | | [Reverse a Doubly Linked List](https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/linkedlist/ReverseDoublyLinkedList.java) | 68 | 69 | ### Trees ![problems-solved](https://img.shields.io/badge/Solved-14/17-1abc9c.svg) 70 | 71 | | Problem | Difficulty Level | Solution Link | 72 | |---------|------------------|:-------------:| 73 | | [Tree: Preorder Traversal](https://www.hackerrank.com/challenges/tree-preorder-traversal) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/trees/PreorderTraversal.java) | 74 | | [Tree: Postorder Traversal](https://www.hackerrank.com/challenges/tree-postorder-traversal) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/trees/PostOrderTraversal.java) | 75 | | [Tree: Inorder Traversal](https://www.hackerrank.com/challenges/tree-inorder-traversal) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/trees/InorderTraversal.java) | 76 | | [Tree: Height of Binary Tree](https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/trees/HeightOfBinaryTree.java) | 77 | | [Tree: Level Order Traversal](https://www.hackerrank.com/challenges/tree-level-order-traversal) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/trees/LevelOrderTraversal.java) | 78 | | [Binary Search Tree: Insertion](https://www.hackerrank.com/challenges/binary-search-tree-insertion) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/trees/BST_Insertion.java) | 79 | | [Tree: Huffman Decoding](https://www.hackerrank.com/challenges/tree-huffman-decoding) | Medium | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/trees/TreeHuffmanDecoding.java) | 80 | | [Binary Search Tree: Lowest Common Ancestor](https://www.hackerrank.com/challenges/binary-search-tree-lowest-common-ancestor) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/trees/LowestCommonAncestor.java) | 81 | | [Swap Nodes [Algo]](https://www.hackerrank.com/challenges/swap-nodes-algo) | Medium | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/trees/SwapNodes_Algo.java) | 82 | | [Is There a Binary Search Tree](https://www.hackerrank.com/challenges/is-binary-search-tree) | Medium | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/trees/IsThisBinarySearchTree.java) | 83 | | [Tree: Top View](https://www.hackerrank.com/challenges/tree-top-view) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/trees/TreesTopView.java) | 84 | | [Kitty's Calculations on a Tree](https://www.hackerrank.com/challenges/kittys-calculations-on-a-tree) | Advanced | [![C++](https://img.icons8.com/color/35/000000/c-plus-plus-logo.png)](src/trees/KitysCalculationOnATree.cpp) | 85 | | [Square Ten Tree](https://www.hackerrank.com/challenges/square-ten-tree) | Hard |[![C++](https://img.icons8.com/color/35/000000/c-plus-plus-logo.png)](src/trees/SquareTenTree.cpp) | 86 | | [Balanced Forest](https://www.hackerrank.com/challenges/balanced-forest) | Hard | [![Python](https://img.icons8.com/color/35/000000/python.png)](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 ![problems-solved](https://img.shields.io/badge/Solved-0/3-1abc9c.svg) 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 ![problems-solved](https://img.shields.io/badge/Solved-8/9-1abc9c.svg) 102 | 103 | | Problem | Difficulty Level | Solution Link | 104 | |---------|------------------|:-------------:| 105 | | [Maximum Element](https://www.hackerrank.com/challenges/maximum-element) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/stacks/MaximumElement.java) | 106 | | [Balanced Brackets](https://www.hackerrank.com/challenges/balanced-brackets) | Medium | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/stacks/BalancedBrackets.java) | 107 | | [Equal Stacks](https://www.hackerrank.com/challenges/equal-stacks) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/stacks/EqualStacks.java) | 108 | | [Game of Two Stacks](https://www.hackerrank.com/challenges/game-of-two-stacks) | Medium | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/stacks/GameOfTwoStacks.java) | 109 | | [Simple Text Editor](https://www.hackerrank.com/challenges/simple-text-editor) | Medium | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/stacks/SimpleTextEditor.java) | 110 | | [Waiter](https://www.hackerrank.com/challenges/waiter) | Medium | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/stacks/Waiter.java) | 111 | | [Largest Rectangle](https://www.hackerrank.com/challenges/largest-rectangle) | Medium | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/stacks/LargestRectangle.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/stacks/largest-rectangle.py) | 112 | | [Poisonous Plants](https://www.hackerrank.com/challenges/poisonous-plants) | Hard | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/stacks/PoisonousPlants.java) | 113 | | [AND xor OR](https://www.hackerrank.com/challenges/and-xor-or) | Hard | | 114 | 115 | 116 | ### Queues ![problems-solved](https://img.shields.io/badge/Solved-5/5-1abc9c.svg) 117 | | Problem | Difficulty Level | Solution Link | 118 | |---------|------------------|---------------| 119 | | [Queue Using Two Stacks](https://www.hackerrank.com/challenges/queue-using-two-stacks) | Medium | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/queues/QueueUsingTwoStacks.java) | 120 | | [Castle on The Grid](https://www.hackerrank.com/challenges/castle-on-the-grid) | Medium | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/queues/CastleOnTheGrid.java) | 121 | | [Down to Zero II](https://www.hackerrank.com/challenges/down-to-zero-ii) | Medium | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/queues/DownToZeroII.java) | 122 | | [Truck Tour](https://www.hackerrank.com/challenges/truck-tour) | Hard | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/queues/TruckTourProblem.java) | 123 | | [Queries with Fixed Length](https://www.hackerrank.com/challenges/queries-with-fixed-length) | Hard | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/queues/QueriesWithFixedLength.java) | 124 | 125 | 126 | ### Heap ![problems-solved](https://img.shields.io/badge/Solved-4/4-1abc9c.svg) 127 | 128 | | Problem | Difficulty Level | Solution Link | 129 | |---------|------------------|---------------| 130 | | [QHEAP1](https://www.hackerrank.com/challenges/qheap1) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/heap/QHEAP1.java) | 131 | | [Jessie and Cookies](https://www.hackerrank.com/challenges/jesse-and-cookies) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/heap/JesseAndCookies.java) | 132 | | [Find the Running Median](https://www.hackerrank.com/challenges/find-the-running-median) | Hard | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/heap/FindTheRunningMedian.java) | 133 | | [Minimum Average Wait Time](https://www.hackerrank.com/challenges/minimum-average-waiting-time) | Hard | [![Python](https://img.icons8.com/color/35/000000/python.png)](python/heap/minimum-average-waiting-time.py) | 134 | 135 | 136 | ### Disjoint Set ![problems-solved](https://img.shields.io/badge/Solved-1/4-1abc9c.svg) 137 | 138 | | Problem | Difficulty Level | Solution Link | 139 | |---------|------------------|---------------| 140 | | [Components In A Graph](https://www.hackerrank.com/challenges/components-in-graph) | Medium | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](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 ![problems-solved](https://img.shields.io/badge/Solved-3/3-1abc9c.svg) 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 | [![Markdown](https://img.icons8.com/office/35/000000/markdown.png)](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 | [![Markdown](https://img.icons8.com/office/35/000000/markdown.png)](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 | [![Markdown](https://img.icons8.com/office/35/000000/markdown.png)](src/mcq/Data%20Structure%20MCQ%203.md) | 153 | 154 | 155 | ### Trie ![problems-solved](https://img.shields.io/badge/Solved-1/2-1abc9c.svg) 156 | 157 | | Problem | Difficulty Level | Solution Link | 158 | |---------|------------------|:-------------:| 159 | | [Contacts]() | Medium | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/trie/Contacts.java) | 160 | | [No Prefix Set](https://www.hackerrank.com/challenges/no-prefix-set) | Hard | | 161 | 162 | 163 | ### Advanced ![problems-solved](https://img.shields.io/badge/Solved-0/53-1abc9c.svg) 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 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | int max_depth = 0; 20 | 21 | struct node 22 | { 23 | int value; 24 | int depth; 25 | node* parent; 26 | 27 | node(int v, int d, node* p) 28 | { 29 | value = v; 30 | depth = d; 31 | parent = p; 32 | } 33 | 34 | node() 35 | { 36 | value = -1; 37 | depth = -1; 38 | } 39 | }; 40 | 41 | struct subtree 42 | { 43 | int root_node; 44 | int depth; 45 | int next_calc_depth = -1; 46 | unsigned long long next_calc = 0; 47 | unsigned long long next_sum = 0; 48 | 49 | subtree() 50 | {} 51 | 52 | subtree(int d) 53 | { 54 | depth = d; 55 | } 56 | 57 | subtree(int cn, int d) 58 | { 59 | root_node = cn; 60 | depth = d; 61 | next_calc_depth = d; 62 | } 63 | }; 64 | 65 | std::unordered_map nodes; 66 | 67 | int main() 68 | { 69 | int num_nodes, num_sets; 70 | std::cin >> num_nodes >> num_sets; 71 | int child_node, parent_node; 72 | 73 | std::vector> node_list; 74 | for (int i = 1; i < num_nodes; i++) 75 | { 76 | std::cin >> child_node >> parent_node; 77 | if (parent_node > child_node) 78 | node_list.push_back(std::pair(child_node, parent_node)); 79 | else 80 | node_list.push_back(std::pair(parent_node, child_node)); 81 | } 82 | 83 | std::pair first_node_pair = *(node_list.begin()); 84 | parent_node = first_node_pair.first; 85 | child_node = first_node_pair.second; 86 | nodes[parent_node] = node(parent_node, 0, nullptr); 87 | nodes[child_node] = node(child_node, 1, &nodes[parent_node]); 88 | 89 | for (auto it = std::next(node_list.begin()); it != node_list.end(); ++it) 90 | { 91 | parent_node = it->first; 92 | child_node = it->second; 93 | node* parent = &nodes[parent_node]; 94 | int parent_depth = parent->depth; 95 | int current_depth = parent_depth + 1; 96 | 97 | if (current_depth > max_depth) 98 | max_depth = current_depth; 99 | 100 | nodes[child_node] = node(child_node, current_depth, parent); 101 | } 102 | 103 | for (int i = 0; i < num_sets; i++) 104 | { 105 | int n; 106 | std::cin >> n; 107 | 108 | if (n > 1) 109 | { 110 | int loadTime = 0; 111 | 112 | std::map subtrees; 113 | std::map> nodes_by_depth; 114 | 115 | unsigned long long int new_kitty_sum = 0; 116 | int subtree_max_depth = 0; 117 | 118 | //Load nodes from the current set and store them by their depth 119 | for (int j = 0; j < n; j++) 120 | { 121 | int current_node_key; 122 | std::cin >> current_node_key; 123 | node current_node = nodes[current_node_key]; 124 | 125 | int current_depth = current_node.depth; 126 | if (current_depth > subtree_max_depth) 127 | subtree_max_depth = current_depth; 128 | 129 | nodes_by_depth[current_depth][current_node.value] = current_node; 130 | } 131 | 132 | //Start at the bottom of the tree and work upward, combining nodes as they hit their common ancestor 133 | for (int j = subtree_max_depth; j > 0; j--) 134 | { 135 | auto process_roots = nodes_by_depth.find(j); 136 | 137 | //We can easily shift a node up as long as it is the only node at its current level and there are no nodes directly above it 138 | //This alleviates quite a bit of processing on very deep trees 139 | if (process_roots->second.size() == 1) 140 | { 141 | auto next_roots_iter = nodes_by_depth.find(j - 1); 142 | if (next_roots_iter == nodes_by_depth.end()) 143 | { 144 | int shifted = 0; 145 | node current_node = process_roots->second.begin()->second; 146 | int previous_node_value = current_node.value; 147 | while (next_roots_iter == nodes_by_depth.end() && (j - shifted) > 0) 148 | { 149 | shifted++; 150 | next_roots_iter = nodes_by_depth.find(j - shifted); 151 | if (next_roots_iter == nodes_by_depth.end()) 152 | { 153 | previous_node_value = current_node.parent->value; 154 | current_node.parent = current_node.parent->parent; 155 | } 156 | } 157 | nodes_by_depth[j - (shifted - 1)].insert(std::pair(previous_node_value, current_node)); 158 | process_roots = nodes_by_depth.find(j - (shifted - 1)); 159 | j -= (shifted - 1); 160 | } 161 | } 162 | 163 | //Check all of the roots at the current level to see if they have a common ancestor or if their parent exists at the next level 164 | //If so, they can be combined 165 | for (auto root_iter = process_roots->second.begin(); root_iter != process_roots->second.end(); ++root_iter) 166 | { 167 | node current_node = root_iter->second; 168 | if (current_node.parent == nullptr) 169 | break; 170 | node* parent_node = current_node.parent; 171 | 172 | auto parent_iter = nodes_by_depth[j - 1].find(current_node.parent->value); 173 | if (parent_iter != nodes_by_depth[j - 1].end()) 174 | { 175 | subtree* next_root_subtree; 176 | auto next_iter = subtrees.find(parent_iter->second.value); 177 | if (next_iter != subtrees.end()) 178 | next_root_subtree = &next_iter->second; 179 | else 180 | { 181 | auto nrs_iter = subtrees.insert(std::pair(parent_iter->first, subtree(parent_iter->first, j - 1))).first; 182 | next_root_subtree = &(nrs_iter->second); 183 | next_root_subtree->next_calc = (uint64_t(parent_iter->second.depth - (j - 1)) * uint64_t(parent_iter->second.value)) % 1000000007; 184 | next_root_subtree->next_sum = parent_iter->second.value; 185 | nodes_by_depth[j - 1][parent_iter->first].value = parent_iter->first; 186 | } 187 | 188 | unsigned long long next_calc = next_root_subtree->next_calc + (next_root_subtree->next_sum * (next_root_subtree->next_calc_depth - (j - 1))) % 1000000007; 189 | unsigned long long next_child_sum = next_root_subtree->next_sum; 190 | next_root_subtree->next_calc = next_calc; 191 | next_root_subtree->next_calc_depth = j - 1; 192 | 193 | auto current_iter = subtrees.find(current_node.value); 194 | if (current_iter != subtrees.end()) 195 | { 196 | subtree* current_subtree = ¤t_iter->second; 197 | int current_index = current_subtree->next_calc_depth - (j - 1); 198 | unsigned long long new_sum = next_calc * (current_subtree->next_sum); 199 | unsigned long long current_product = current_subtree->next_calc + (current_subtree->next_sum * uint64_t(current_index)) % 1000000007; 200 | unsigned long long second_sum = next_child_sum * (current_product % 1000000007); 201 | new_kitty_sum += (new_sum % 1000000007) + (second_sum % 1000000007); 202 | next_root_subtree->next_calc += (current_product % 1000000007); 203 | next_root_subtree->next_calc %= 1000000007; 204 | next_root_subtree->next_sum += current_subtree->next_sum; 205 | } 206 | else 207 | { 208 | int current_depth = current_node.depth; 209 | int current_index = current_depth - (j - 1); 210 | int current_sum = current_node.value; 211 | unsigned long long new_sum = next_calc * uint64_t(current_sum); 212 | unsigned long long current_product = uint64_t(current_sum) * uint64_t(current_index); 213 | unsigned long long second_sum = next_child_sum * (current_product % 1000000007); 214 | new_kitty_sum += (new_sum % 1000000007) + (second_sum % 1000000007); 215 | int new_index = current_depth - next_root_subtree->depth; 216 | next_root_subtree->next_calc += (current_product % 1000000007); 217 | next_root_subtree->next_calc %= 1000000007; 218 | next_root_subtree->next_sum += uint64_t(current_sum); 219 | } 220 | } 221 | else 222 | { 223 | int new_root_depth = j - 1; 224 | current_node.parent = parent_node->parent; 225 | nodes_by_depth[new_root_depth][parent_node->value] = current_node; 226 | } 227 | } 228 | } 229 | 230 | std::cout << new_kitty_sum % 1000000007 << std::endl; 231 | } 232 | else 233 | { 234 | std::cin >> n; 235 | std::cout << 0 << std::endl; 236 | } 237 | } 238 | 239 | return 0; 240 | } -------------------------------------------------------------------------------- /src/trees/LevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | 6 | public class LevelOrderTraversal { 7 | 8 | public static void main(String[] args) { 9 | Tree root = new Tree(); 10 | root.input(); 11 | root.print(); 12 | 13 | ArrayList list = levelOrder(root); 14 | for(int i=0 ; i levelOrder(Tree root){ 20 | LinkedList list = new LinkedList<>(); 21 | ArrayList ans = new ArrayList<>(); 22 | 23 | list.add(root); 24 | 25 | while (!list.isEmpty()){ 26 | Tree node = list.pop(); 27 | ans.add(node); 28 | 29 | if(node.left != null) 30 | list.add(node.left); 31 | if(node.right != null) 32 | list.add(node.right); 33 | } 34 | 35 | return ans; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/trees/LowestCommonAncestor.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Scanner; 5 | 6 | public class LowestCommonAncestor { 7 | 8 | public static boolean flag = false; 9 | 10 | public static void main(String[] args) { 11 | CustomTree root = new CustomTree<>(); 12 | root.input(); 13 | root.print(); 14 | 15 | Scanner s = new Scanner(System.in); 16 | int data1 = s.nextInt(); 17 | int data2 = s.nextInt(); 18 | 19 | CustomTree node = lowestCommonAncestor(root, data1, data2); 20 | System.out.println("\n" + node.data); 21 | } 22 | 23 | private static CustomTree lowestCommonAncestor(CustomTree root, int data1, int data2){ 24 | ArrayList> list1 = ancestorOf(root, data1); flag = false; 25 | ArrayList> list2 = ancestorOf(root, data2); flag = false; 26 | 27 | print(list1); 28 | print(list2); 29 | 30 | int i; 31 | for(i=0 ; i> ancestorOf(CustomTree root, int data){ 41 | if(root == null){ 42 | return new ArrayList>(); 43 | } 44 | 45 | if((int)root.data == data){ 46 | ArrayList> smallList = new ArrayList<>(); 47 | smallList.add(root); 48 | flag = true; 49 | return smallList; 50 | } 51 | 52 | if(!flag) { 53 | ArrayList> smallList1 = ancestorOf(root.left, data); 54 | if (flag) { 55 | smallList1.add(root); 56 | return smallList1; 57 | } else { 58 | ArrayList> smallList2 = ancestorOf(root.right, data); 59 | if(flag){ 60 | smallList2.add(root); 61 | return smallList2; 62 | } 63 | } 64 | } 65 | 66 | return new ArrayList<>(); 67 | } 68 | 69 | private static void print(ArrayList> list){ 70 | System.out.println(""); 71 | for(int i=0 ; i 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | string sub_1(string s) { 9 | const auto n = s.size(); 10 | assert(n > 1 || n == 1 && s[0] > '0'); 11 | for (auto i = 0; i < n; ++i) { 12 | auto j = n-i-1; 13 | if (s[j] == '0') 14 | s[j] = '9'; 15 | else { 16 | --s[j]; 17 | break; 18 | } 19 | } 20 | auto i = 0; 21 | for (; s[i] == '0'; ++i); 22 | i = min(i, int(n - 1)); 23 | return s.substr(i); 24 | } 25 | 26 | string add_1(string s) { 27 | const auto n = s.size(); 28 | for (auto i = 0; i < n; ++i) { 29 | auto j = n - i - 1; 30 | if (s[j] != '9') { 31 | ++s[j]; 32 | return s; 33 | } 34 | s[j] = '0'; 35 | } 36 | return "1" + s; 37 | } 38 | 39 | string sub(string f, string s) { 40 | const auto n1 = f.size(); 41 | const auto n2 = s.size(); 42 | assert(n1 >= n2); 43 | char d = 0; 44 | int i = 0; 45 | for (; i < n2; ++i) { 46 | auto j1 = n1 - i - 1; 47 | auto j2 = n2 - i - 1; 48 | auto v1 = f[j1] - '0'; 49 | auto v2 = s[j2] - '0'; 50 | f[j1] = (10 + v1 - v2 - d) % 10 + '0'; 51 | d = v2 + d > v1? 1: 0; 52 | } 53 | for (; d != 0 && i < n1; ++i) { 54 | auto j = n1 - i - 1; 55 | if (f[j] != '0') { 56 | d = 0; 57 | --f[j]; 58 | } else 59 | f[j] = '9'; 60 | } 61 | i = 0; 62 | for (; i < n1 && f[i] == '0'; ++i); 63 | i = min(i, int(n1 - 1)); 64 | return f.substr(i); 65 | } 66 | 67 | int cmp(const string &f, const string &s) { 68 | const auto n1 = f.size(); 69 | const auto n2 = s.size(); 70 | if (n1 > n2) 71 | return 1; 72 | if (n1 < n2) 73 | return -1; 74 | for (auto i = 0; i < n1; ++i) { 75 | if (f[i] > s[i]) 76 | return 1; 77 | if (f[i] < s[i]) 78 | return -1; 79 | } 80 | return 0; 81 | } 82 | 83 | vector test_border(const string &s, const vector &num_zeros, char c) { 84 | const auto k = s.size(); 85 | const auto n = num_zeros.size(); 86 | vector res(n, false); 87 | auto i = 1; 88 | auto flag = false; 89 | for (; i < n; ++i) { 90 | if (c != '0' && num_zeros[i] > k) { 91 | flag = true; 92 | break; 93 | } 94 | for (auto j = num_zeros[i-1]; j < num_zeros[i] && j < k; ++j) 95 | if (s[k-j-1] != c) { 96 | flag = true; 97 | break; 98 | } 99 | if (flag) 100 | break; 101 | } 102 | for (; i < n; ++i) 103 | res[i] = true; 104 | return res; 105 | } 106 | 107 | vector> solve( 108 | const string &l, 109 | const string &r, 110 | int k, bool has_left, bool has_right, 111 | const vector &num_zeros, 112 | const vector &has_left_array, 113 | const vector &has_right_array) { 114 | 115 | 116 | if (k == 0) 117 | return vector>(1, 118 | make_pair(0, string(1, r.back() - l.back() + 1 + '0'))); 119 | string k_left, k_right; 120 | const size_t l_size = l.size(); 121 | const size_t r_size = r.size(); 122 | size_t start = num_zeros[k]; 123 | size_t stop = num_zeros[k+1]; 124 | if (start >= l_size) 125 | k_left = "0"; 126 | else { 127 | auto j1 = l_size - start; 128 | auto j2 = l_size - min(stop, l_size); 129 | k_left = l.substr(j2, j1 - j2); 130 | } 131 | if (start >= r_size) 132 | k_right = "0"; 133 | else { 134 | auto j1 = r_size - start; 135 | auto j2 = r_size - min(stop, r_size); 136 | k_right = r.substr(j2, j1 - j2); 137 | } 138 | auto cmp_res = cmp(k_left, k_right); 139 | 140 | if (cmp_res == 0 && (has_left || has_right)) { 141 | // the left and the right border are the same 142 | // so nothing to do on this level 143 | return solve(l, r, k - 1, 144 | has_left && has_left_array[k-1], 145 | has_right && has_right_array[k-1], 146 | num_zeros, has_left_array, has_right_array); 147 | } 148 | 149 | vector> res; 150 | if (has_left) { 151 | // create right border 152 | auto right = k_left + string(start, '9'); 153 | auto left_res = solve(l, right, k-1, 154 | has_left && has_left_array[k-1], false, 155 | num_zeros, has_left_array, has_right_array); 156 | res.insert(res.end(), left_res.begin(), left_res.end()); 157 | } 158 | if (cmp_res < 1) { 159 | auto dif = sub(k_right, k_left); 160 | if (!has_left) 161 | dif = add_1(dif); 162 | if (has_right) 163 | dif = sub_1(dif); 164 | res.emplace_back(k, dif); 165 | } 166 | if (has_right) { 167 | auto left = k_right + string(start, '0'); 168 | auto right_res = solve(left, r, k-1, 169 | false, has_right && has_right_array[k-1], 170 | num_zeros, has_left_array, has_right_array); 171 | res.insert(res.end(), right_res.begin(), right_res.end()); 172 | } 173 | return res; 174 | } 175 | 176 | int main(int argc, char *argv[]) { 177 | string l, r; 178 | cin >> l >> r; 179 | l = sub_1(l); 180 | r = sub_1(r); 181 | const auto n = r.size(); 182 | // number of zeros in the step size 183 | vector num_zeros(1, 0); 184 | num_zeros.push_back(1); 185 | while (num_zeros.back() <= 1000000) 186 | num_zeros.push_back(num_zeros.back() * 2); 187 | auto has_left = test_border(l, num_zeros, '0'); 188 | auto has_right = test_border(r, num_zeros, '9'); 189 | auto k = num_zeros.size() - 2; 190 | auto res = solve(l, r, k, has_left[k], has_right[k], num_zeros, has_left, has_right); 191 | cout << res.size() << endl; 192 | for (auto &el: res) 193 | cout << el.first << ' ' << el.second << endl; 194 | return 0; 195 | } -------------------------------------------------------------------------------- /src/trees/SwapNodes_Algo.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Scanner; 5 | 6 | public class SwapNodes_Algo { 7 | 8 | private static Scanner s = new Scanner(System.in); 9 | 10 | public static void main(String[] args) { 11 | int n = s.nextInt(); 12 | CustomTree root = prepareTree(); 13 | root.print(); 14 | 15 | int testCases = s.nextInt(); 16 | swapNodes(root, testCases); 17 | } 18 | 19 | private static void swapNodes(CustomTree root, int testCases){ 20 | while (testCases-- > 0){ 21 | int k = s.nextInt(); 22 | swapNodesKTimes(root, k, 1); 23 | inOrder(root); 24 | } 25 | } 26 | 27 | private static void swapNodes(CustomTree root){ 28 | CustomTree temp = root.left; 29 | root.left = root.right; 30 | root.right = temp; 31 | } 32 | 33 | private static void swapNodesKTimes(CustomTree root, int k, int depth){ 34 | if(root == null) 35 | return; 36 | 37 | if(depth % k == 0) 38 | swapNodes(root); 39 | 40 | swapNodesKTimes(root.left, k, depth+1); 41 | swapNodesKTimes(root.right, k, depth+1); 42 | } 43 | 44 | private static void inOrder(CustomTree root){ 45 | if(root == null){ 46 | return; 47 | } 48 | 49 | inOrder(root.left); 50 | System.out.print(root.data + " "); 51 | inOrder(root.right); 52 | System.out.println(""); 53 | } 54 | 55 | private static CustomTree prepareTree(){ 56 | CustomTree root = new CustomTree<>(1); 57 | LinkedList> linkedList = new LinkedList<>(); 58 | linkedList.add(root); 59 | 60 | while (!linkedList.isEmpty()){ 61 | CustomTree node = linkedList.pop(); 62 | int left = s.nextInt(); 63 | int right = s.nextInt(); 64 | 65 | if(left != -1){ 66 | node.left = new CustomTree<>(left); 67 | linkedList.add(node.left); 68 | } 69 | if(right != -1){ 70 | node.right = new CustomTree<>(right); 71 | linkedList.add(node.right); 72 | } 73 | } 74 | 75 | return root; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/trees/Tree.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | import java.util.Scanner; 4 | 5 | class Tree { 6 | private Scanner s = new Scanner(System.in); 7 | 8 | T data; 9 | Tree left; 10 | Tree right; 11 | 12 | Tree(){} 13 | Tree(T data){ 14 | this.data = data; 15 | } 16 | 17 | public void input(){ 18 | input(this); 19 | } 20 | 21 | private Tree input(Tree root){ 22 | System.out.print("Enter Data : "); 23 | int data = s.nextInt(); 24 | 25 | if(data != -1) 26 | root.data = data; 27 | else return null; 28 | 29 | root.left = input(new Tree()); 30 | root.right = input(new Tree()); 31 | 32 | return root; 33 | } 34 | 35 | public void print(){ 36 | print(this); 37 | } 38 | 39 | private void print(Tree root){ 40 | if(root == null) 41 | return; 42 | 43 | System.out.println(root.data + " : " + 44 | (root.left == null ? "NULL " : root.left.data) + " " + (root.right == null ? "NULL " : root.right.data) ); 45 | 46 | print(root.left); 47 | print(root.right); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/trees/TreeHuffmanDecoding.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | import java.util.Scanner; 4 | 5 | public class TreeHuffmanDecoding { 6 | public static void main(String[] args) { 7 | Tree root = new Tree<>(); 8 | root.input(); 9 | root.print(); 10 | 11 | Scanner s = new Scanner(System.in); 12 | String binaryString = s.next(); 13 | 14 | String huffmanStr = huffmanString(root, binaryString); 15 | System.out.println(huffmanStr); 16 | } 17 | 18 | private static String huffmanString(Tree root, String binaryStr){ 19 | return ""; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/trees/TreesTopView.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | import java.util.HashMap; 4 | import java.util.LinkedList; 5 | import java.util.Map; 6 | import java.util.Queue; 7 | import java.util.Scanner; 8 | 9 | public class TreesTopView { 10 | public static Node insert(Node root, int data) { 11 | if(root == null) { 12 | return new Node(data); 13 | } else { 14 | Node cur; 15 | if(data <= root.data) { 16 | cur = insert(root.left, data); 17 | root.left = cur; 18 | } else { 19 | cur = insert(root.right, data); 20 | root.right = cur; 21 | } 22 | return root; 23 | } 24 | } 25 | 26 | public static void main(String[] args) { 27 | Scanner scan = new Scanner(System.in); 28 | int t = scan.nextInt(); 29 | Node root = null; 30 | while(t-- > 0) { 31 | int data = scan.nextInt(); 32 | root = insert(root, data); 33 | } 34 | scan.close(); 35 | topView(root); 36 | } 37 | 38 | public static void topView(Node root) { 39 | Map view = new HashMap<>(); 40 | generateView(view, root); 41 | printView(view); 42 | System.out.println(); 43 | } 44 | 45 | private static void generateView(Map view, Node root) { 46 | Queue queue = new LinkedList<>(); 47 | queue.add(new Info(root, 0)); 48 | 49 | while (!queue.isEmpty()) { 50 | Info element = queue.poll(); 51 | if (element.node != null) { 52 | queue.add(new Info(element.node.left, element.level - 1)); 53 | queue.add(new Info(element.node.right, element.level + 1)); 54 | if (!view.containsKey(element.level)) { 55 | view.put(element.level, element.node.data); 56 | } 57 | } 58 | } 59 | } 60 | 61 | private static void printView(Map view) { 62 | for (int index = -500 ; index <= 500 ; index++) { 63 | if (view.containsKey(index)) { 64 | System.out.print(view.get(index) + " "); 65 | } 66 | } 67 | } 68 | 69 | private static class Info { 70 | Node node; 71 | int level; 72 | 73 | Info(Node node, int level) { 74 | this.node = node; 75 | this.level = level; 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/trie/Contacts.java: -------------------------------------------------------------------------------- 1 | package trie; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.Scanner; 6 | 7 | class Letter { 8 | private HashMap map; 9 | private boolean isWord; 10 | private char letter; 11 | private int words = 0; 12 | 13 | Letter(char letter){ 14 | map = new HashMap<>(); 15 | isWord = false; 16 | this.letter = letter; 17 | } 18 | Letter(boolean isWord, char letter){ 19 | this.isWord = isWord; 20 | map = new HashMap<>(); 21 | this.letter = letter; 22 | } 23 | 24 | public boolean isWord(){ 25 | return isWord; 26 | } 27 | public char value(){ 28 | return letter; 29 | } 30 | public int getWords(){ 31 | return words; 32 | } 33 | 34 | public void addWord(String word){ 35 | words++; 36 | 37 | if(word.length() == 0){ 38 | this.isWord = true; 39 | return; 40 | } 41 | 42 | if(map.containsKey(word.charAt(0))) 43 | map.get(word.charAt(0)).addWord(word.substring(1)); 44 | else { 45 | map.put(word.charAt(0), new Letter(word.charAt(0))); 46 | map.get(word.charAt(0)).addWord(word.substring(1)); 47 | } 48 | } 49 | public void print(String name){ 50 | name = name + letter; 51 | if(isWord) 52 | System.out.println(name); 53 | 54 | for(Map.Entry letterEntry : map.entrySet()){ 55 | letterEntry.getValue().print(name); 56 | } 57 | } 58 | public int numberOfClosestEntries(String word){ 59 | if(word.length() == 0) 60 | return words; 61 | 62 | if(map.containsKey(word.charAt(0))) 63 | return map.get(word.charAt(0)).numberOfClosestEntries(word.substring(1)); 64 | 65 | return 0; 66 | } 67 | public boolean containsPrefix(String word){ 68 | if(word.length() == 0 || words <= 1) 69 | return false; 70 | 71 | if(isWord) 72 | return true; 73 | 74 | if(map.containsKey(word.charAt(0))) 75 | return map.get(word.charAt(0)).containsPrefix(word.substring(1)); 76 | 77 | return false; 78 | } 79 | } 80 | 81 | 82 | class Node{ 83 | private HashMap map; 84 | 85 | Node(){ 86 | map = new HashMap<>(); 87 | } 88 | 89 | public boolean containsLetter(char letter){ 90 | return map.containsKey(letter); 91 | } 92 | public void add(char letter){ 93 | map.put(letter, new Letter(letter)); 94 | } 95 | public void addWord(String word){ 96 | map.get(word.charAt(0)).addWord(word.substring(1)); 97 | } 98 | public void print(){ 99 | for(Map.Entry letterEntry : map.entrySet()){ 100 | letterEntry.getValue().print(""); 101 | } 102 | } 103 | public int numberOfClosestEntries(String word){ 104 | if(word.length() == 0) 105 | return map.size(); 106 | 107 | if(map.containsKey(word.charAt(0))) 108 | return map.get(word.charAt(0)).numberOfClosestEntries(word.substring(1)); 109 | 110 | return 0; 111 | } 112 | public boolean containsPrefix(String word){ 113 | if(word.length() == 0) 114 | return false; 115 | 116 | if(map.containsKey(word.charAt(0))){ 117 | Letter firstLetter = map.get(word.charAt(0)); 118 | if(firstLetter.getWords() > 1) 119 | return firstLetter.isWord() || firstLetter.containsPrefix(word.substring(1)); 120 | return false; 121 | } 122 | 123 | return false; 124 | } 125 | } 126 | 127 | 128 | class Trie { 129 | private Node start; 130 | 131 | Trie(){ 132 | start = new Node(); 133 | } 134 | 135 | public void addWord(String string){ 136 | if(string.length() == 0) 137 | return; 138 | 139 | if(start.containsLetter(string.charAt(0))){ 140 | start.addWord(string); 141 | } else { 142 | start.add(string.charAt(0)); 143 | start.addWord(string); 144 | } 145 | } 146 | public void print(){ 147 | start.print(); 148 | } 149 | public int numberOfClosestEntries(String word){ 150 | return start.numberOfClosestEntries(word); 151 | } 152 | public boolean containsPrefix(String word){ 153 | return start.containsPrefix(word); 154 | } 155 | } 156 | 157 | public class Contacts { 158 | private static Scanner in = new Scanner(System.in); 159 | 160 | public static void main(String[] args) { 161 | int queries = in.nextInt(); 162 | performQueries(queries); 163 | } 164 | 165 | private static void performQueries(int queries){ 166 | Trie contacts = new Trie(); 167 | 168 | while (queries-- > 0){ 169 | String operation = in.next(); 170 | String name = in.next(); 171 | 172 | if(operation.charAt(0) == 'a'){ 173 | contacts.addWord(name); 174 | } else { 175 | System.out.println(contacts.numberOfClosestEntries(name)); 176 | } 177 | } 178 | 179 | contacts.print(); 180 | } 181 | } 182 | --------------------------------------------------------------------------------