[
  {
    "path": ".github/workflows/push-ci.yml",
    "content": "name: Push CI\n\non: [push]\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      - name: Read .nvmrc\n        run: echo \"##[set-output name=NVMRC;]$(cat .nvmrc)\"\n        id: nvm\n\n      - name: Use Node.js (.nvmrc)\n        uses: actions/setup-node@v2\n        with:\n          node-version: '${{ steps.nvm.outputs.NVMRC }}'\n\n      - name: Install dependencies\n        run: yarn\n\n      - name: Test\n        run: yarn test\n"
  },
  {
    "path": ".gitignore",
    "content": "*.pyc\n__pycache__\n.pytest_cache\n\n# dependencies\n/node_modules\n/.pnp\n.pnp.js\n\n# testing\n/coverage\n\n# production\n/build\n\n# misc\n.DS_Store\n*.pem\n\n# debug\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n\n# typescript\n*.tsbuildinfo\n\n.eslintcache\n/local"
  },
  {
    "path": ".nvmrc",
    "content": "v20.4.0\n"
  },
  {
    "path": ".prettierrc",
    "content": "{\n  \"trailingComma\": \"es5\",\n  \"tabWidth\": 2,\n  \"singleQuote\": true\n}\n"
  },
  {
    "path": ".vscode/settings.json",
    "content": "{\n  \"[javascript]\": {\n    \"editor.defaultFormatter\": \"esbenp.prettier-vscode\"\n  }\n}\n"
  },
  {
    "path": "FUNDING.yml",
    "content": "github: [imteekay]\ncustom: [https://teekay.substack.com]\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) TK\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "<samp>\n\n# Algorithms & Data Structures\n\n## Introduction\n\n- [🎥 Algorithms and Data Structures Tutorial](https://www.youtube.com/watch?v=8hly31xKli0&ab_channel=freeCodeCamp.org)\n- [🎥 Data Structures and Algorithms in JavaScript](https://www.youtube.com/playlist?list=PLWKjhJtqVAbkso-IbgiiP48n-O-JQA9PJ)\n- [🎥 Introduction to Algorithms](https://www.youtube.com/playlist?list=PLUl4u3cNGP63EdVPNLG3ToM6LaEUuStEY)\n- [🎥 Python Algorithms for Interviews](https://www.youtube.com/watch?v=p65AHm9MX80)\n- [📝 Introduction of Data Structure and algorithm](https://www.scaler.com/topics/data-structures)\n- [📝 Top 10 algorithms in interview questions](https://www.geeksforgeeks.org/top-10-algorithms-in-interview-questions)\n- [📝 Useful links about algorithms](https://leetcode.com/discuss/general-discussion/665604/important-and-useful-links-from-all-over-the-Leetcode)\n- [Leetcode lists](https://docs.google.com/document/d/1lHB0yI7UDcllyCQYqxCHLmFM1F4THDCfrj7_3zC6sDE/edit?tab=t.0)\n\n## Big-O notation and design\n\n- [🎥 Big O Notation w/ Gayle](https://www.youtube.com/watch?v=v4cd1O4zkGw&ab_channel=HackerRank)\n- [🎥 Design and Analysis of Algorithms — MIT](https://www.youtube.com/playlist?list=PLUl4u3cNGP6317WaSNfmCvGym2ucw3oGp)\n- [💻 Big O](computer_science/big_o)\n- [📝 Know your complexities: Big-O cheat sheet](https://www.bigocheatsheet.com)\n- [📝 Big O in DS](./big-o.md)\n- [📝 Computational complexity part one](https://www.topcoder.com/thrive/articles/Computational%20Complexity%20part%20one)\n- [📝 Computational complexity part two](https://www.topcoder.com/thrive/articles/Computational%20Complexity%20part%20two)\n\n## Data Structures\n\n- [🎥 Data Structures Easy to Advanced Course - Full Tutorial from a Google Engineer](https://www.youtube.com/watch?v=RBSGKlAvoiM)\n- [💻 Data Structures and Algorithms cheat sheet](https://github.com/TSiege/Tech-Interview-Cheat-Sheet)\n- [📝 What is Data Structure?](https://www.scaler.com/topics/data-structures/what-is-data-structure)\n\n### Stack\n\n- [📝 Stack Data Structure in JavaScript](https://www.iamtk.co/series/data-structures-in-javascript/stack-data-structure)\n- [📝 Stack Data Structure Practice Problems](https://medium.com/techie-delight/stack-data-structure-practice-problems-and-interview-questions-9f08a35a7f19)\n- [📝 Stack Data Structure](https://www.iamtk.co/series/data-structures/stack-data-structure)\n\n### Queues\n\n- [📝 Queue Data Structure in JavaScript](https://www.iamtk.co/series/data-structures-in-javascript/queue-data-structure)\n- [📝 Queue Data Structure](https://www.iamtk.co/series/data-structures/queue-data-structure)\n- [📝 Queue Data Structure](https://www.scaler.com/topics/data-structures/queue-in-data-structure)\n\n### Linked Lists\n\n- [🎥 Linked Lists for Technical Interviews](https://www.youtube.com/watch?v=Hj_rA0dhr2I&ab_channel=freeCodeCamp.org)\n- [📝 Linked Lists Data Structure in JavaScript](https://www.iamtk.co/series/data-structures-in-javascript/linked-list-data-structure)\n- [📝 Linked Lists Data Structure](https://www.iamtk.co/series/data-structures/linked-list-data-structure)\n- [📝 Linked Lists Data Structure](https://www.scaler.com/topics/linked-list)\n\n### Trees\n\n- [🎥 Binary Tree Algorithms for Technical Interviews](https://www.youtube.com/watch?v=fAAZixBzIAI&ab_channel=freeCodeCamp.org)\n- [📝 Tree Data Structure](https://www.iamtk.co/series/data-structures/tree-data-structure)\n- [📝 Tree Data Structure](https://www.scaler.com/topics/data-structures/tree-data-structure)\n\n### Graphs\n\n- [🎥 Breadth First Search & Depth First Search](https://www.youtube.com/watch?v=pcKY4hjDrxk&ab_channel=AbdulBari)\n- [🎥 Graph Algorithms for Technical Interviews](https://www.youtube.com/watch?v=tWVWeAqZ0WU&ab_channel=freeCodeCamp.org)\n- [🎥 Graph data structure — Part 1](https://www.youtube.com/watch?v=JDP1OVgoa0Q&ab_channel=JunminLee)\n- [🎥 Graph data structure — Part 2](https://www.youtube.com/watch?v=bSZ57h7GN2w&ab_channel=JunminLee)\n- [🎥 Graph Search Algorithms in 100 Seconds](https://www.youtube.com/watch?v=cWNEl4HE2OE&ab_channel=Fireship)\n- [📝 Depth First Search](https://www.hackerearth.com/practice/algorithms/graphs/depth-first-search/tutorial)\n- [📝 Graph in Data Structure](https://www.scaler.com/topics/data-structures/graph-in-data-structure)\n\n## Algorithms\n\n- [🎥 Problem Patterns](https://designgurus.org/course/grokking-the-coding-interview)\n- [🎥 Programação Dinamica](https://www.youtube.com/watch?v=qp9UOJ0XUlg&ab_channel=GubnunBR)\n- [📝 3 Tricks To Master Linked List Problems](https://medium.com/interviewnoodle/leetcode-3-tricks-to-master-linked-list-problems-8647a74a5f1c)\n- [📝 3 Tricks To Master String Problems](https://medium.com/interviewnoodle/leetcode-3-tricks-to-master-string-problems-bf10079df639)\n- [📝 5 Tricks To Solve Any Interval/Conflict Schedule Related Problems](https://medium.com/interviewnoodle/leetcode-5-tricks-to-solve-any-interval-conflict-schedule-related-problems-3f33d6e5af55)\n- [📝 Coding Patterns - Backtracking](https://iorilan.medium.com/after-solved-1000-medium-leetcode-found-thes-patterns-backtracking-b683aa8bd8ac)\n- [📝 Coding Patterns - BFS](https://iorilan.medium.com/after-finished-1000-leetcode-medium-level-i-found-some-patterns-bfs-63783cbd2c70)\n- [📝 Coding Patterns - DFS](https://iorilan.medium.com/after-finished-1000-leetcode-medium-level-i-found-some-patterns-dfs-77e584425474)\n- [📝 Coding Patterns - Dynamic Programming](https://iorilan.medium.com/after-solved-1000-leetcode-medium-level-i-found-these-patterns-dynamic-programming-205226223f4e)\n- [📝 Coding Patterns - Mono-Stack](https://iorilan.medium.com/after-solved-1000-medium-leetcode-found-thes-patterns-mono-stack-40ce6067abfe)\n- [📝 Coding Patterns - Presum, Greedy, intervals](https://iorilan.medium.com/after-solved-1000-medium-leetcode-found-these-patterns-presum-greedy-intervals-511d899bcee3)\n- [📝 Coding Patterns - Sliding Window, 2 Pointer, String](https://iorilan.medium.com/after-solved-1000-medium-leetcode-found-these-patterns-sliding-window-2-pointer-string-18332ca4861)\n- [📝 Coding Patterns - UnionFind, Devide And Conquer, Toposort](https://iorilan.medium.com/after-solved-1000-medium-leetcode-found-these-patterns-unionfind-devide-and-conquer-toposort-9210dfc90223)\n- [📝 Coding Patterns — Binary Search, Trie, Heap](https://medium.com/@iorilan/after-solved-1000-medium-leetcode-found-these-patterns-binary-search-trie-heap-8dc5c82e9e94)\n- [📝 Find Kth Largest/Smallest Element Without Sorting](https://medium.com/interviewnoodle/leetcode-find-kth-largest-smallest-element-without-sorting-77b92c75c890)\n- [📝 Grokking LeetCode: A Smarter Way to Prepare for Coding Interviews](https://interviewnoodle.com/grokking-leetcode-a-smarter-way-to-prepare-for-coding-interviews-e86d5c9fe4e1)\n- [📝 Let's implement a Bloom Filter](https://onatm.dev/2020/08/10/let-s-implement-a-bloom-filter)\n- [📝 Master 2D matrix/maze traversal](https://medium.com/interviewnoodle/leetcode-master-2d-matrix-maze-traversal-ec9f2e0bc300)\n- [📝 Recursive descent parsing](https://austinhenley.com/blog/teenytinycompiler2.html)\n\n## Coding Interviews\n\nBuild the the foundation by learning the fundamental algorithms and data structures:\n\n- Fundamental Algorithms\n  - [ ] Sorting\n    - [ ] Merge Sort\n    - [ ] Quick Sort\n    - [ ] Bucket Sort\n    - [ ] Heap Sort\n    - [ ] Counting Sort\n  - [x] Searching\n    - [x] [Binary Search](computer_science/algorithms/binary-search/binary-search.js)\n    - [x] [Tree Depth First Search](computer_science/data_structures/binary_search_tree)\n    - [x] [Tree Breadth First Search](computer_science/data_structures/binary_search_tree)\n    - [ ] Graph Depth First Search\n    - [ ] Graph Breadth First Search\n  - [ ] Dynamic Programming\n  - [x] [String / Array: reverse](computer_science/algorithms/reverse-string/reverse-string.js)\n  - [x] [Linked list: insertion, deletion](computer_science/data_structures/linked_list)\n- Fundamental Data Structures\n  - [x] [Stack](computer_science/data_structures/stack)\n  - [x] [Queue](computer_science/data_structures/queue)\n  - [x] [Linked List](computer_science/data_structures/linked_list)\n  - [x] [Hash Map](computer_science/data_structures/hash_table)\n  - [ ] Heap\n  - [ ] Priority Queue\n  - [ ] Tree\n    - [x] [Binary Search Tree](computer_science/data_structures/binary_search_tree)\n    - [ ] AVL Tree\n    - [ ] Red-Black Tree\n    - [ ] Segment Tree\n    - [ ] Fenwick Tree (Binary Indexed Tree)\n  - [x] [Graph](computer_science/data_structures/graph)\n- Time & Space Complexity\n  - [ ] Space complexity for all algorithms / data structures\n  - [ ] Runtime complexity for all algorithms / data structures\n  - [ ] Make comparisons between algorithms and data structures\n\n### Preparation\n\n- [🎥 10 Common Coding Interview Problems](https://www.youtube.com/watch?v=Peq4GCPNC5c&ab_channel=freeCodeCamp.org)\n- [🎥 8 Most Popular Microsoft Coding Interview Questions Solved Step by Step](https://www.youtube.com/watch?v=1P3xh7CGSU8&ab_channel=SCALER)\n- [🎥 Crack Your Dream Tech Interviews](https://www.youtube.com/watch?v=hm53n8tqbTo&ab_channel=Exaltitude)\n- [🎥 Data Structures and Algorithms in Java | Free course | Animations and Implementations](https://www.youtube.com/watch?v=6iCHf7OZn6c&list=PL6Zs6LgrJj3tDXv8a_elC6eT_4R5gfX4d&ab_channel=DineshVaryani)\n- [🎥 Google's Career Page - Interview Tips](https://www.youtube.com/watch?v=VXE1eBIulKg&ab_channel=JeffHSipe-PracticeInterviews)\n- [🎥 How to Crack The Coding Interview? | Important LeetCode Questions | Preparation Tips](https://www.youtube.com/watch?v=cM4o7_UY9vM&ab_channel=DineshVaryani)\n- [🎥 How To Study For Coding Interviews Efficiently](https://www.youtube.com/watch?v=2nVFdxJJdLw&ab_channel=ConnerArdman)\n- [🎥 Joining the Uber Eng Team - Coding Interview](https://www.youtube.com/watch?v=xxAnIoIxWGM)\n- [📝 3-month plan for Cracking the Coding Interview](https://medium.com/interviewnoodle/3-month-plan-for-cracking-the-coding-interview-5534f0ad7595)\n- [📝 Algorithm Problem Solving](./problem-solving.md)\n- [📝 Algorithm Template](https://docs.google.com/document/d/1TKNUaBdgzEoPaD8LNexz9JlquRKc1ZSBnNJuZmhFp4Y/edit)\n- [📝 Amazon's Interview Guide](https://www.linkedin.com/posts/arslanahmad_systemdesign-sde-datastructures-activity-7074384240607428608-D9AH)\n- [📝 Before the interview](http://blog.gainlo.co/index.php/2017/02/18/chapter-1-get-interview-google-complete-guide-google-interview-preparation)\n- [📝 Blind Curated 75](https://leetcode.com/list/x84cr1pj)\n- [📝 Brian Bi considerations](https://qr.ae/TSJE9l)\n- [📝 Build a Solid Foundation – The Complete Guide to Google Interview Preparation](http://blog.gainlo.co/index.php/2017/02/24/chapter-2-build-solid-foundation-complete-guide-google-interview-preparation)\n- [📝 Build a Solid Foundation – The Complete Guide to Google Interview Preparation](http://blog.gainlo.co/index.php/2017/02/24/chapter-2-build-solid-foundation-complete-guide-google-interview-preparation)\n- [📝 Coding Interview Prep Guide](https://formation.dev/guide)\n- [📝 Crack The Coding Interview Spreadsheet - Leetcode](https://docs.google.com/spreadsheets/d/1pnI8HmSMPcfwrCCu7wYETCXaKDig4VucZDpcjVRuYrE/edit#gid=237636947)\n- [📝 Deliberate practice coding interviews](https://www.linkedin.com/feed/update/urn:li:activity:7102397119537303554)\n- [📝 Don’t Study 500 LeetCode Problems, Do This Instead](https://medium.com/@brianjenney/dont-study-500-leetcode-problems-do-this-instead-28181ebb1eb1)\n- [📝 Facebook Interview Guide](https://www.linkedin.com/posts/arslanahmad_fb-meta-sde-activity-6980448214105669632-5-9e)\n- [📝 From Zero to Hero in Problem Solving](https://1162429.medium.com/from-zero-to-hero-in-problem-solving-c616641b5639)\n- [📝 Get an Interview with Google – The Complete Guide to Google Interview Preparation](http://blog.gainlo.co/index.php/2017/02/18/chapter-1-get-interview-google-complete-guide-google-interview-preparation)\n- [📝 Google devtip: DS & Algorithms](https://techdevguide.withgoogle.com/paths/data-structures-and-algorithms)\n- [📝 Google devtip: Interview Prep](https://techdevguide.withgoogle.com/paths/interview)\n- [📝 Google devtip: Software Engineering Principles](https://techdevguide.withgoogle.com/paths/principles)\n- [📝 Google Interview Guide](https://www.linkedin.com/posts/arslanahmad_google-datastructures-algorithms-activity-7076187648985350144-fYbP)\n- [📝 Google Interview Preparation](http://blog.gainlo.co/index.php/category/google-interview-preparation)\n- [📝 How I build a habit to leetcode](https://medium.com/@chuayewwee/how-i-build-a-habit-to-leetcode-23b1fdb5e0d9)\n- [📝 How to Land a Front-end Software Engineer job at Big Tech Companies such as Google, Facebook, and Twitter](https://javascript.plainenglish.io/how-to-land-a-software-engineer-job-in-google-facebook-and-twitter-44e49906e87)\n- [📝 How to study Data Structures and Algorithms while working a full-time job?](https://medium.com/@pepcoding/how-to-study-data-structures-and-algorithms-while-working-a-full-time-job-8ac21c93da5e)\n- [📝 knock a technical interview](https://qr.ae/TSJEkK)\n- [📝 Meta's Career Page - Interview Prep](https://www.metacareers.com/profile/trial/?redirect=job_details&chooseView=Hello%20World)\n- [📝 Microsoft's Interview Guide](https://www.linkedin.com/posts/arslanahmad_microsoft-sde-datastructures-activity-7073219389096947712-ARqi)\n- [📝 Must Do Easy Questions](https://leetcode.com/list/xip8yt56)\n- [📝 Must Do Medium Questions](https://leetcode.com/list/xineettm)\n- [📝 Prep by elliotbot](https://old.reddit.com/r/cscareerquestions/comments/6278bi/my_journey_and_tips_29_gpa_at_a_noname_liberal)\n- [📝 Programming Interview Questions](http://www.ardendertat.com/2012/01/09/programming-interview-questions)\n- [📝 Recruiter's view](https://qr.ae/TSJE3x)\n- [📝 Software Engineer interview preparation](https://www.mauriciopoppe.com/notes/misc/software-engineer-interview-preparation)\n- [📝 System Design](./system-design.md)\n- [📝 Taejun's preparation](https://qr.ae/TSJEJv)\n- [📝 The ultimate guide to preparing for the coding interview](https://medium.com/free-code-camp/the-ultimate-guide-to-preparing-for-the-coding-interview-183251ee36c9)\n\n### Interview\n\n- [🎥 Google Coding Interview](https://www.youtube.com/watch?v=rw4s4M3hFfs&ab_channel=Cl%C3%A9mentMihailescu)\n- [📝 A “strong yes” technical interview.](https://medium.com/@paulanthonysalvatore/a-strong-yes-technical-interview-195fb851d836)\n- [📝 Green flags in a interview](https://qr.ae/TSJEQA)\n\n### Platforms to learn\n\n- [Cracking the Coding Interview](coding_interviews/cracking-the-coding-interview)\n- [Binary Search](https://binarysearch.com)\n- [InterviewBit algorithms course](https://www.interviewbit.com/courses/programming)\n- [Leetcode Patterns](https://seanprashad.com/leetcode-patterns)\n- [Scaler Topics](https://www.scaler.com/topics)\n- [Structy](https://structy.net)\n- [Leetcode](coding_interviews/leetcode)\n- [algoexpert](coding_interviews/algoexpert)\n- [LabEx Interview Questions](https://labex.io/interview-questions)\n\n### Competitive Programming\n\n- [Codeforces](competitive-programming/codeforces)\n- [Hacker Rank](competitive-programming/hacker-rank)\n- [SPOJ BR](competitive-programming/spoj-br)\n- [Timus](competitive-programming/timus)\n- [UCoder](competitive-programming/ucoder)\n- [URI Online Judge](competitive-programming/uri)\n- [UVa Online Judge](competitive-programming/uva)\n\n## Computer Science\n\n### Computing\n\n- [🎥 Software as Computational Media](https://www.youtube.com/watch?v=I-aGF-47hqI&ab_channel=ACMSIGPLAN)\n- [🎥 Tools & Craft: Andy Matuschak - Software and Computing](https://www.youtube.com/watch?v=bcrcaTuvpBk&ab_channel=Notion)\n\n### Theory\n\n- [🎥 A Uniﬁed Theory of Garbage Collection](https://www.youtube.com/watch?v=XtUtfARSIv8&ab_channel=PapersWeLove)\n- [📝 Computer Organization - Performance](https://www.csie.nuk.edu.tw/~kcf/course/95_Spring/Organization/Chapter4_Performance.pdf)\n- [📝 Computer Organization | Performance of Computer](https://www.geeksforgeeks.org/computer-organization-performance-of-computer)\n\n### Courses\n\n- [🎥 Intro to Theoretical Computer Science](https://classroom.udacity.com/courses/cs313)\n- [🎥 MIT 6.042J Mathematics for Computer Science](https://www.youtube.com/playlist?list=PLUl4u3cNGP60UlabZBeeqOuoLuj_KNphQ)\n- [🎥 MIT 6.006 Introduction to Algorithms](https://www.youtube.com/playlist?list=PLUl4u3cNGP63EdVPNLG3ToM6LaEUuStEY)\n- [🎥 MIT 6.046J Design and Analysis of Algorithms](https://www.youtube.com/playlist?list=PLUl4u3cNGP6317WaSNfmCvGym2ucw3oGp)\n\n## License\n\n[MIT](/LICENSE) © [TK](https://iamtk.co)\n\n</samp>\n"
  },
  {
    "path": "big-o.md",
    "content": "# Big O\n\n| Big O Notation | Type        | Computations for 10 elements | Computations for 100 elements | Computations for 1000 elements |\n| -------------- | ----------- | ---------------------------- | ----------------------------- | ------------------------------ |\n| **O(1)**       | Constant    | 1                            | 1                             | 1                              |\n| **O(log N)**   | Logarithmic | 3                            | 6                             | 9                              |\n| **O(N)**       | Linear      | 10                           | 100                           | 1000                           |\n| **O(N log N)** | n log(N)    | 30                           | 600                           | 9000                           |\n| **O(N^2)**     | Quadratic   | 100                          | 10000                         | 1000000                        |\n| **O(2^N)**     | Exponential | 1024                         | 1.26e+29                      | 1.07e+301                      |\n| **O(N!)**      | Factorial   | 3628800                      | 9.3e+157                      | 4.02e+2567                     |\n\n### Data Structure Operations Complexity\n\n| Data Structure         | Access | Search | Insertion | Deletion |\n| ---------------------- | :----: | :----: | :-------: | :------: |\n| **Array**              |   1    |   N    |     N     |    N     |\n| **Stack**              |   N    |   N    |     1     |    1     |\n| **Queue**              |   N    |   N    |     1     |    1     |\n| **Linked List**        |   N    |   N    |     1     |    N     |\n| **Hash Table**         |   1    |   N    |     N     |    N     |\n| **Binary Search Tree** |   N    |   N    |     N     |    N     |\n"
  },
  {
    "path": "coding_interviews/README.md",
    "content": "<samp>\n\n# Interview Traning\n\n## Tech Interview Preparation\n\n### Before the interview\n\n- Referral Is The Core\n  - Talk to some friends at this Tech companies\n- Resume\n  - Concise and easy to understand\n  - Single page\n  - Balance between details and simplicity\n  - Clear to anyone without relevant background and at the same time give people some ideas about the complexity\n  - Review and feedback\n- Technical Questions\n  - Draw an example:\n    - Specific. It should use real numbers or strings (if applicable to the problem).\n    - Sufficiently large. Most examples are too small, by about 50%.\n    - Not a special case. Be careful. It's very easy to inadvertently draw a special case. If there's any way your example is a special case (even if you think it probably won't be a big deal), you should fix it.\n\n### Build a Solid Foundation\n\nSome questions to have in mind:\n\n- How to do a search in a graph? What are the pros and cons of each approach? How to decide which one to use?\n- For a list of objects, you can use linked list, array, stack, queue and other data structures. How would you decide which one to use? What is the biggest advantage/disadvantage?\n- What’s the difference between dynamic programming and recursion? How do you compare a recursive solution and its iterative version?\n- If I want to improve my solution from O(n^2) time complexity to O(nlogn), what algorithms come to your mind? How about O(n)?\n\n### Algorithm Design Canvas\n\n#### Constraints\n\n- Constraints: Strings, Arrays, Numbers\n  - range of values: min and max values for any key value\n  - How many elements can be in the array?\n  - How large can each element be? If it’s a string, how long? If it’s a number, what is the minimum and maximum value?\n  - What is in each element? If it’s a number, is it an integer or a floating point? If it’s a string, is it single-byte or multibyte (unicode)?\n  - If the problem involves finding a subsequence, does “subsequence” mean that the elements must be adjacent, or is there no such requirement?\n  - Does the array contain unique numbers or can they be repeated (this is sometimes relevant)?\n- Constraints: Grids/Mazes\n  - For problems where some actor (e.g. a robot) is moving in a grid or maze, what moves are allowed? Can the robot move diagonally (hence 8 valid moves), or only horizontally/vertically (hence only 4 valid moves)?\n  - Are all cells in the grid allowed, or can there be obstacles?\n  - If the actor is trying to get from cell A to cell B, are cells A and B guaranteed to be different from each other?\n  - If the actor is trying to get from cell A to cell B, is it guaranteed that there’s a path between the two cells?\n- Constraints: Graphs\n  - How many nodes can the graph have?\n  - How many edges can the graph have?\n  - If the edges have weights, what is the range for the weights?\n  - Can there be loops in the graph? Can there be negative-sum loops in the graph?\n  - Is the graph directed or undirected?\n  - Does the graph have multiple edges and/or self-loops?\n- Constraints: Return Values\n  - What should my method return? For example, if I’m trying to find the longest subsequence of increasing numbers in an array, should I return the length, the start index, or both?\n  - If there are multiple solutions to the problem, which one should be returned?\n  - If it should return multiple values, do you have any preference on what to return? E.g. should it return an object, a tuple, an array, or pass the output parameters as input references? (This may not be applicable in languages allowing you to return multiple values, e.g. Python)\n  - What should I do/return if the input is invalid / does not match the constraints? Options may be to do nothing (always assume the input is correct), raise an exception, or return some specific value.\n  - In problems where you’re supposed to find something (e.g. a number in an array), what should be returned if the element is not present?\n\n### Things to know when stuck\n\n- Always consider hash tables (dictionaries) with their O(1)-ness. (\"Tip: using a dictionary is the most common way to get from a brute force approach to something more clever. It should always be your first thought.\")\n- If at all array-related, try sorting first.\n- If search-related, consider binary search.\n- Start with a brute force solution, look for repeat work in that solution, and modify it to only do that work once.\n  Space-time trade-off! That is, for better time complexity, try using auxiliary data structures. E.g., do something in a single pass over an array—O(N) time—by using a hash table—O(N) space—vs. doing something in multiple passes—O(N ^ 2)—without using any extra space—O(1). What information can I store to save time? (Another example: O(1) get_max method for a Stack class stores extra information (the max at and below each element) to save time (instead of iterating through the stack O(N)).)\n- Try a greedy solution: Iterate through the problem space taking the optimal solution \"so far\" until the end. (Optimal if the problem has \"optimal substructure,\" which means stitching together optimal solutions to subproblems yields an optimal solution.)\n- Remember that I can use two pointers (e.g., to get the midpoint by having one pointer go twice as fast, or in a sum problem by having the pointers work inward from either end, or to test if a string is a palindrome).\n- If the problem involves parsing or tree/graph traversal (or reversal in some way), consider using a stack.\n- Does solving the problem for size (N – 1) make solving it for size N any easier? If so, try to solve recursively and/or with dynamic programming. (Using the max/min function can help a lot in recursive or dynamic programming problems.)\n- A lot of problems can be treated as graph problems and/or use breadth-first or depth-first traversal.\n- If you have a lot of strings, try putting them in a prefix tree / trie.\n- Any time you repeatedly have to take the min or max of a dynamic collection, think heaps. (If you don’t need to insert random elements, prefer a sorted array.)\n\n### Common problems and approaches\n\n- subsequence\n  - consecutive sequence vs non-consecutive sequence\n    - consecutive sequence: [1, 2, 3] is the consecutive sequence of [1, 2, 3, 4, 5]\n    - non-consecutive sequence: [1, 3, 5] is the non-consecutive sequence of [1, 2, 3, 4, 5]\n- binary search\n  - [problem](/coding_interviews/leetcode/easy/guess-number-higher-or-lower/guess-number-higher-or-lower.js)\n\n</samp>\n"
  },
  {
    "path": "coding_interviews/algoexpert/README.md",
    "content": "# AlgoExpert\n"
  },
  {
    "path": "coding_interviews/algoexpert/array-of-products/array-of-products-optimized.js",
    "content": "/**\n *\n * Write a function that takes in a non-empty array of integers and returns\n * an array of the same length, where each element in the output array is\n * equal to the product of every other number in the input array.\n * In other words, the value at output[i] is equal to the product of\n * every number in the input array other than input[i].\n * Note that you're expected to solve this problem without using division.\n *\n * Input: array = [5, 1, 4, 2]\n * Output: [8, 40, 10, 20]\n */\n\n// Runtime: O(N), N = length of array\n// Space: O(N)\n\nfunction initOutput(length) {\n  let output = [];\n\n  while (length--) {\n    output.push(1);\n  }\n\n  return output;\n}\n\nfunction arrayOfProducts(array) {\n  let left = 1;\n  let right = 1;\n  let length = array.length;\n  let output = initOutput(length);\n\n  for (let index = 0; index < length; index++) {\n    output[index] *= left;\n    output[length - index - 1] *= right;\n    left *= array[index];\n    right *= array[length - index - 1];\n  }\n\n  return output;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/array-of-products/array-of-products.js",
    "content": "/**\n *\n * Write a function that takes in a non-empty array of integers and returns\n * an array of the same length, where each element in the output array is\n * equal to the product of every other number in the input array.\n * In other words, the value at output[i] is equal to the product of\n * every number in the input array other than input[i].\n * Note that you're expected to solve this problem without using division.\n *\n * Input: array = [5, 1, 4, 2]\n * Output: [8, 40, 10, 20]\n */\n\n// Runtime: O(N^2), N = length of array\n// Space: O(N)\n\nfunction initOutput(length) {\n  let output = [];\n\n  while (length--) {\n    output.push(1);\n  }\n\n  return output;\n}\n\nfunction arrayOfProducts(array) {\n  let output = initOutput(array.length);\n\n  for (let index = 0; index < array.length; index++) {\n    for (let outputIndex = 0; outputIndex < output.length; outputIndex++) {\n      if (index !== outputIndex) {\n        output[outputIndex] *= array[index];\n      }\n    }\n  }\n\n  return output;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/best-seat/best-seat.js",
    "content": "/**\n * You walk into a theatre you're about to see a show in. The usher within\n * the theatre walks you to your row and mentions you're allowed to sit\n * anywhere within the given row. Naturally you'd like to sit in the seat\n * that gives you the most space. You also would prefer this space to be\n * evenly distributed on either side of you (e.g. if there are three empty\n * seats in a row, you would prefer to sit in the middle of those three seats).\n * Given the theatre row represented as an integer array, return the seat\n * index of where you should sit. Ones represent occupied seats and zeroes\n * represent empty seats.\n *\n * You may assume that someone is always sitting in the first and last seat\n * of the row. Whenever there are two equally good seats, you should sit in\n * the seat with the lower index. If there is no seat to sit in, return -1.\n * The given array will always have a length of at least one and contain only\n * ones and zeroes.\n *\n * Input: seats = [1, 0, 1, 0, 0, 0, 1]\n * Output: 4\n */\n\n// Runtime: O(N), N = seats length\n// Space: O(1)\n\nfunction bestSeat(seats) {\n  let sequenceIndex;\n  let sequenceIndexTemp;\n  let sequenceLength = 0;\n  let maxSequenceLength = 0;\n\n  for (let index = 1; index < seats.length; index++) {\n    let seat = seats[index];\n\n    if (seat === 0) {\n      sequenceLength++;\n\n      if (!sequenceIndexTemp) {\n        sequenceIndexTemp = index;\n      }\n    } else {\n      if (sequenceLength > maxSequenceLength) {\n        maxSequenceLength = sequenceLength;\n        sequenceIndex = sequenceIndexTemp;\n      }\n\n      sequenceLength = 0;\n      sequenceIndexTemp = undefined;\n    }\n  }\n\n  if (maxSequenceLength <= 0) {\n    return -1;\n  }\n\n  return maxSequenceLength % 2 === 0\n    ? sequenceIndex + Math.floor(maxSequenceLength / 2) - 1\n    : sequenceIndex + Math.floor(maxSequenceLength / 2);\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/binary-search/binary-search.js",
    "content": "// Runtime: O(logN)\n// Space: O(1)\n\nfunction binarySearch(array, target) {\n  let start = 0;\n  let end = array.length - 1;\n  let middle = Math.floor((start + end) / 2);\n\n  while (start <= end) {\n    let num = array[middle];\n\n    if (num === target) {\n      return middle;\n    }\n\n    if (num > target) {\n      end = middle - 1;\n    }\n\n    if (num < target) {\n      start = middle + 1;\n    }\n\n    middle = Math.floor((start + end) / 2);\n  }\n\n  return -1;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/branch-sums/branch-sums-without-recreating-sums.js",
    "content": "// Runtime: O(N), N = number of nodes\n// Space: list of branch sums (number of leaf nodes) is O(N) and recursive algorithm (call stack) is log(N)\n\nclass BinaryTree {\n  constructor(value) {\n    this.value = value;\n    this.left = null;\n    this.right = null;\n  }\n}\n\nfunction branchSums(root) {\n  let sums = [];\n\n  const recursiveBranchSums = (node, sum) => {\n    if (!node) return;\n    let newSum = sum + node.value;\n    if (!node.left && !node.right) return sums.push(newSum);\n    recursiveBranchSums(node.left, newSum);\n    recursiveBranchSums(node.right, newSum);\n  };\n\n  recursiveBranchSums(root, 0);\n  return sums;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/branch-sums/branch-sums.js",
    "content": "// Runtime: O(N), N = number of nodes\n// Space: list of branch sums (number of leaf nodes) is O(N) and recursive algorithm (call stack) is log(N)\n\nclass BinaryTree {\n  constructor(value) {\n    this.value = value;\n    this.left = null;\n    this.right = null;\n  }\n}\n\nfunction branchSums(root, sum = 0, sums = []) {\n  if (!root) return sums;\n  if (!root.left && !root.right) return [...sums, sum + root.value];\n\n  let newSum = sum + root.value;\n  let leftBranch = branchSums(root.left, newSum, sums);\n  let rightBranch = branchSums(root.right, newSum, sums);\n\n  return [...leftBranch, ...rightBranch];\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/bst-construction/bst-construction.js",
    "content": "/**\nBST Construction\n\nWrite a BST class for a Binary Search Tree. The class should support:\n\nInserting values with the insert method.\nRemoving values with the remove method; this method should only remove the first instance of a given value.\nSearching for values with the contains method.\nNote that you can't remove values from a single-node tree.\nIn other words, calling the remove method on a single-node tree should simply not do anything.\n\nEach BST node has an integer value, a left child node, and a right child node.\nA node is said to be a valid BST node if and only if it satisfies the BST property:\nits value is strictly greater than the values of every node to its left;\nits value is less than or equal to the values of every node to its right;\nand its children nodes are either valid BST nodes themselves or None / null. \n*/\n\nclass BST {\n  constructor(value) {\n    this.value = value;\n    this.left = null;\n    this.right = null;\n  }\n\n  insert(value) {\n    if (value < this.value) {\n      if (this.left) this.left.insert(value);\n      else this.left = new BST(value);\n    } else {\n      if (this.right) this.right.insert(value);\n      else this.right = new BST(value);\n    }\n\n    return this;\n  }\n\n  contains(value) {\n    if (this.value === value) {\n      return true;\n    }\n\n    if (value < this.value) {\n      return this.left ? this.left.contains(value) : false;\n    }\n\n    if (value >= this.value) {\n      return this.right ? this.right.contains(value) : false;\n    }\n\n    return false;\n  }\n\n  remove(value, parent = null) {\n    if (parent === null && this.left === null && this.right === null) return;\n\n    if (value === this.value) {\n      // when the node has children:\n      // get the smallest node from the right subtree and replace the removed node with this one\n      if (this.left && this.right) {\n        let smallestNodeValue = this.right._findSmallestNodeValue();\n        this.right.remove(smallestNodeValue, this);\n        this.value = smallestNodeValue;\n        return this;\n      }\n\n      // when the node to be removed is a leaf node: just remove it\n      if (!this.left && !this.right) {\n        if (parent.left === this) parent.left = null;\n        if (parent.right === this) parent.right = null;\n      }\n\n      // when the node to be removed only has one child node: point child node to the parent\n      if (this.left) {\n        let greatestNodeValue = this.left._findGreatestNodeValue();\n        this.value = greatestNodeValue;\n        this.left.remove(greatestNodeValue, this);\n      }\n\n      // when the node to be removed only has one child node: point child node to the parent\n      if (this.right) {\n        let smallestNodeValue = this.right._findSmallestNodeValue();\n        this.value = smallestNodeValue;\n        this.right.remove(smallestNodeValue, this);\n      }\n    }\n\n    if (value < this.value) {\n      if (this.left) {\n        this.left.remove(value, this);\n      }\n    }\n\n    if (value >= this.value) {\n      if (this.right) {\n        this.right.remove(value, this);\n      }\n    }\n\n    return this;\n  }\n\n  _findSmallestNodeValue() {\n    return this.left ? this.left._findSmallestNodeValue() : this.value;\n  }\n\n  _findGreatestNodeValue() {\n    return this.right ? this.right._findGreatestNodeValue() : this.value;\n  }\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/bst-traversal/bst-traversal.js",
    "content": "function inOrderTraverse(tree, array) {\n  if (!tree) return;\n  inOrderTraverse(tree.left, array);\n  array.push(tree.value);\n  inOrderTraverse(tree.right, array);\n  return array;\n}\n\nfunction preOrderTraverse(tree, array) {\n  if (!tree) return;\n  array.push(tree.value);\n  preOrderTraverse(tree.left, array);\n  preOrderTraverse(tree.right, array);\n  return array;\n}\n\nfunction postOrderTraverse(tree, array) {\n  if (!tree) return;\n  postOrderTraverse(tree.left, array);\n  postOrderTraverse(tree.right, array);\n  array.push(tree.value);\n  return array;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/bubble-sort/bubble-sort.js",
    "content": "// Runtime: O(N^2)\n// Space: O(1)\n\nfunction bubbleSort(array) {\n  let sorted = false;\n\n  while (!sorted) {\n    sorted = true;\n    for (let index = 0; index < array.length - 1; index++) {\n      if (array[index] > array[index + 1]) {\n        let aux = array[index];\n        array[index] = array[index + 1];\n        array[index + 1] = aux;\n        sorted = false;\n      }\n    }\n  }\n\n  return array;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/caesar-cipher-encryptor/caesar-cipher-encryptor.js",
    "content": "// Runtime: O(N), N = number of characters\n// Space: O(N)\n\nfunction getChar(char, key) {\n  let charCode = ((char.charCodeAt() - 97 + key) % 26) + 97;\n  return String.fromCharCode(charCode);\n}\n\nfunction caesarCipherEncryptor(string, key) {\n  return [...string].map((char) => getChar(char, key)).join('');\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/class-photos/class-photos.js",
    "content": "function classPhotos(redShirtHeights, blueShirtHeights) {\n  redShirtHeights.sort((a, b) => a - b);\n  blueShirtHeights.sort((a, b) => a - b);\n\n  let backRow;\n  let frontRow;\n\n  if (redShirtHeights[0] < blueShirtHeights[0]) {\n    backRow = blueShirtHeights;\n    frontRow = redShirtHeights;\n  } else {\n    backRow = redShirtHeights;\n    frontRow = blueShirtHeights;\n  }\n\n  for (let index = 0; index < backRow.length; index++) {\n    if (frontRow[index] >= backRow[index]) return false;\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/common-characters/common-characters.js",
    "content": "// Runtime: (N * M), N = number of strings and M = length of biggest string\n// Space: (M), M = length of biggest string\n\n/**\n * Write a function that takes in a non-empty list of non-empty strings and returns\n * a list of characters that are common to all strings in the list, ignoring multiplicity.\n * Note that the strings are not guaranteed to only contain alphanumeric characters.\n * The list you return can be in any order.\n *\n * Input:\n * strings = [\"abc\", \"bcd\", \"cbaccd\"]\n *\n * Output:\n * [\"b\", \"c\"] // The characters could be ordered differently.\n */\n\nfunction commonCharacters(strings) {\n  let map = new Map();\n  let result = [];\n\n  for (let string of strings) {\n    let set = new Set(string);\n\n    for (let char of set) {\n      map.set(char, map.get(char) + 1 || 1);\n    }\n  }\n\n  for (let [char, count] of map) {\n    if (count === strings.length) {\n      result.push(char);\n    }\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/depth-first-search/depth-first-search-cleaner.js",
    "content": "// Runtime: O(V + E), V = vertices, E = edges\n// Space: O(V), V = vertices\n\nclass Node {\n  constructor(name) {\n    this.name = name;\n    this.children = [];\n  }\n\n  addChild(name) {\n    this.children.push(new Node(name));\n    return this;\n  }\n\n  depthFirstSearch(array) {\n    array.push(this.name);\n    for (let child of this.children) {\n      child.depthFirstSearch(array);\n    }\n    return array;\n  }\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/depth-first-search/depth-first-search.js",
    "content": "// Runtime: O(V + E), V = vertices, E = edges\n// Space: O(V), V = vertices\n\nclass Node {\n  constructor(name) {\n    this.name = name;\n    this.children = [];\n  }\n\n  addChild(name) {\n    this.children.push(new Node(name));\n    return this;\n  }\n\n  depthFirstSearch(array) {\n    let queue = [this];\n\n    while (queue.length) {\n      let node = queue.shift();\n      array.push(node.name);\n\n      for (let child of node.children) {\n        child.depthFirstSearch(array);\n      }\n    }\n\n    return array;\n  }\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/evaluate-expression-tree/evaluate-expression-tree-cleaner.js",
    "content": "function evaluateExpressionTree({value, left, right}) {\n  if (value === -1) return evaluateExpressionTree(left) + evaluateExpressionTree(right);\n  if (value === -2) return evaluateExpressionTree(left) - evaluateExpressionTree(right);\n  if (value === -3) return Math.trunc(evaluateExpressionTree(left) / evaluateExpressionTree(right));\n  if (value === -4) return evaluateExpressionTree(left) * evaluateExpressionTree(right);\n  return value;\n}"
  },
  {
    "path": "coding_interviews/algoexpert/evaluate-expression-tree/evaluate-expression-tree-with-trunc.js",
    "content": "function evaluateExpressionTree(tree) {\n  if (!tree) return null;\n\n  let leftValue = evaluateExpressionTree(tree.left);\n  let rightValue = evaluateExpressionTree(tree.right);\n\n  if (!leftValue && !rightValue) return tree.value;\n\n  if (tree.value === -1) return leftValue + rightValue;\n  if (tree.value === -2) return leftValue - rightValue;\n  if (tree.value === -3) return Math.trunc(leftValue / rightValue);\n  if (tree.value === -4) return leftValue * rightValue;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/evaluate-expression-tree/evaluate-expression-tree.js",
    "content": "function evaluateExpressionTree(tree) {\n  if (!tree) return null;\n\n  let leftValue = evaluateExpressionTree(tree.left);\n  let rightValue = evaluateExpressionTree(tree.right);\n\n  if (!leftValue && !rightValue) return tree.value;\n\n  if (tree.value === -1) return leftValue + rightValue;\n  if (tree.value === -2) return leftValue - rightValue;\n  if (tree.value === -3) {\n    let value = leftValue / rightValue;\n    return Math.sign(value) * Math.floor(Math.abs(value));\n  }\n  if (tree.value === -4) return leftValue * rightValue;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/find-closest-value-in-bst/find-closest-value-in-bst-optimized-cleaner.js",
    "content": "// Runtime\n// - average: O(logN), where N = number of nodes in the tree\n// - worst case: O(N), where N = number of nodes in the tree\n// Space: O(1)\n\nfunction abs(value) {\n  return Math.abs(value);\n}\n\nfunction findClosestValueInBst(tree, target, closest = Infinity) {\n  if (!tree) {\n    return closest;\n  }\n\n  if (abs(tree.value - target) < abs(closest - target)) {\n    closest = tree.value;\n  }\n\n  if (target === tree.value) {\n    return closest;\n  }\n\n  if (target < tree.value) {\n    return findClosestValueInBst(tree.left, target, closest);\n  }\n\n  return findClosestValueInBst(tree.right, target, closest);\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/find-closest-value-in-bst/find-closest-value-in-bst-optimized.js",
    "content": "// Runtime\n// - average: O(logN), where N = number of nodes in the tree\n// - worst case: O(N), where N = number of nodes in the tree\n// Space: O(1)\n\nfunction findClosestValueInBst(tree, target, closestValue = Infinity) {\n  if (!tree) {\n    return closestValue;\n  }\n\n  if (tree.value === target) {\n    return target;\n  }\n\n  let currentDiff = Math.abs(tree.value - target);\n  let diff = Math.abs(closestValue - target);\n  let newClosestValue = currentDiff <= diff ? tree.value : closestValue;\n  let leftValue =\n    target < tree.value\n      ? findClosestValueInBst(tree.left, target, newClosestValue)\n      : newClosestValue;\n  let rightValue =\n    target > tree.value\n      ? findClosestValueInBst(tree.right, target, newClosestValue)\n      : newClosestValue;\n  let leftDiff = Math.abs(leftValue - target);\n  let rightDiff = Math.abs(rightValue - target);\n\n  if (currentDiff <= leftDiff && currentDiff <= rightDiff) {\n    return tree.value;\n  } else if (leftDiff <= rightDiff) {\n    return leftValue;\n  }\n\n  return rightValue;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/find-closest-value-in-bst/find-closest-value-in-bst.js",
    "content": "// Runtime: O(N), where N = number of nodes in the tree\n// Space: O(1)\n\nfunction findClosestValueInBst(tree, target, closestValue = Infinity) {\n  if (!tree) {\n    return closestValue;\n  }\n\n  let currentDiff = Math.abs(tree.value - target);\n  let diff = Math.abs(closestValue - target);\n  let leftValue = findClosestValueInBst(\n    tree.left,\n    target,\n    currentDiff <= diff ? tree.value : closestValue\n  );\n  let rightValue = findClosestValueInBst(\n    tree.right,\n    target,\n    currentDiff <= diff ? tree.value : closestValue\n  );\n  let leftDiff = Math.abs(leftValue - target);\n  let rightDiff = Math.abs(rightValue - target);\n\n  if (currentDiff <= leftDiff && currentDiff <= rightDiff) {\n    return tree.value;\n  } else if (leftDiff <= rightDiff) {\n    return leftValue;\n  }\n\n  return rightValue;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/find-three-largest-numbers/find-three-largest-numbers.js",
    "content": "// Runtime: O(N), N = number of numbers in the array\n// Space: O(1)\n\nfunction findThreeLargestNumbers(array) {\n  let first = -Infinity;\n  let second = -Infinity;\n  let third = -Infinity;\n\n  for (let num of array) {\n    if (num > first) {\n      third = second;\n      second = first;\n      first = num;\n    } else if (num > second) {\n      third = second;\n      second = num;\n    } else if (num > third) {\n      third = num;\n    }\n  }\n\n  return [third, second, first];\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/first-duplicate-value/first-duplicate-value-optimized.js",
    "content": "/**\n * Given an array of integers between 1 and n, inclusive, where n is the length of\n * the array, write a function that returns the first integer that appears more\n * than once (when the array is read from left to right).\n * In other words, out of all the integers that might occur more than once in the\n * input array, your function should return the one whose first duplicate\n * value has the minimum index.\n * If no integer appears more than once, your function should return -1.\n * Note that you're allowed to mutate the input array.\n *\n * Input: array = [2, 1, 5, 2, 3, 3, 4]\n * Output: 2\n */\n\n// Runtime: O(N), N = array length\n// Space: O(1)\n\nfunction firstDuplicateValue(array) {\n  for (let index = 0; index < array.length; index++) {\n    let newIndex = Math.abs(array[index]) - 1;\n\n    if (array[newIndex] < 0) {\n      return Math.abs(array[index]);\n    }\n\n    array[newIndex] = array[newIndex] * -1;\n  }\n\n  return -1;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/first-duplicate-value/first-duplicate-value.js",
    "content": "/**\n * Given an array of integers between 1 and n, inclusive, where n is the length of\n * the array, write a function that returns the first integer that appears more\n * than once (when the array is read from left to right).\n * In other words, out of all the integers that might occur more than once in the\n * input array, your function should return the one whose first duplicate\n * value has the minimum index.\n * If no integer appears more than once, your function should return -1.\n * Note that you're allowed to mutate the input array.\n *\n * Input: array = [2, 1, 5, 2, 3, 3, 4]\n * Output: 2\n */\n\n// Runtime: O(N), N = array length\n// Space: O(N)\n\nfunction firstDuplicateValue(array) {\n  let map = new Map();\n\n  for (let num of array) {\n    map.set(num, map.get(num) + 1 || 1);\n\n    if (map.get(num) > 1) {\n      return num;\n    }\n  }\n\n  return -1;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/first-non-repeating-character/first-non-repeating-character.js",
    "content": "// Runtime: O(N), N = string length\n// Space: O(N)\n\nfunction firstNonRepeatingCharacter(string) {\n  let map = new Map();\n\n  for (let char of string) {\n    map.set(char, map.get(char) + 1 || 1);\n  }\n\n  for (let index = 0; index < string.length; index++) {\n    if (map.get(string[index]) <= 1) return index;\n  }\n\n  return -1;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/generate-document/generate-document.js",
    "content": "/**\n *\n * You're given a string of available characters and a string representing a document that you need to generate.\n * Write a function that determines if you can generate the document using the available characters.\n * If you can generate the document, your function should return true; otherwise, it should return false.\n * You're only able to generate the document if the frequency of unique characters in the characters string\n * is greater than or equal to the frequency of unique characters in the document string.\n * For example, if you're given characters = \"abcabc\" and document = \"aabbccc\" you cannot generate\n * the document because you're missing one c.\n * The document that you need to create may contain any characters, including special characters,\n * capital letters, numbers, and spaces.\n * Note: you can always generate the empty string (\"\").\n *\n * Input:\n * characters = \"Bste!hetsi ogEAxpelrt x \"\n * document = \"AlgoExpert is the Best!\"\n *\n * Output:\n * true\n */\n\nfunction generateDocument(characters, document) {\n  let map = new Map();\n\n  for (let char of characters) {\n    map.set(char, map.get(char) + 1 || 1);\n  }\n\n  for (let char of document) {\n    if (map.has(char) && map.get(char) > 0) {\n      map.set(char, map.get(char) - 1);\n    } else {\n      return false;\n    }\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/insertion-sort/insertion-sort.js",
    "content": "// Runtime: O(N^2)\n// Space: O(1)\n\nfunction swap(array, i, j) {\n  let aux = array[i];\n  array[i] = array[j];\n  array[j] = aux;\n}\n\nfunction insertionSort(array) {\n  for (let index = 0; index < array.length; index++) {\n    let toSwapIndex = index;\n    while (toSwapIndex > 0 && array[toSwapIndex] < array[toSwapIndex - 1]) {\n      swap(array, toSwapIndex, toSwapIndex - 1);\n      toSwapIndex -= 1;\n    }\n  }\n\n  return array;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/longest-peak/longest-peak.js",
    "content": "/**\n * Write a function that takes in an array of integers and returns\n * the length of the longest peak in the array.\n * A peak is defined as adjacent integers in the array that are\n * strictly increasing until they reach a tip (the highest value in\n * the peak), at which point they become strictly decreasing.\n * At least three integers are required to form a peak.\n * For example, the integers 1, 4, 10, 2 form a peak, but the\n * integers 4, 0, 10 don't and neither do the integers 1, 2, 2, 0.\n * Similarly, the integers 1, 2, 3 don't form a peak because there\n * aren't any strictly decreasing integers after the 3.\n *\n * Input: array = [1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3]\n * Output: 6 // 0, 10, 6, 5, -1, -3\n */\n\n// Runtime: O(N), N = array length\n// Space: O(1)\n\nfunction longestPeak(array) {\n  let longestPeak = 0;\n  let leftEdge;\n  let rightEdge;\n\n  for (let peakIndex = 1; peakIndex < array.length - 1; peakIndex++) {\n    if (\n      array[peakIndex] > array[peakIndex - 1] &&\n      array[peakIndex] > array[peakIndex + 1]\n    ) {\n      for (let index = peakIndex; index > 0; index--) {\n        if (array[index - 1] < array[index]) {\n          leftEdge = index - 1;\n        } else {\n          break;\n        }\n      }\n\n      for (let index = peakIndex; index < array.length - 1; index++) {\n        if (array[index] > array[index + 1]) {\n          rightEdge = index + 1;\n        } else {\n          break;\n        }\n      }\n\n      longestPeak = Math.max(longestPeak, rightEdge - leftEdge + 1);\n    }\n  }\n\n  return longestPeak;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/majority-element/majority-element.js",
    "content": "// Runtime: O(N^2)\n// Space: O(N)\n\nfunction majorityElement(array) {\n  let half = Math.floor(array.length / 2);\n\n  if (array.length <= 1) return array[0];\n\n  for (let i = 0; i < array.length; i++) {\n    let count = 1;\n    let number = array[i];\n\n    for (let k = i + 1; k < array.length; k++) {\n      if (array[k] === number) {\n        count++;\n      }\n\n      if (count > half) {\n        return number;\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/merge-overlapping-intervals/merge-overlapping-intervals.js",
    "content": "/**\n * Write a function that takes in a non-empty array of arbitrary intervals,\n * merges any overlapping intervals, and returns the new intervals in no\n * particular order.\n * Each interval interval is an array of two integers, with interval[0] as\n * the start of the interval and interval[1] as the end of the interval.\n * Note that back-to-back intervals aren't considered to be overlapping.\n * For example, [1, 5] and [6, 7] aren't overlapping; however, [1, 6] and\n * [6, 7] are indeed overlapping.\n * Also note that the start of any particular interval will always be\n * less than or equal to the end of that interval.\n *\n * Input: intervals = [[1, 2], [3, 5], [4, 7], [6, 8], [9, 10]]\n * Output: [[1, 2], [3, 8], [9, 10]]\n */\n\n// Runtime: O(NlogN), N = array length\n// Space: O(N)\n\nfunction mergeOverlappingIntervals(array) {\n  if (array.length <= 1) return array;\n\n  array.sort((a, b) => a[0] - b[0]);\n\n  let intervals = [];\n  let current = array[0];\n\n  for (let index = 1; index < array.length; index++) {\n    let next = array[index];\n\n    if (current[1] >= next[0]) {\n      current = [current[0], Math.max(current[1], next[1])];\n    } else {\n      intervals.push(current);\n      current = next;\n    }\n\n    if (index === array.length - 1) {\n      intervals.push(current);\n    }\n  }\n\n  return intervals;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/middle-node/middle-node-slow-fast.js",
    "content": "// Runtime: O(N), N = number of nodes in the linked list\n// Space: O(1)\n\nfunction middleNode(linkedList) {\n  let fast = linkedList;\n  let slow = linkedList;\n\n  while (fast && fast.next) {\n    fast = fast.next.next;\n    slow = slow.next;\n  }\n\n  return slow;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/middle-node/middle-node.js",
    "content": "// Runtime: O(N), N = number of nodes in the linked list\n// Space: O(1)\n\nfunction middleNode(linkedList) {\n  let length = 0;\n  let node = linkedList;\n\n  while (linkedList) {\n    linkedList = linkedList.next;\n    length++;\n  }\n\n  let middle = Math.floor(length / 2);\n  let index = 0;\n\n  while (node) {\n    if (index === middle) {\n      return node;\n    }\n\n    node = node.next;\n    index++;\n  }\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/minimum-waiting-time/minimum-waiting-time.js",
    "content": "function minimumWaitingTime(queries) {\n  let waitingTime = 0;\n  let previous = 0;\n\n  queries.sort((a, b) => a - b);\n\n  for (let query of queries) {\n    waitingTime += previous;\n    previous += query;\n  }\n\n  return waitingTime;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/missing-numbers/missing-numbers.js",
    "content": "// Runtime: O(N)\n// Space: O(N)\n\nfunction missingNumbers(nums) {\n  let numbers = [];\n\n  for (let index = 0; index < nums.length + 2; index++) {\n    numbers.push(index + 1);\n  }\n\n  for (let num of nums) {\n    numbers[num - 1] = 0;\n  }\n\n  let result = [];\n\n  for (let num of numbers) {\n    if (num) result.push(num);\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/monotonic-array/monotonic-array-optimization-1.js",
    "content": "/**\n * Write a function that takes in an array of integers and returns a boolean\n * representing whether the array is monotonic.\n * An array is said to be monotonic if its elements, from left to right, are\n * entirely non-increasing or entirely non-decreasing.\n * Non-increasing elements aren't necessarily exclusively decreasing; they\n * simply don't increase. Similarly, non-decreasing elements aren't necessarily\n * exclusively increasing; they simply don't decrease.\n * Note that empty arrays and arrays of one element are monotonic.\n *\n * Input:\n * array = [-1, -5, -10, -1100, -1100, -1101, -1102, -9001]\n *\n * Output:\n * true\n */\n\n// Runtime: O(N), N = array length\n// Space: O(1)\n\nfunction isMonotonic(array) {\n  let num = array[0];\n  let upward;\n\n  for (let index = 1; index < array.length; index++) {\n    if (upward === undefined) {\n      upward = array[index] !== num ? array[index] > num : undefined;\n    }\n\n    if (upward !== undefined && upward && array[index] < num) {\n      return false;\n    }\n\n    if (upward !== undefined && !upward && array[index] > num) {\n      return false;\n    }\n\n    num = array[index];\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/monotonic-array/monotonic-array-optimization-2.js",
    "content": "/**\n * Write a function that takes in an array of integers and returns a boolean\n * representing whether the array is monotonic.\n * An array is said to be monotonic if its elements, from left to right, are\n * entirely non-increasing or entirely non-decreasing.\n * Non-increasing elements aren't necessarily exclusively decreasing; they\n * simply don't increase. Similarly, non-decreasing elements aren't necessarily\n * exclusively increasing; they simply don't decrease.\n * Note that empty arrays and arrays of one element are monotonic.\n *\n * Input:\n * array = [-1, -5, -10, -1100, -1100, -1101, -1102, -9001]\n *\n * Output:\n * true\n */\n\n// Runtime: O(N), N = array length\n// Space: O(1)\n\nfunction isMonotonic(array) {\n  let isNonDecreasing = true;\n  let isNonIncreasing = true;\n\n  for (let index = 0; index < array.length - 1; index++) {\n    if (array[index] > array[index + 1]) isNonDecreasing = false;\n    if (array[index] < array[index + 1]) isNonIncreasing = false;\n  }\n\n  return isNonDecreasing || isNonIncreasing;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/monotonic-array/monotonic-array.js",
    "content": "/**\n * Write a function that takes in an array of integers and returns a boolean\n * representing whether the array is monotonic.\n * An array is said to be monotonic if its elements, from left to right, are\n * entirely non-increasing or entirely non-decreasing.\n * Non-increasing elements aren't necessarily exclusively decreasing; they\n * simply don't increase. Similarly, non-decreasing elements aren't necessarily\n * exclusively increasing; they simply don't decrease.\n * Note that empty arrays and arrays of one element are monotonic.\n *\n * Input:\n * array = [-1, -5, -10, -1100, -1100, -1101, -1102, -9001]\n *\n * Output:\n * true\n */\n\n// Runtime: O(N), N = array length\n// Space: O(1)\n\nfunction isNonIncreasing(array) {\n  let num = array[0];\n\n  for (let index = 1; index < array.length; index++) {\n    if (array[index] > num) {\n      return false;\n    }\n    num = array[index];\n  }\n\n  return true;\n}\n\nfunction isNonDecreasing(array) {\n  let num = array[0];\n\n  for (let index = 1; index < array.length; index++) {\n    if (array[index] < num) {\n      return false;\n    }\n    num = array[index];\n  }\n\n  return true;\n}\n\nfunction isMonotonic(array) {\n  return isNonIncreasing(array) || isNonDecreasing(array);\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/move-element-to-end/move-element-to-end.js",
    "content": "/**\n * You're given an array of integers and an integer. Write a function that\n * moves all instances of that integer in the array to the end of the\n * array and returns the array.\n * The function should perform this in place (i.e., it should mutate the input array)\n * and doesn't need to maintain the order of the other integers.\n *\n * Input:\n * array = [2, 1, 2, 2, 2, 3, 4, 2]\n * toMove = 2\n *\n * Output:\n * [1, 3, 4, 2, 2, 2, 2, 2]\n */\n\n// Runtime: O(2N) = O(N), where N = array length\n// Space: O(1)\n\nfunction moveElementToEnd(array, toMove) {\n  let pointer = 0;\n\n  for (let index = 0; index < array.length; index++) {\n    if (array[index] !== toMove) {\n      array[pointer] = array[index];\n      pointer++;\n    }\n  }\n\n  for (let index = pointer; index < array.length; index++) {\n    array[index] = toMove;\n  }\n\n  return array;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/node-depths/node-depths.js",
    "content": "// Runtime: O(N), N = number of nodes\n// Space: O(H), H = height of the tree\n\nfunction nodeDepths(root, sum = 0) {\n  if (!root) return 0;\n  return sum + nodeDepths(root.left, sum + 1) + nodeDepths(root.right, sum + 1);\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/non-constructible-change/non-constructible-change.js",
    "content": "// Runtime: O(nlogn)\n// Space: O(1)\n\nfunction nonConstructibleChange(coins) {\n  coins.sort((a, b) => a - b);\n\n  let currentChangeCreated = 0;\n\n  for (let coin of coins) {\n    if (coin > currentChangeCreated + 1) {\n      return currentChangeCreated + 1;\n    }\n\n    currentChangeCreated += coin;\n  }\n\n  return currentChangeCreated + 1;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/nth-fibonacci/nth-fibonacci-memo-no-space.js",
    "content": "// Runtime: O(N)\n// Space: O(1)\n\nfunction getNthFib(n) {\n  if (n === 1) return 0;\n  if (n === 2) return 1;\n\n  let first = 0;\n  let second = 1;\n\n  for (let num = 3; num <= n; num++) {\n    let sum = first + second;\n    first = second;\n    second = sum;\n  }\n\n  return second;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/nth-fibonacci/nth-fibonacci-memo.js",
    "content": "// Runtime: O(N)\n// Space: O(N)\n\nfunction getNthFib(n) {\n  if (n === 1) return 0;\n  if (n === 2) return 1;\n\n  let memo = [0, 0, 1];\n  let result;\n\n  for (let num = 3; num <= n; num++) {\n    result = memo[num - 1] + memo[num - 2];\n    memo.push(result);\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/nth-fibonacci/nth-fibonacci.js",
    "content": "// Runtime: O(2^N)\n// Space: O(N)\n\nfunction getNthFib(n) {\n  if (n === 0) return 0;\n  if (n === 1) return 0;\n  if (n === 2) return 1;\n  return getNthFib(n - 1) + getNthFib(n - 2);\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/optimal-freelancing/optimal-freelancing-sorting.js",
    "content": "function sortJobs(jobs) {\n  jobs.sort((job1, job2) => {\n    if (job1.payment > job2.payment) return -1;\n    if (job1.payment < job2.payment) return 1;\n    return 0;\n  });\n}\n\nfunction optimalFreelancing(jobs) {\n  let profit = 0;\n  let days = [0, 0, 0, 0, 0, 0, 0];\n\n  sortJobs(jobs);\n\n  for (let { deadline, payment } of jobs) {\n    let maxTime = Math.min(deadline, 7);\n\n    for (let time = maxTime; time >= 1; time--) {\n      if (days[time - 1] === 0) {\n        profit += payment;\n        days[time - 1] = payment;\n        break;\n      }\n    }\n  }\n\n  return profit;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/optimal-freelancing/optimal-freelancing.js",
    "content": "function optimalFreelancing(jobs) {\n  let profit = 0;\n  let day = 7;\n  let completedJobs = new WeakSet();\n\n  while (day > 0) {\n    let bestJob;\n\n    for (let job of jobs) {\n      if (\n        job.deadline >= day &&\n        job.payment > (bestJob?.payment || 0) &&\n        !completedJobs.has(job)\n      ) {\n        bestJob = job;\n      }\n    }\n\n    day--;\n\n    if (bestJob) {\n      completedJobs.add(bestJob);\n      profit += bestJob.payment;\n    }\n  }\n\n  return profit;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/palindrome-check/palindrome-check.js",
    "content": "// Runtime: O(N), N = characters in the string\n// Space: O(1)\n\nfunction isPalindrome(string) {\n  let start = 0;\n  let end = string.length - 1;\n  let middle = Math.floor((start + end) / 2);\n\n  while (start <= middle && end >= middle) {\n    if (string[start] !== string[end]) {\n      return false;\n    }\n\n    start++;\n    end--;\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/product-sum/product-sum-timer-later.js",
    "content": "// Runtime: O(N), N = all numbers including the numbers inside nested arrays\n// Space: O(D), D = the depth of the nested arrays\n\nfunction productSum(array, depth = 1) {\n  let sum = 0;\n\n  for (let num of array) {\n    if (Array.isArray(num)) {\n      sum += productSum(num, depth + 1);\n    } else {\n      sum += num;\n    }\n  }\n\n  return sum * depth;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/product-sum/product-sum.js",
    "content": "// Runtime: O(N), N = all numbers including the numbers inside nested arrays\n// Space: O(D), D = the depth of the nested arrays\n\nfunction productSum(array, product = 1) {\n  let sum = 0;\n\n  for (let num of array) {\n    if (Array.isArray(num)) {\n      sum += productSum(num, product + 1) * product;\n    } else {\n      sum += num * product;\n    }\n  }\n\n  return sum;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/remove-duplicates-from-linked-list/remove-duplicates-from-linked-list.js",
    "content": "// Runtime: O(N), N = number of nodes in the linked list\n// Space: O(1)\n\nfunction removeDuplicatesFromLinkedList(linkedList) {\n  let head = linkedList;\n  while (linkedList) {\n    let next = linkedList.next;\n    while (next && linkedList.value === next.value) {\n      next = next.next;\n    }\n    linkedList.next = next;\n    linkedList = next;\n  }\n  return head;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/remove-islands/remove-islands-optimized.js",
    "content": "/**\nYou're given a two-dimensional array (a matrix) of potentially unequal height and width containing only 0s and 1s.\nThe matrix represents a two-toned image, where each 1 represents black and each 0 represents white.\nAn island is defined as any number of 1s that are horizontally or vertically adjacent (but not diagonally adjacent)\nand that don't touch the border of the image. In other words, a group of horizontally or vertically adjacent 1s isn't an island\nif any of those 1s are in the first row, last row, first column, or last column of the input matrix.\nNote that an island can twist. In other words, it doesn't have to be a straight vertical line or a straight horizontal line;\nit can be L-shaped, for example.\n\nYou can think of islands as patches of black that don't touch the border of the two-toned image.\nWrite a function that returns a modified version of the input matrix, where all of the islands are removed.\nYou remove an island by replacing it with 0s.\n\nNaturally, you're allowed to mutate the input matrix.\n */\n\nfunction markNonIsland(matrix, rowIndex, colIndex) {\n  if (\n    rowIndex < 0 ||\n    rowIndex >= matrix.length ||\n    colIndex < 0 ||\n    colIndex >= matrix[rowIndex].length ||\n    [0, 2].includes(matrix[rowIndex][colIndex])\n  ) {\n    return;\n  }\n\n  matrix[rowIndex][colIndex] = 2;\n  markNonIsland(matrix, rowIndex - 1, colIndex); // top\n  markNonIsland(matrix, rowIndex + 1, colIndex); // bottom\n  markNonIsland(matrix, rowIndex, colIndex - 1); // left\n  markNonIsland(matrix, rowIndex, colIndex + 1); // right\n}\n\nfunction removeIslands(matrix) {\n  const lastRowIndex = matrix.length - 1;\n  const lastColIndex = matrix[0].length - 1;\n\n  for (let colIndex = 0; colIndex < matrix[0].length; colIndex++) {\n    if (matrix[0][colIndex] === 1) markNonIsland(matrix, 0, colIndex);\n    if (matrix[lastRowIndex][colIndex] === 1)\n      markNonIsland(matrix, lastRowIndex, colIndex);\n  }\n\n  for (let rowIndex = 0; rowIndex < matrix.length; rowIndex++) {\n    if (matrix[rowIndex][0] === 1) markNonIsland(matrix, rowIndex, 0);\n    if (matrix[rowIndex][lastColIndex] === 1)\n      markNonIsland(matrix, rowIndex, lastColIndex);\n  }\n\n  for (let rowIndex = 0; rowIndex < matrix.length; rowIndex++) {\n    for (let colIndex = 0; colIndex < matrix[rowIndex].length; colIndex++) {\n      if (matrix[rowIndex][colIndex] === 1) {\n        matrix[rowIndex][colIndex] = 0;\n      }\n\n      if (matrix[rowIndex][colIndex] === 2) {\n        matrix[rowIndex][colIndex] = 1;\n      }\n    }\n  }\n\n  return matrix;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/remove-islands/remove-islands.js",
    "content": "/**\nYou're given a two-dimensional array (a matrix) of potentially unequal height and width containing only 0s and 1s.\nThe matrix represents a two-toned image, where each 1 represents black and each 0 represents white.\nAn island is defined as any number of 1s that are horizontally or vertically adjacent (but not diagonally adjacent)\nand that don't touch the border of the image. In other words, a group of horizontally or vertically adjacent 1s isn't an island\nif any of those 1s are in the first row, last row, first column, or last column of the input matrix.\nNote that an island can twist. In other words, it doesn't have to be a straight vertical line or a straight horizontal line;\nit can be L-shaped, for example.\n\nYou can think of islands as patches of black that don't touch the border of the two-toned image.\nWrite a function that returns a modified version of the input matrix, where all of the islands are removed.\nYou remove an island by replacing it with 0s.\n\nNaturally, you're allowed to mutate the input matrix.\n */\n\nfunction removeIsland(matrix, rowIndex, colIndex) {\n  if (\n    rowIndex < 0 ||\n    rowIndex >= matrix.length ||\n    colIndex < 0 ||\n    colIndex >= matrix[rowIndex].length\n  ) {\n    return;\n  }\n\n  if ([0, 2].includes(matrix[rowIndex][colIndex])) {\n    return;\n  }\n\n  matrix[rowIndex][colIndex] = 2;\n  removeIsland(matrix, rowIndex - 1, colIndex); // top\n  removeIsland(matrix, rowIndex + 1, colIndex); // bottom\n  removeIsland(matrix, rowIndex, colIndex - 1); // left\n  removeIsland(matrix, rowIndex, colIndex + 1); // right\n}\n\nfunction removeIslands(matrix) {\n  for (let rowIndex = 0; rowIndex < matrix.length; rowIndex++) {\n    for (let colIndex = 0; colIndex < matrix[rowIndex].length; colIndex++) {\n      if (\n        matrix[rowIndex][colIndex] === 1 &&\n        (rowIndex === 0 ||\n          rowIndex === matrix.length - 1 ||\n          colIndex === 0 ||\n          colIndex === matrix[rowIndex].length - 1)\n      ) {\n        removeIsland(matrix, rowIndex, colIndex);\n      }\n    }\n  }\n\n  for (let rowIndex = 0; rowIndex < matrix.length; rowIndex++) {\n    for (let colIndex = 0; colIndex < matrix[rowIndex].length; colIndex++) {\n      if (matrix[rowIndex][colIndex] === 1) {\n        matrix[rowIndex][colIndex] = 0;\n      }\n\n      if (matrix[rowIndex][colIndex] === 2) {\n        matrix[rowIndex][colIndex] = 1;\n      }\n    }\n  }\n\n  return matrix;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/run-length-encoding/run-length-encoding copy.js",
    "content": "function runLengthEncoding(string) {\n  let currentChar;\n  let num = 1;\n  let result = [];\n\n  for (let index = 0; index < string.length; index++) {\n    currentChar = string[index];\n    if (currentChar === string[index + 1] && num < 9) {\n      num++;\n    } else {\n      result.push(`${num}${currentChar}`);\n      num = 1;\n    }\n  }\n\n  return result.join('');\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/run-length-encoding/run-length-encoding-cleaner.js",
    "content": "function runLengthEncoding(string) {\n  if (string.length === 1) {\n    return `1${string}`;\n  }\n\n  let currentChar = string[0];\n  let num = 1;\n  let result = [];\n\n  for (let index = 1; index < string.length; index++) {\n    let char = string[index];\n\n    if (char === currentChar) {\n      if (num === 9) {\n        result.push(num);\n        result.push(currentChar);\n        num = 1;\n      } else {\n        num++;\n      }\n    } else {\n      result.push(num);\n      result.push(currentChar);\n      num = 1;\n      currentChar = char;\n    }\n\n    if (index === string.length - 1) {\n      result.push(num);\n      result.push(currentChar);\n    }\n  }\n\n  return result.join('');\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/run-length-encoding/run-length-encoding.js",
    "content": "function runLengthEncoding(string) {\n  if (string.length === 1) {\n    return `1${string}`;\n  }\n\n  let currentChar = string[0];\n  let num = 1;\n  let result = [];\n\n  for (let index = 1; index < string.length; index++) {\n    let char = string[index];\n\n    if (char === currentChar) {\n      if (num === 9) {\n        result.push(num);\n        result.push(currentChar);\n        num = 1;\n      } else {\n        num++;\n      }\n    } else {\n      result.push(num);\n      result.push(currentChar);\n      num = 1;\n      currentChar = char;\n    }\n\n    if (index === string.length - 1) {\n      result.push(num);\n      result.push(currentChar);\n    }\n  }\n\n  return result.join('');\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/semordnilap/semordnilap.js",
    "content": "/**\nWrite a function that takes in a list of unique strings\nand returns a list of semordnilap pairs.\n\nA semordnilap pair is defined as a set of different strings\nwhere the reverse of one word is the same as the forward version\nof the other. For example the words \"diaper\" and \"repaid\" are a\nsemordnilap pair, as are the words \"palindromes\" and \"semordnilap\".\n\nThe order of the returned pairs and the order of the strings\nwithin each pair does not matter.\n*/\n\n// Runtime: O(N * M), N = number of words, M = length o largest word\n// Space: O(N)\n\nfunction reverse(word) {\n  let reversedWord = [];\n\n  for (let index = word.length - 1; index >= 0; index--) {\n    reversedWord.push(word[index]);\n  }\n\n  return reversedWord.join('');\n}\n\nfunction semordnilap(words) {\n  let pairs = [];\n  let map = new Map();\n\n  for (let word of words) {\n    if (map.has(word)) {\n      pairs.push([word, map.get(word)]);\n    } else {\n      map.set(reverse(word), word);\n    }\n  }\n\n  return pairs;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/smallest-difference/smallest-difference.js",
    "content": "/**\n *\n * Write a function that takes in two non-empty arrays of integers,\n * finds the pair of numbers (one from each array) whose absolute\n * difference is closest to zero, and returns an array containing\n * these two numbers, with the number from the first array in the first position.\n * Note that the absolute difference of two integers is the distance\n * between them on the real number line. For example, the absolute\n * difference of -5 and 5 is 10, and the absolute difference of -5 and -4 is 1.\n * You can assume that there will only be one pair of numbers with the smallest difference.\n *\n * Input:\n * arrayOne = [-1, 5, 10, 20, 28, 3]\n * arrayTwo = [26, 134, 135, 15, 17]\n *\n * Output:\n * [28, 26]\n */\n\n// Runtime: O(NlogN + MlogM), where N = length of arrayOne and M = length of arrayTwo\n// Space: O(1)\n\nfunction smallestDifference(arrayOne, arrayTwo) {\n  let output = [];\n  let indexOne = 0;\n  let indexTwo = 0;\n  let smallestDistance = Infinity;\n\n  arrayOne.sort((a, b) => a - b);\n  arrayTwo.sort((a, b) => a - b);\n\n  while (indexOne < arrayOne.length && indexTwo < arrayTwo.length) {\n    let one = arrayOne[indexOne];\n    let two = arrayTwo[indexTwo];\n    let distance = Math.abs(one - two);\n\n    if (distance < smallestDistance) {\n      smallestDistance = distance;\n      output = [one, two];\n    }\n\n    if (one < two) indexOne++;\n    else indexTwo++;\n  }\n\n  return output;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/sorted-squared-array/sorted-squared-array-insert-position.js",
    "content": "// Runtime: O(n)\n// Space: O(n)\n\nfunction sortedSquaredArray(array) {\n  let output = [];\n\n  for (let num of array) {\n    let square = num * num;\n    let inserted = false;\n\n    for (let index = 0; index < output.length; index++) {\n      if (square <= output[index]) {\n        output = [...output.slice(0, index), square, ...output.slice(index)];\n        inserted = true;\n        break;\n      }\n    }\n\n    if (!inserted) output.push(square);\n  }\n\n  return output;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/sorted-squared-array/sorted-squared-array-two-pointers.js",
    "content": "// Runtime: O(n)\n// Space: O(n)\n\nfunction sortedSquaredArray(array) {\n  let p1 = 0;\n  let p2 = array.length - 1;\n  let result = [];\n\n  while (p1 <= p2) {\n    let square1 = array[p1] * array[p1];\n    let square2 = array[p2] * array[p2];\n\n    if (square1 > square2) {\n      result.unshift(square1);\n      p1++;\n    } else {\n      result.unshift(square2);\n      p2--;\n    }\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/sorted-squared-array/sorted-squared-array.js",
    "content": "// Runtime: O(nlogn)\n// Space: O(1)\n\nfunction sortedSquaredArray(array) {\n  return array.map((num) => num * num).sort((a, b) => a - b);\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/spiral-traverse/spiral-traverse.js",
    "content": "/**\n *\n * Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m)\n * and returns a one-dimensional array of all the array's elements in spiral order.\n * Spiral order starts at the top left corner of the two-dimensional array, goes to the right,\n * and proceeds in a spiral pattern all the way until every element has been visited.\n *\n * Input:\n * array = [\n *  [1,   2,  3, 4],\n *  [12, 13, 14, 5],\n *  [11, 16, 15, 6],\n *  [10,  9,  8, 7],\n * ]\n *\n * Output:\n * [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]\n */\n\n// Right: keep the row and increase the column\n// Bottom: keep the column and increase the row\n// Left: keep the row and decrease the column\n// Top: keep the column and decrease the row\n\nfunction spiralTraverse(array) {\n  let row = 0;\n  let col = 0;\n  let endRow = array.length - 1;\n  let endCol = array[0].length - 1;\n  let output = [];\n  let command = 'R';\n\n  while (col <= endCol && row <= endRow) {\n    if (command === 'R') {\n      for (let index = col; index <= endCol; index++) {\n        output.push(array[row][index]);\n      }\n\n      row++;\n      command = 'B';\n      continue;\n    }\n\n    if (command === 'B') {\n      for (let index = row; index <= endRow; index++) {\n        output.push(array[index][endCol]);\n      }\n\n      endCol--;\n      command = 'L';\n      continue;\n    }\n\n    if (command === 'L') {\n      for (let index = endCol; index >= col; index--) {\n        output.push(array[endRow][index]);\n      }\n\n      endRow--;\n      command = 'T';\n      continue;\n    }\n\n    if (command === 'T') {\n      for (let index = endRow; index >= row; index--) {\n        output.push(array[index][col]);\n      }\n\n      col++;\n      command = 'R';\n      continue;\n    }\n  }\n\n  return output;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/tandem-bicycle/tandem-bicycle-cleaner.js",
    "content": "// Runtime: O(NlogN)\n// Space: O(1)\n\nfunction getTotalSpeed(redShirtSpeeds, blueShirtSpeeds) {\n  let sum = 0;\n\n  for (let index = 0; index < redShirtSpeeds.length; index++) {\n    sum += Math.max(redShirtSpeeds[index], blueShirtSpeeds[index]);\n  }\n\n  return sum;\n}\n\nfunction tandemBicycle(redShirtSpeeds, blueShirtSpeeds, fastest) {\n  redShirtSpeeds.sort((a, b) => a - b);\n  blueShirtSpeeds.sort((a, b) => (fastest ? b - a : a - b));\n\n  return getTotalSpeed(redShirtSpeeds, blueShirtSpeeds);\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/tandem-bicycle/tandem-bicycle.js",
    "content": "// Runtime: O(NlogN)\n// Space: O(1)\n\nfunction getMinimumTotalSpeed(redShirtSpeeds, blueShirtSpeeds) {\n  let sum = 0;\n\n  for (let index = 0; index < redShirtSpeeds.length; index++) {\n    sum += Math.max(redShirtSpeeds[index], blueShirtSpeeds[index]);\n  }\n\n  return sum;\n}\n\nfunction getMaximumTotalSpeed(redShirtSpeeds, blueShirtSpeeds) {\n  let sum = 0;\n\n  for (let index = 0; index < redShirtSpeeds.length; index++) {\n    sum += Math.max(\n      redShirtSpeeds[index],\n      blueShirtSpeeds[blueShirtSpeeds.length - index - 1]\n    );\n  }\n\n  return sum;\n}\n\nfunction tandemBicycle(redShirtSpeeds, blueShirtSpeeds, fastest) {\n  redShirtSpeeds.sort((a, b) => a - b);\n  blueShirtSpeeds.sort((a, b) => a - b);\n\n  return fastest\n    ? getMaximumTotalSpeed(redShirtSpeeds, blueShirtSpeeds)\n    : getMinimumTotalSpeed(redShirtSpeeds, blueShirtSpeeds);\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/three-number-sum/three-number-sum.js",
    "content": "function sortKey(array) {\n  return [...new Set(array)]\n    .sort((a, b) => a - b)\n    .map((num) => num.toString())\n    .join('*');\n}\n\nfunction threeNumberSum(array, targetSum) {\n  array.sort((a, b) => a - b);\n\n  let map = new Map();\n  let triplets = [];\n  let cache = new Map();\n\n  for (let num of array) {\n    map.set(num, map.get(num) + 1 || 1);\n  }\n\n  for (let i = 0; i < array.length; i++) {\n    for (let j = i + 1; j < array.length; j++) {\n      let rest = targetSum - array[i] - array[j];\n      let triplet = [array[i], array[j], rest];\n      let sortedKey = sortKey(triplet);\n      let allEqual =\n        array[i] === array[j] &&\n        array[i] === rest &&\n        map.has(rest) &&\n        map.get(rest) >= 3;\n      let isFirstEqualRest =\n        array[i] !== array[j] &&\n        array[i] === rest &&\n        map.has(rest) &&\n        map.get(rest) >= 2;\n      let isSecondEqualRest =\n        array[i] !== array[j] &&\n        array[j] === rest &&\n        map.has(rest) &&\n        map.get(rest) >= 2;\n      let hasRest = array[i] !== rest && array[j] !== rest && map.has(rest);\n      let isEligibleTriplet =\n        (allEqual && isFirstEqualRest && isSecondEqualRest) || hasRest;\n\n      if (!cache.has(sortedKey) && isEligibleTriplet) {\n        cache.set(sortedKey, 1);\n        triplets.push(triplet);\n      }\n    }\n  }\n\n  return triplets;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/tournament-winner/tournament-winner-optimized.js",
    "content": "// Runtime: O(n), n being the number of competition\n// Space: O(k), k being the number of teams\n\nfunction tournamentWinner(competitions, results) {\n  let teams = new Map();\n  let maxPoints = 0;\n  let winner;\n\n  for (let index = 0; index < competitions.length; index++) {\n    let competition = competitions[index];\n    let result = results[index];\n    let team = result === 1 ? competition[0] : competition[1];\n    let points = (teams.get(team) || 0) + 3;\n\n    teams.set(team, points);\n\n    if (points > maxPoints) {\n      winner = team;\n      maxPoints = points;\n    }\n  }\n\n  return winner;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/tournament-winner/tournament-winner.js",
    "content": "// Runtime: O(n), n being the number of competition\n// Space: O(k), k being the number of teams\n\nfunction tournamentWinner(competitions, results) {\n  let teams = new Map();\n  let maxPoints = 0;\n  let winner;\n\n  for (let index = 0; index < competitions.length; index++) {\n    let competition = competitions[index];\n    let result = results[index];\n    let team = result === 1 ? competition[0] : competition[1];\n\n    teams.set(team, (teams.get(team) || 0) + 3);\n  }\n\n  for (let [team, points] of teams.entries()) {\n    if (points > maxPoints) {\n      winner = team;\n      maxPoints = points;\n    }\n  }\n\n  return winner;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/transpose-matrix/transpose-matrix.js",
    "content": "// Runtime: O(R * C), R = rows and C = columns\n// Space: O(N)\n\nfunction transposeMatrix(matrix) {\n  let transposedMatrix = [];\n\n  for (let col = 0; col < matrix[0].length; col++) {\n    let newRow = [];\n    for (let row = 0; row < matrix.length; row++) {\n      let cell = matrix[row][col];\n      newRow.push(cell);\n    }\n    transposedMatrix.push(newRow);\n  }\n\n  return transposedMatrix;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/two-number-sum/two-number-sum-optimized.js",
    "content": "// Runtime: O(n)\n// Space: O(n)\n\nfunction twoNumberSum(array, targetSum) {\n  let hashmap = new Map();\n\n  for (let num of array) {\n    let complement = targetSum - num;\n\n    if (hashmap.has(complement)) {\n      return [num, complement];\n    }\n\n    hashmap.set(num, num);\n  }\n\n  return [];\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/two-number-sum/two-number-sum-two-pointers.js",
    "content": "// Runtime: O(nlogn)\n// Space: O(1)\n\nfunction twoNumberSum(array, targetSum) {\n  array.sort((a, b) => a - b);\n\n  let left = 0;\n  let right = array.length - 1;\n\n  while (left < right) {\n    let leftNumber = array[left];\n    let rightNumber = array[right];\n\n    if (leftNumber + rightNumber === targetSum) {\n      return [leftNumber, rightNumber];\n    }\n\n    if (leftNumber + rightNumber > targetSum) {\n      right--;\n    } else {\n      left++;\n    }\n  }\n\n  return [];\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/two-number-sum/two-number-sum.js",
    "content": "// Runtime: O(n^2)\n// Space: O(1)\n\nfunction twoNumberSum(array, targetSum) {\n  let hashmap = new Map();\n\n  for (let num of array) {\n    hashmap.set(num, num);\n  }\n\n  for (let num of array) {\n    let match = targetSum - num;\n    if (match !== num && hashmap.has(match)) {\n      return [num, match];\n    }\n  }\n\n  return [];\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/validate-bst/validate-bst.js",
    "content": "class BST {\n  constructor(value) {\n    this.value = value;\n    this.left = null;\n    this.right = null;\n  }\n}\n\nfunction validateBst(tree) {\n  if (!tree) return true;\n\n  let greaterThanLeftChild = true;\n  let smallerThanOrEqualToRightChild = true;\n\n  if (tree.left) greaterThanLeftChild = tree.left.value < tree.value;\n  if (tree.right)\n    smallerThanOrEqualToRightChild = tree.right.value >= tree.value;\n\n  return (\n    greaterThanLeftChild &&\n    smallerThanOrEqualToRightChild &&\n    validateBst(tree.left) &&\n    validateBst(tree.right)\n  );\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/validate-subsequence/validate-subsequence-two-pointers.js",
    "content": "// Runtime: O(n)\n// Space: O(1)\n\nfunction isValidSubsequence(array, sequence) {\n  let p1 = 0;\n  let p2 = 0;\n\n  while (p1 < array.length && p2 < sequence.length) {\n    if (array[p1] === sequence[p2]) {\n      p1++;\n      p2++;\n    } else {\n      p1++;\n    }\n  }\n\n  return p2 === sequence.length;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/validate-subsequence/validate-subsequence.js",
    "content": "// Runtime: O(n)\n// Space: O(1)\n\nfunction isValidSubsequence(array, sequence) {\n  let p = 0;\n\n  for (let index = 0; index < array.length; index++) {\n    if (array[index] === sequence[p]) {\n      p++;\n    }\n\n    if (p === sequence.length) {\n      return true;\n    }\n  }\n\n  return false;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/zero-sum-subarray/zero-sum-subarray-optimized.js",
    "content": "// Runtime: O(N), N = nums length\n// Space: O(N)\n\nfunction zeroSumSubarray(nums) {\n  let currentSum = 0;\n  let sums = new Set();\n\n  for (let index = 0; index < nums.length; index++) {\n    currentSum += nums[index];\n\n    if (currentSum === 0 || sums.has(currentSum)) {\n      return true;\n    }\n\n    sums.add(currentSum);\n  }\n\n  return false;\n}\n"
  },
  {
    "path": "coding_interviews/algoexpert/zero-sum-subarray/zero-sum-subarray.js",
    "content": "// Runtime: O(N^2), N = nums length\n// Space: O(1)\n\nfunction zeroSumSubarray(nums) {\n  for (let i = 0; i < nums.length; i++) {\n    let sum = nums[i];\n\n    for (let j = i; j < nums.length; j++) {\n      if (i !== j) {\n        sum += nums[j];\n      }\n\n      if (sum === 0) {\n        return true;\n      }\n    }\n  }\n\n  return false;\n}\n"
  },
  {
    "path": "coding_interviews/algorithms_in_python/queue/R-6.7.py",
    "content": "# What values are returned during the following sequence of queue operations,\n# if executed on an initially empty queue? enqueue(5), enqueue(3), dequeue(),\n# enqueue(2), enqueue(8), dequeue(), dequeue(), enqueue(9), enqueue(1), dequeue(),\n# enqueue(7), enqueue(6), dequeue(), dequeue(), enqueue(4), dequeue(), dequeue().\n\n\nclass Emptiness(Exception):\n    pass\n\n\nclass Queue:\n    def __init__(self):\n        self.items = []\n\n    def enqueue(self, item):\n        self.items.append(item)\n\n    def dequeue(self):\n        if self.is_empty():\n            raise Emptiness('The Queue is empty')\n\n        return self.items.pop(0)\n\n    def is_empty(self):\n        return self.size() == 0\n\n    def front(self):\n        if self.is_empty():\n            raise Emptiness('The Queue is empty')\n\n        return self.items[0]\n\n    def back(self):\n        if self.is_empty():\n            raise Emptiness('The Queue is empty')\n\n        return self.items[-1]\n\n    def size(self):\n        return len(self.items)\n\n\nqueue = Queue()\nqueue.enqueue(5)  # [5]\nqueue.enqueue(3)  # [5, 3]\nqueue.dequeue()  # [3]\nqueue.enqueue(2)  # [3, 2]\nqueue.enqueue(8)  # [3, 2, 8]\nqueue.dequeue()  # [2, 8]\nqueue.dequeue()  # [8]\nqueue.enqueue(9)  # [8, 9]\nqueue.enqueue(1)  # [8, 9, 1]\nqueue.dequeue()  # [9, 1]\nqueue.enqueue(7)  # [9, 1, 7]\nqueue.enqueue(6)  # [9, 1, 7, 6]\nqueue.dequeue()  # [1, 7, 6]\nqueue.dequeue()  # [7, 6]\nqueue.enqueue(4)  # [7, 6, 4]\nqueue.dequeue()  # [6, 4]\nqueue.dequeue()  # [4]\n"
  },
  {
    "path": "coding_interviews/algorithms_in_python/stack/R-6.1.py",
    "content": "# R-6.1 from the Algorithms in Pytho book\n# What values are returned during the following series of stack operations,\n# if executed upon an initially empty stack?\n# push(5), push(3), pop(), push(2), push(8), pop(), pop(), push(9),\n# push(1), pop(), push(7), push(6), pop(), pop(), push(4), pop(), pop().\n\n\nclass Emptiness(Exception):\n    pass\n\n\nclass Stack:\n    def __init__(self):\n        self.items = []\n\n    def push(self, item):\n        self.items.append(item)\n\n    def pop(self):\n        if self.is_empty():\n            raise Emptiness('The Stack is empty')\n\n        return self.items.pop()\n\n    def is_empty(self):\n        return self.size() == 0\n\n    def top(self):\n        if self.is_empty():\n            raise Emptiness('The Stack is empty')\n\n        return self.items[-1]\n\n    def size(self):\n        return len(self.items)\n\n\nstack = Stack()\nstack.push(5)  # [5]\nstack.push(3)  # [5, 3]\nstack.pop()  # [5] (removed 3)\nstack.push(2)  # [5, 2]\nstack.push(8)  # [5, 2, 8]\nstack.pop()  # [5, 2] (removed 8)\nstack.pop()  # [5] (removed 2)\nstack.push(9)  # [5, 9]\nstack.push(1)  # [5, 9, 1]\nstack.pop()  # [5, 9] (removed 1)\nstack.push(7)  # [5, 9, 7]\nstack.push(6)  # [5, 9, 7, 6]\nstack.pop()  # [5, 9, 7] (removed 6)\nstack.pop()  # [5, 9] (removed 7)\nstack.push(4)  # [5, 9, 4]\nstack.pop()  # [5, 9] (removed 4)\nstack.pop()  # [5] (removed 9)\n"
  },
  {
    "path": "coding_interviews/algorithms_in_python/stack/R-6.3.py",
    "content": "# R-6.3 from the Algorithms in Pytho book\n# Implement a function with signature transfer(S, T) that transfers all elements\n# from stack S onto stack T, so that the element that starts at the top of S is\n# the first to be inserted onto T, and the element at the bottom of S ends up at the top of T.\n\n\nclass Emptiness(Exception):\n    pass\n\n\nclass Stack:\n    def __init__(self):\n        self.items = []\n\n    def push(self, item):\n        self.items.append(item)\n\n    def pop(self):\n        if self.is_empty():\n            raise Emptiness('The Stack is empty')\n\n        return self.items.pop()\n\n    def is_empty(self):\n        return self.size() == 0\n\n    def top(self):\n        if self.is_empty():\n            raise Emptiness('The Stack is empty')\n\n        return self.items[-1]\n\n    def size(self):\n        return len(self.items)\n\n\ndef transfer(S, T):\n    while not S.is_empty():\n        popped_item = S.pop()\n        T.push(popped_item)\n\n    return T\n\n\nS = Stack()\nT = Stack()\n\nS.push(1)\nS.push(2)\nS.push(3)\nS.push(4)\nS.push(5)\n\nnew_T = transfer(S, T)\n\nprint(new_T.items)  # [5, 4, 3, 2, 1]\n"
  },
  {
    "path": "coding_interviews/algorithms_in_python/stack/R-6.4.py",
    "content": "# R-6.4 from the Algorithms in Pytho book\n# Give a recursive method for removing all the elements from a stack.\n\n\nclass Emptiness(Exception):\n    pass\n\n\nclass Stack:\n    def __init__(self):\n        self.items = []\n\n    def push(self, item):\n        self.items.append(item)\n\n    def pop(self):\n        if self.is_empty():\n            raise Emptiness('The Stack is empty')\n\n        return self.items.pop()\n\n    def is_empty(self):\n        return self.size() == 0\n\n    def top(self):\n        if self.is_empty():\n            raise Emptiness('The Stack is empty')\n\n        return self.items[-1]\n\n    def size(self):\n        return len(self.items)\n\n\ndef remove_all(stack):\n    if stack.is_empty():\n        return stack\n\n    stack.pop()\n\n    return remove_all(stack)\n\n\nstack = Stack()\nstack.push(1)\nstack.push(2)\nstack.push(3)\nstack.push(4)\nstack.push(5)\n\nnew_stack = remove_all(stack)\nprint(new_stack.items)  # []\n"
  },
  {
    "path": "coding_interviews/algorithms_in_python/stack/R-6.5.py",
    "content": "# R-6.5 from the Algorithms in Pytho book\n# Implement a function that reverses a list of elements by pushing them onto\n# a stack in one order, and writing them back to the list in reversed order.\n\n\nclass Emptiness(Exception):\n    pass\n\n\nclass Stack:\n    def __init__(self):\n        self.items = []\n\n    def push(self, item):\n        self.items.append(item)\n\n    def pop(self):\n        if self.is_empty():\n            raise Emptiness('The Stack is empty')\n\n        return self.items.pop()\n\n    def is_empty(self):\n        return self.size() == 0\n\n    def top(self):\n        if self.is_empty():\n            raise Emptiness('The Stack is empty')\n\n        return self.items[-1]\n\n    def size(self):\n        return len(self.items)\n\n\ndef reverse(items):\n    stack = Stack()\n\n    for item in items:\n        stack.push(item)\n\n    new_items = []\n\n    while not stack.is_empty():\n        popped_item = stack.pop()\n        new_items.append(popped_item)\n\n    return new_items\n\n\nitems = [1, 2, 3, 4, 5]\n\nnew_items = reverse(items)\nprint(new_items)\n"
  },
  {
    "path": "coding_interviews/blind75/README.md",
    "content": "<samp>\n\n# Blind 75 LeetCode Questions\n\n## Array\n\n- [x] [Two Sum](https://leetcode.com/problems/two-sum): [Solution](/coding_interviews/leetcode/easy/two-sum/two-sum.js)\n- [ ] [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock)\n- [x] [Contains Duplicate](https://leetcode.com/problems/contains-duplicate): [Solution 1](/coding_interviews/leetcode/easy/contains-duplicate/contains-duplicate.js) & [Solution 2](/coding_interviews/leetcode/easy/contains-duplicate/contains-duplicate-hashmap.js)\n- [x] [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self): [Solution](/coding_interviews/leetcode/medium/product-of-array-except-self/product-of-array-except-self.js)\n- [x] [Maximum Subarray](https://leetcode.com/problems/maximum-subarray): [Solution](/coding_interviews/leetcode/easy/maximum-subarray/maximum-subarray.js)\n- [ ] [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray)\n- [ ] [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array)\n- [ ] [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array)\n- [ ] [3Sum](https://leetcode.com/problems/3sum)\n- [ ] [Container With Most Water](https://leetcode.com/problems/container-with-most-water)\n\n## Binary\n\n- [ ] [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers)\n- [ ] [Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits)\n- [ ] [Counting Bits](https://leetcode.com/problems/counting-bits)\n- [ ] [Missing Number](https://leetcode.com/problems/missing-number)\n- [ ] [Reverse Bits](https://leetcode.com/problems/reverse-bits)\n\n## Dynamic Programming\n\n- [x] [Climbing Stairs](https://leetcode.com/problems/climbing-stairs): [Solution](/coding_interviews/leetcode/easy/climbing-stairs/climbing-stairs.js)\n- [ ] [Coin Change](https://leetcode.com/problems/coin-change)\n- [ ] [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence)\n- [ ] [Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence)\n- [ ] [Word Break Problem](https://leetcode.com/problems/word-break)\n- [ ] [Combination Sum](https://leetcode.com/problems/combination-sum-iv)\n- [ ] [House Robber](https://leetcode.com/problems/house-robber)\n- [ ] [House Robber II](https://leetcode.com/problems/house-robber-ii)\n- [ ] [Decode Ways](https://leetcode.com/problems/decode-ways)\n- [ ] [Unique Paths](https://leetcode.com/problems/unique-paths)\n- [ ] [Jump Game](https://leetcode.com/problems/jump-game)\n\n## Graph\n\n- [x] [Clone Graph](https://leetcode.com/problems/clone-graph): [Solution](https://github.com/imteekay/algorithms/blob/master/coding_interviews/leetcode/medium/clone-graph/clone-graph.js)\n- [ ] [Course Schedule](https://leetcode.com/problems/course-schedule)\n- [ ] [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow)\n- [x] [Number of Islands](https://leetcode.com/problems/number-of-islands): [Solution](/coding_interviews/leetcode/medium/number-of-islands/number-of-islands.js)\n- [ ] [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence)\n\n## Interval\n\n- [ ] [Insert Interval](https://leetcode.com/problems/insert-interval)\n- [ ] [Merge Intervals](https://leetcode.com/problems/merge-intervals)\n- [ ] [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals)\n\n## Linked List\n\n- [x] [Reverse a Linked List](https://leetcode.com/problems/reverse-linked-list): [Solution](/coding_interviews/leetcode/easy/reverse-linked-list/reverse-linked-list.js)\n- [ ] [Detect Cycle in a Linked List](https://leetcode.com/problems/linked-list-cycle)\n- [ ] [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists): [Solution](/coding_interviews/leetcode/easy/merge-two-sorted-lists/merge-two-sorted-lists.js)\n- [ ] [Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists)\n- [ ] [Remove Nth Node From End Of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list): [Solution 1](/coding_interviews/leetcode/medium/remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.js) & [Solution 2](/coding_interviews/leetcode/medium/remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list-fast-slow.js)\n- [ ] [Reorder List](https://leetcode.com/problems/reorder-list)\n\n## Matrix\n\n- [x] [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes): [Solution](/coding_interviews/leetcode/medium/set-matrix-zeroes/set-matrix-zeroes.js)\n- [ ] [Spiral Matrix](https://leetcode.com/problems/spiral-matrix)\n- [x] [Rotate Image](https://leetcode.com/problems/rotate-image): [Solution](/coding_interviews/leetcode/medium/rotate-image/rotate-image.js)\n- [ ] [Word Search](https://leetcode.com/problems/word-search)\n\n## String\n\n- [x] [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters): [Solution](/coding_interviews/leetcode/medium/longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.js)\n- [ ] [Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement)\n- [ ] [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring)\n- [x] [Valid Anagram](https://leetcode.com/problems/valid-anagram): [Solution](/coding_interviews/leetcode/easy/valid-anagram/valid-anagram.js)\n- [x] [Group Anagrams](https://leetcode.com/problems/group-anagrams): [Solution](/coding_interviews/leetcode/medium/group-anagrams/group-anagrams.js)\n- [x] [Valid Parentheses](https://leetcode.com/problems/valid-parentheses): [Solution](/coding_interviews/leetcode/easy/valid-parentheses/valid-parentheses.js)\n- [x] [Valid Palindrome](https://leetcode.com/problems/valid-palindrome): [Solution](/coding_interviews/leetcode/easy/valid-palindrome/valid-palindrome.js)\n- [ ] [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring)\n- [ ] [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings)\n\n## Tree\n\n- [x] [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree): [Solution 1](/coding_interviews/leetcode/easy/maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.js) & [Solution 2](/coding_interviews/leetcode/easy/maximum-depth-of-binary-tree/maximum-depth-of-binary-tree-2.js)\n- [x] [Same Tree](https://leetcode.com/problems/same-tree): [Solution](/coding_interviews/leetcode/easy/same-tree/same-tree.js)\n- [x] [Invert/Flip Binary Tree](https://leetcode.com/problems/invert-binary-tree): [Solution](/coding_interviews/leetcode/easy/invert-binary-tree/invert-binary-tree.js)\n- [ ] [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum)\n- [x] [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal): [Solution](/coding_interviews/leetcode/medium/binary-tree-level-order-traversal/binary-tree-level-order-traversal.js)\n- [ ] [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree)\n- [x] [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree): [Solution](/coding_interviews/leetcode/easy/subtree-of-another-tree/subtree-of-another-tree.js)\n- [ ] [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal)\n- [x] [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree): [Solution 1](/coding_interviews/leetcode/medium/validate-binary-search-tree/validate-binary-search-tree-2.js) & [Solution 2](/coding_interviews/leetcode/medium/validate-binary-search-tree/validate-binary-search-tree.js)\n- [x] [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst): [Solution 1](/coding_interviews/leetcode/medium/kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst-1.js) & [Solution 2](/coding_interviews/leetcode/medium/kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst-2.js)\n- [x] [Lowest Common Ancestor of BST](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree): [Solution](/coding_interviews/leetcode/easy/lowest-common-ancestor-of-a-binary-search-tree/lowest-common-ancestor-of-a-binary-search-tree.js)\n- [ ] [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree)\n- [ ] [Add and Search Word](https://leetcode.com/problems/add-and-search-word-data-structure-design)\n- [ ] [Word Search II](https://leetcode.com/problems/word-search-ii)\n\n## Heap\n\n- [ ] [Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists)\n- [ ] [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements)\n- [ ] [Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream)\n\n## Important Link:\n\n[14 Patterns to Ace Any Coding Interview Question](https://hackernoon.com/14-patterns-to-ace-any-coding-interview-question-c5bb3357f6ed)\n\n</samp>\n"
  },
  {
    "path": "coding_interviews/coding_interview_questions/common_elements.py",
    "content": "def common_elements(list1, list2):\n    result = []\n    elements = {}\n\n    for item in list1:\n        elements[item] = 1\n\n    for item in list2:\n        if item in elements:\n            result.append(item)\n\n    return result\n\n\n# common_elements(list_a1, list_a2) should return [1, 4, 9] (a list).\nlist_a1 = [1, 3, 4, 6, 7, 9]\nlist_a2 = [1, 2, 4, 5, 9, 10]\nprint(common_elements(list_a1, list_a2))\n\n# common_elements(list_b1, list_b2) should return [1, 2, 9, 10, 12] (a list).\nlist_b1 = [1, 2, 9, 10, 11, 12]\nlist_b2 = [0, 1, 2, 3, 4, 5, 8, 9, 10, 12, 14, 15]\nprint(common_elements(list_b1, list_b2))\n\n# common_elements(list_b1, list_b2) should return [] (an empty list).\nlist_c1 = [0, 1, 2, 3, 4, 5]\nlist_c2 = [6, 7, 8, 9, 10, 11]\nprint(common_elements(list_c1, list_c2))\n"
  },
  {
    "path": "coding_interviews/coding_interview_questions/decode-string/decode-string.js",
    "content": "const isNum = (char) => !isNaN(Number(char));\n\nexport function decodeString(encodedString) {\n  const stack = [];\n  let index = 0;\n\n  while (index < encodedString.length) {\n    const char = encodedString[index];\n\n    if (isNum(char)) {\n      const number = [];\n\n      while (isNum(encodedString[index])) {\n        number.push(encodedString[index]);\n        index++;\n      }\n\n      stack.push(Number(number.join('')));\n      continue;\n    }\n\n    if (char === ']') {\n      let str = '';\n\n      while (stack[stack.length - 1] !== '[') {\n        str = stack.pop() + str;\n      }\n\n      stack.pop();\n      stack.push(str.repeat(stack.pop()));\n      index++;\n      continue;\n    }\n\n    stack.push(char);\n    index++;\n  }\n\n  return stack.join('');\n}\n"
  },
  {
    "path": "coding_interviews/coding_interview_questions/decode-string/tests/decode-string.test.js",
    "content": "import { describe, it, expect } from 'vitest';\nimport { decodeString } from '../decode-string';\n\ndescribe('decodeString', () => {\n  it('', () => {\n    expect(decodeString('3[a]2[bc]')).toEqual('aaabcbc');\n  });\n\n  it('', () => {\n    expect(decodeString('2[abc]3[cd]ef')).toEqual('abcabccdcdcdef');\n  });\n\n  it('', () => {\n    expect(decodeString('3[a2[c]]')).toEqual('accaccacc');\n  });\n\n  it('', () => {\n    expect(decodeString('100[leetcode]')).toEqual(\n      'leetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcode'\n    );\n  });\n});\n"
  },
  {
    "path": "coding_interviews/coding_interview_questions/mine_swipper.py",
    "content": "# [[0, 0], [0, 1]], 3, 4\n# => [\n#     [-1, -1, 1, 0],\n#     [2, 2, 1, 0],\n#     [0, 0, 0, 0]\n#   ]\n\ndef update_table_spot(table, row, col, num_rows, num_cols):\n    table_with_border = table\n    border = []\n\n    for row in range(num_rows):\n        table_with_border[row].insert(0, 0)\n        table_with_border[row].insert(num_cols+1, 0)\n\n    for i in range(num_cols+2):\n        border.append(0)\n\n    table_with_border.insert(0, border)\n    table_with_border.insert(num_rows+1, border)\n\n    number_of_bomb_neighboors = 0\n\n    for i in range(num_rows):\n        for j in range(num_cols):\n            print(table[i][j], end='')\n\n        print()\n    print()\n\n    if table_with_border[row-1][col-1] == -1: number_of_bomb_neighboors += 1\n    if table_with_border[row-1][col] == -1: number_of_bomb_neighboors += 1\n    if table_with_border[row-1][col+1] == -1: number_of_bomb_neighboors += 1\n    if table_with_border[row][col-1] == -1: number_of_bomb_neighboors += 1\n    if table_with_border[row][col+1] == -1: number_of_bomb_neighboors += 1\n    if table_with_border[row+1][col-1] == -1: number_of_bomb_neighboors += 1\n    if table_with_border[row+1][col] == -1: number_of_bomb_neighboors += 1\n    if table_with_border[row+1][col+1] == -1: number_of_bomb_neighboors += 1\n\n    table[row][col] = number_of_bomb_neighboors\n    return table\n\ndef mine_swipper(bombs, num_rows, num_cols):\n    table = []\n\n    for row in range(num_rows):\n        filled_row = []\n\n        for col in range(num_cols):\n            filled_row.append(0)\n\n        table.append(filled_row)\n\n    for bomb in bombs:\n        table[bomb[0]][bomb[1]] = -1\n\n    for row in range(num_rows):\n        for col in range(num_cols):\n            if table[row][col] == 0:\n                table = update_table_spot(table, row, col, num_rows, num_cols)\n\n    for i in range(num_rows):\n        for j in range(num_cols):\n            print(table[i][j], end='')\n\n        print()\n\nmine_swipper([[0, 0], [0, 1]], 3, 4)\n"
  },
  {
    "path": "coding_interviews/coding_interview_questions/most_frequently_occurring.py",
    "content": "def most_frequent(given_list):\n    max_item = 0\n    result = 0\n\n    if not given_list:\n        return None\n\n    frequencies = {}\n\n    for item in given_list:\n        if item in frequencies:\n            frequencies[item] += 1\n        else:\n            frequencies[item] = 1\n\n        if frequencies[item] > max_item:\n            result = item\n            max_item = frequencies[item]\n\n    return result\n\n# most_frequent(list1) should return 1\nlist1 = [1, 3, 1, 3, 2, 1]\nprint(most_frequent(list1))\n\n# most_frequent(list2) should return 3\nlist2 = [3, 3, 1, 3, 2, 1]\nprint(most_frequent(list2))\n\n# most_frequent(list3) should return None\nlist3 = []\nprint(most_frequent(list3))\n\n# most_frequent(list4) should return 0\nlist4 = [0]\nprint(most_frequent(list4))\n\n# most_frequent(list5) should return -1\nlist5 = [0, -1, 10, 10, -1, 10, -1, -1, -1, 1]\nprint(most_frequent(list5))\n"
  },
  {
    "path": "coding_interviews/coding_interview_questions/non_repeating.py",
    "content": "# 'aabcb' --> 'c'\n# 'xxyz' --> 'y'\n# '' --> None\n# 'aabb' --> None\n# 'abcab' --> 'c'\n# 'abab' --> None\n# 'aabbbc' --> 'c'\n# 'aabbdbc' --> 'd'\n\ndef non_repeating(string):\n    counter_mapping = {}\n\n    for char in string:\n        if char in counter_mapping:\n            counter_mapping[char] += 1\n        else:\n            counter_mapping[char] = 1\n\n    for char, counter in counter_mapping.items():\n        if counter == 1:\n            return char\n\n    return None\n\nprint(non_repeating('aabcb'))\nprint(non_repeating('xxyz'))\nprint(non_repeating(''))\nprint(non_repeating('aabb'))\nprint(non_repeating(\"abcab\"))\nprint(non_repeating(\"abab\"))\nprint(non_repeating(\"aabbbc\"))\nprint(non_repeating(\"aabbdbc\"))\n"
  },
  {
    "path": "coding_interviews/coding_interview_questions/nth_element_from_the_end.py",
    "content": "# Use this class to create linked lists.\nclass Node:\n    def __init__(self, value, next=None):\n        self.value = value\n        self.next = next\n\n    def __str__(self):\n        return str(self.value)\n\ndef nth_from_last(head, n):\n    if head is None or n < 0:\n        return\n\n    elements = []\n    current_node = head\n\n    while current_node:\n        elements.append(current_node.value)\n        current_node = current_node.next\n\n    if n > len(elements):\n        return None\n    else:\n        return elements[len(elements) - n]\n\n# Testing Linked List function\ndef linked_list_to_string(head):\n    current = head\n    str_list = []\n\n    while current:\n        str_list.append(str(current.value))\n        current = current.next\n\n    return ' -> '.join(str_list.append('(None)'))\n\ncurrent = Node(1)\nfor i in range(2, 8):\n    current = Node(i, current)\nhead = current\n# head = 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> (None)\n\ncurrent2 = Node(4)\nfor i in range(3, 0, -1):\n    current2 = Node(i, current2)\nhead2 = current2\n# head2 = 1 -> 2 -> 3 -> 4 -> (None)\n\nprint('nth_from_last(head, 1) should return 1.')\nprint(nth_from_last(head, 1))\nprint('nth_from_last(head, 5) should return 5.')\nprint(nth_from_last(head, 5))\nprint('nth_from_last(head2, 2) should return 3.')\nprint(nth_from_last(head2, 2))\nprint('nth_from_last(head2, 4) should return 1.')\nprint(nth_from_last(head2, 4))\nprint('nth_from_last(head2, 5) should return None.')\nprint(nth_from_last(head2, 5))\nprint('nth_from_last(None, 1) should return None.')\nprint(nth_from_last(None, 1))\n"
  },
  {
    "path": "coding_interviews/coding_interview_questions/one_away_strings.py",
    "content": "# 'abcde'\n# 'abfde'\n# => True\n\n# 'abcde'\n# 'abde'\n# => True\n\n# 'abde'\n# 'abfde'\n# => True\n\ndef handle_different_sized_strings(s1, s2):\n    indice1, indice2, number_of_differences = 0, 0, 0\n\n    while indice2 < len(s2):\n        if number_of_differences > 1:\n            return False\n\n        if s1[indice1] != s2[indice2]:\n            number_of_differences += 1\n            indice1 += 1\n\n        indice1 += 1\n        indice2 += 1\n\n    return True\n\ndef handle_same_sized_strings(s1, s2):\n    number_of_differences = 0\n\n    for indice in range(len(s1)):\n        if s1[indice] != s2[indice]:\n            number_of_differences += 1\n\n    return number_of_differences == 1\n\ndef is_one_away(s1, s2):\n    if len(s1) - len(s2) > 1 or len(s2) - len(s1) > 1:\n        return False\n\n    if s1 == s2:\n        return True\n\n    if len(s1) > len(s2):\n        return handle_different_sized_strings(s1, s2)\n\n    if len(s2) > len(s1):\n        return handle_different_sized_strings(s2, s1)\n\n    if len(s1) == len(s2):\n        return handle_same_sized_strings(s1, s2)\n\nprint(is_one_away('abcde', 'abfde'))\nprint(is_one_away('abcde', 'abde'))\nprint(is_one_away('abde', 'abfde'))\nprint(is_one_away('', ''))\nprint(is_one_away('', 'a'))\nprint(is_one_away('a', ''))\nprint(is_one_away('aabb', 'aacc'))\n\nprint()\n\nprint(is_one_away(\"abcde\", \"abcd\"))  # should return True\nprint(is_one_away(\"abde\", \"abcde\"))  # should return True\nprint(is_one_away(\"a\", \"a\"))  # should return True\nprint(is_one_away(\"abcdef\", \"abqdef\"))  # should return True\nprint(is_one_away(\"abcdef\", \"abccef\"))  # should return True\nprint(is_one_away(\"abcdef\", \"abcde\"))  # should return True\nprint(is_one_away(\"aaa\", \"abc\"))  # should return False\nprint(is_one_away(\"abcde\", \"abc\"))  # should return False\nprint(is_one_away(\"abc\", \"abcde\"))  # should return False\nprint(is_one_away(\"abc\", \"bcc\"))  # should return False\n"
  },
  {
    "path": "coding_interviews/coding_interview_questions/optimized_common_elements.py",
    "content": "def common_elements(list1, list2):\n    result = []\n    point1 = 0\n    point2 = 0\n\n    while point1 < len(list1) and point2 < len(list2):\n        if list1[point1] == list2[point2]:\n            result.append(list1[point1])\n            point1 += 1\n            point2 += 1\n        elif list1[point1] > list2[point2]:\n            point2 += 1\n        else:\n            point1 += 1\n\n    return result\n\n\n# common_elements(list_a1, list_a2) should return [1, 4, 9] (a list).\nlist_a1 = [1, 3, 4, 6, 7, 9]\nlist_a2 = [1, 2, 4, 5, 9, 10]\nprint(common_elements(list_a1, list_a2))\n\n# common_elements(list_b1, list_b2) should return [1, 2, 9, 10, 12] (a list).\nlist_b1 = [1, 2, 9, 10, 11, 12]\nlist_b2 = [0, 1, 2, 3, 4, 5, 8, 9, 10, 12, 14, 15]\nprint(common_elements(list_b1, list_b2))\n\n# common_elements(list_b1, list_b2) should return [] (an empty list).\nlist_c1 = [0, 1, 2, 3, 4, 5]\nlist_c2 = [6, 7, 8, 9, 10, 11]\nprint(common_elements(list_c1, list_c2))\n"
  },
  {
    "path": "coding_interviews/coding_interview_questions/rotation_array.py",
    "content": "# both arrays are the same size? => true\n# is A and B is equal, is A a rotation of B? => false\n# is both array is empty, one is a rotation of another? => true\n\n# [1, 2, 3, 4, 5, 6, 7]\n# [4, 5, 6, 7, 1, 2, 3]\n# True\n\n# [1, 2, 3, 4, 5, 6, 7]\n# [4, 3, 6, 7, 1, 2, 3]\n# False\n\n# []\n# []\n# True\n\ndef is_rotation(a, b):\n    if a == b:\n        return True\n\n    if len(a) != len(b):\n        return False\n\n    for index in range(1, len(b)):\n        if b[index:len(b)] + b[0:index] == a:\n            return True\n\n    return False\n\na = [1, 2, 3, 4, 5, 6, 7]\nb = [4, 5, 6, 7, 1, 2, 3]\nprint(is_rotation(a, b))\n\na = [1, 2, 3, 4, 5, 6, 7]\nb = [4, 3, 6, 7, 1, 2, 3]\nprint(is_rotation(a, b))\n\na = []\nb = []\nprint(is_rotation(a, b))\n"
  },
  {
    "path": "coding_interviews/coding_interview_questions/two-crystal-balls/index.js",
    "content": "export function twoCrystalBalls(breaks) {\n  let jumpAmount = Math.floor(Math.sqrt(breaks.length));\n  let index = jumpAmount;\n\n  for (; index < breaks.length; index += jumpAmount) {\n    if (breaks[index]) break;\n  }\n\n  index -= jumpAmount;\n\n  for (let j = 0; j < jumpAmount && index < breaks.length; index++, j++) {\n    if (breaks[index]) return index;\n  }\n\n  return -1;\n}\n"
  },
  {
    "path": "coding_interviews/coding_interview_questions/two-crystal-balls/tests/index.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { twoCrystalBalls } from '..';\n\ndescribe('twoCrystalBalls', () => {\n  it('', () => {\n    const idx = Math.floor(Math.random() * 10000);\n    const data = new Array(10000).fill(false);\n\n    for (let i = idx; i < 10000; ++i) {\n      data[i] = true;\n    }\n\n    expect(twoCrystalBalls(data)).toEqual(idx);\n    expect(twoCrystalBalls(new Array(821).fill(false))).toEqual(-1);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/README.md",
    "content": "# Cracking the Coding Interview\n\n## Chapter 001: Arrays and Strings\n\n- [1.1 Is Unique](./chapter-001/is-unique)\n- [1.2 Check Permutation](./chapter-001/check-permutation)\n- [1.3 URLlify](./chapter-001/urlify)\n- [1.4 Palindrome Permutation](./chapter-001/palindrome-permutation)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/aditional1.py",
    "content": "def product(a, b):\n    sum = 0\n    for i in range(b):\n        sum += a\n\n    return sum\n\nprint(product(2, 4))\n\n# Complexity: O(b) | O(N)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/aditional2.py",
    "content": "def power(a, b):\n    if b < 0:\n        return 0\n    elif b == 0:\n        return 1\n    else:\n        return a * power(a, b - 1)\n\nprint(power(2, 2))\nprint(power(2, 10))\nprint(power(3, 2))\n\n# Complexity: O(B)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/aditional3.py",
    "content": "def mod(a, b):\n    if b > a:\n        return a\n\n    return mod(a - b, b)\n\nprint(mod(10, 2))\nprint(mod(10, 3))\nprint(mod(10, 4))\nprint(mod(10, 5))\nprint(mod(10, 6))\n\n# Complexity: O(a / b)\n\ndef mod(a, b):\n    if b <= 0:\n        return -1\n\n    div = a / b\n    return a - div * b\n\n# Complexity: O(1)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/aditional4.py",
    "content": "def div(a, b):\n    count = 0\n    sum = b\n\n    while sum <= a:\n        sum += b\n        count += 1\n\n    return count\n\nprint(div(10, 5))\nprint(div(10, 2))\nprint(div(10, 3))\nprint(div(10, 11))\n\n# Complexity: O(a / b)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/aditional5.py",
    "content": "def sqrt(n):\n    return sqrt_helper(n, 1, n)\n\ndef sqrt_helper(n, min, max):\n    if min > max:\n        return -1\n\n    guess = (min + max) / 2\n\n    if guess * guess > n:\n        return sqrt_helper(n, min, guess - 1)\n    elif guess * guess < n:\n        return sqrt_helper(n, guess + 1, max)\n    else:\n        return guess\n\nprint(sqrt(100))\nprint(sqrt(9))\nprint(sqrt(25))\nprint(sqrt(3))\n\n# Complexity: O(log N) --> It is a binary search algorithm\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/aditional6.py",
    "content": "from math import sqrt\n\ndef square_root(n):\n    for guess in range(int(sqrt(n))+1):\n        if guess * guess == n:\n            return guess\n\n    return -1\n\nprint(square_root(100))\nprint(square_root(9))\nprint(square_root(25))\nprint(square_root(3))\n\n# Complexity: O(log N) --> It is a binary search algorithm\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/example1.py",
    "content": "def foo(array):\n    sum = 0\n    product = 1\n\n    for element in array:\n        sum += element\n\n    for element in array:\n        product *= element\n\n    print(\"%d, %d\" %(sum, product))\n\nfoo([1, 2, 3, 4, 5])\n\n# The complexity of the foo function is: O(N)\n# Initializing sum and product = 1 + 1 = 2\n# We iterate through the array two times = 2 * length(array) = 2 * N\n# Printing sum and product = 1\n# Conclusion: O(2N + 3) = O(N)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/example10.py",
    "content": "from math import sqrt\n\ndef is_prime(num):\n    if num < 2:\n        return False\n\n    if num == 2:\n        return True\n\n    if num % 2 == 0:\n        return False\n\n    for i in range(3, int(sqrt(num)) + 1, 2):\n        if num % i == 0:\n            return False\n\n    return True\n\nprint(is_prime(1)) # False\nprint(is_prime(2)) # True\nprint(is_prime(9)) # False\nprint(is_prime(17)) # True\nprint(is_prime(24)) # False\n\n# is prime function has complexity of O(sqrt(N))\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/example11.py",
    "content": "def factorial(n):\n    if n < 0:\n        return -1\n\n    if n == 0:\n        return 1\n\n    return n * factorial(n - 1)\n\n# factorial function has a complexity of O(N)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/example12.py",
    "content": "def permutation(str):\n    handle_permutation(str, \"\")\n\ndef handle_permutation(str, prefix):\n    if len(str) == 0:\n        print(prefix)\n    else:\n        for i in range(len(str)):\n            rem = str[0:i] + str[i+1:]\n            handle_permutation(rem, prefix + str[i])\n\npermutation('abc')\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/example13.py",
    "content": "def fib(n):\n    if n == 0:\n        return 0\n\n    if n == 1:\n        return 1\n\n    return fib(n - 1) + fib(n - 2)\n\nprint(fib(1))\nprint(fib(4))\nprint(fib(5))\nprint(fib(10))\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/example14.py",
    "content": "def all_fib(n):\n    for i in range(n):\n        print(fib(i))\n\ndef fib(n):\n    if n == 0:\n        return 0\n\n    if n == 1:\n        return 1\n\n    return fib(n - 1) + fib(n - 2)\n\nall_fib(10)\n\n# Complexity: O(2 ^ (n+1))\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/example15.py",
    "content": "def all_fib(n):\n    memo = []\n    memo.append(0)\n    memo.append(1)\n\n    for i in range(n):\n        print(\"%d: %d\" %(i, fib(i, memo)))\n\ndef fib(n, memo):\n    if n <= len(memo) - 1:\n        return memo[n]\n\n    memo.append(fib(n - 1, memo) + fib(n - 2, memo))\n    return memo[n]\n\nall_fib(7)\n\n# Complexity: O(N)\n# All previous actions are already computed\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/example16.py",
    "content": "def powers_of_2(n):\n    if n <= 0:\n        return 0\n\n    if n == 1:\n        print(1)\n        return 1\n\n    previous = powers_of_2(n / 2)\n    current = previous * 2\n    print(current)\n    return current\n\npowers_of_2(4)\n\n# Complexity: O(log N)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/example2.py",
    "content": "def print_pairs(array):\n    for i in array:\n        for j in array:\n            print(\"%d, %d\" %(i, j))\n\nprint_pairs([1, 2, 3, 4, 5])\n\n# The complexity of the print_pairs function is: O(N^2)\n# We do a nested loop = length(array) ^ 2 = N * 2\n# There are O(N^2) pairs\n# Conclusion: O(N^2)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/example3.py",
    "content": "def print_unordered_pairs(array):\n    for i in range(len(array)):\n        for j in range(i+1, len(array)):\n            print(\"%d, %d\" %(array[i], array[j]))\n\nprint_unordered_pairs([1, 2, 3, 4, 5])\n\n# The complexity of the print_unordered_pairs function is: O(N^2)\n# We do a nested loop = length(array) * (length(array) - 1) / 2 = (length(array) * 2 - length(array)) / 2 = (N^2 - N) / 2\n# There are O((N^2 - N) / 2) pairs\n# Conclusion: O(N^2)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/example4.py",
    "content": "def print_unordered_pairs(array_a, array_b):\n    for a in array_a:\n        for b in array_b:\n            if a < b:\n                print('%d, %d' %(a, b))\n\nprint_unordered_pairs([1, 2, 3, 4, 5], [3, 1, 2, 5, 4])\n\n# The complexity of the print_unordered_pairs function is: O(N^2)\n# We do a nested loop = length(array_a) * length(array_b) = N^2\n# There are O(N^2) pairs\n# Conclusion: O(N^2)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/example5.py",
    "content": "def print_unordered_pairs(array_a, array_b):\n    for a in array_a:\n        for b in array_b:\n            for i in range(1000000):\n                print('%d, %d' %(a, b))\n\nprint_unordered_pairs([1, 2, 3, 4, 5], [3, 1, 2, 5, 4])\n\n# The complexity of the print_unordered_pairs function is: O(N^2)\n# We do a nested loop = length(array_a) * length(array_b) * 1000000 = N^2 * 1000000\n# There are O(N^2 * 1000000) pairs\n# Conclusion: O(N^2)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/example6.py",
    "content": "def reverse(array):\n    for i in range(len(array) / 2):\n        index = len(array) - i - 1\n        temporary_num = array[index]\n        array[index] = array[i]\n        array[i] = temporary_num\n\n    return array\n\nnew_array = reverse(list(range(1, 6))\n\nfor i in new_array:\n    print(i)\n\n# The complexity of the reverse function is: O(N)\n# Even though we iterate only through half of the array (O(N/2)), we still consider this a O(N) complexity\n# Conclusion: O(N)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/example7.py",
    "content": "# O(N + P), if P < N / 2 --> O(N)\n# O(2N) --> O(N)\n# O(N + logN) --> O(N)\n# O(N + M), if N > M then O(N), otherwise O(M)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/big_o/example9.py",
    "content": "def sum(node):\n    if node is None:\n        return 0\n\n    return sum(node.left) + node.value + sum(node.right)\n\n# If we have N nodes in our tree, this will be O(N) complexity\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/check-permutation/check-permutation.js",
    "content": "// Given two strings, write a method to decide if one is a permutation of the other\n\n// If they have different lengths, they are not permutations\n// Build a hashmap of characters of one of the strings\n// Iterate through the other string and check if the characters are in the hashmap\n// If there's no match in the hashmap, they are not permutations\n// If it passes the loop, they are permutations.\n// Runtime Complexity: O(N), where N = the length of the string\n// Space Complexity: O(N), where N = the length of the string\n\nfunction buildCharsMap(string) {\n  const charsMap = new Map();\n\n  for (let char of string) {\n    if (charsMap.has(char)) charsMap.set(char, charsMap.get(char) + 1);\n    else charsMap.set(char, 1);\n  }\n\n  return charsMap;\n}\n\nexport function checkPermutation(s1, s2) {\n  if (s1.length !== s2.length) return false;\n  const charsMap = buildCharsMap(s1);\n\n  for (let char of s2) {\n    if (!charsMap.has(char)) {\n      return false;\n    }\n\n    if (charsMap.get(char) === 0) {\n      return false;\n    }\n\n    charsMap.set(char, charsMap.get(char) - 1);\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/check-permutation/check-permutation.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { checkPermutation } from './check-permutation';\n\ndescribe('checkPermutation', () => {\n  it('returns the correct results', () => {\n    expect(checkPermutation('aba', 'aab')).toBeTruthy();\n  });\n\n  it('returns the correct results', () => {\n    expect(checkPermutation('aba', 'aaba')).toBeFalsy();\n  });\n\n  it('returns the correct results', () => {\n    expect(checkPermutation('aba', 'aa')).toBeFalsy();\n  });\n});\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/cpp/remove_specified_character.cpp",
    "content": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n\tstring word, characteres, result = \"\";\n\n\tgetline(cin, word);\n\tcin >> characteres;\n\n\tfor (int i = 0; i < word.size(); i++) {\n\t\tint belongs_to = 0;\n\n\t\tfor (int j = 0; j < characteres.size(); j++) {\n\t\t\tif (word[i] == characteres[j]) {\n\t\t\t\tbelongs_to = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!belongs_to) result += word[i];\n\t}\n\n\tcout << result << endl;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/is-unique/is-unique.js",
    "content": "// Is Unique: Implement an algorithm to determine if a string has all unique characters.\n\n// Using a hashmap to count the number of characters in the string\n// if there's already a character, it should return false as a result\n// if it passes the entire string, it means it's a string with unique characters\n// Time Complexity: O(N), N = number of charactes in the string\n// Space Complexity: O(N), N = number of charactes in the string stored in the `charMap` hashmap\nexport function isUnique(string) {\n  const charMap = new Map();\n\n  for (let char of string) {\n    if (charMap.has(char)) return false;\n    charMap.set(char, 1);\n  }\n\n  return true;\n}\n\n// Using a set to store all unique characters of the string\n// if the size of the set is equal to the string, the string has unique characters\n// Time Complexity: O(N), N = number of charactes in the string\n// Space Complexity: O(N), N = number of charactes in the string stored in the `uniqueChars` set\nexport function isUniqueWithSet(string) {\n  const uniqueChars = new Set();\n\n  for (let char of string) {\n    uniqueChars.add(char);\n  }\n\n  return uniqueChars.size === string.length;\n}\n\n// Using a set to store all unique characters of the string\n// A simplified version using the Set constructor\n// Time Complexity: O(N), N = number of charactes in the string\n// Space Complexity: O(N), N = number of charactes in the string stored in the `uniqueChars` set\nexport function isUniqueWithSetSimplified(string) {\n  return string.length === new Set(string).size;\n}\n\n// --- What if you cannot use additional data structures? ---\n\n// Comparing each character with all the other characters\n// Runtime Complexity: O(N^2)\n// Space Complexity: O(1)\nexport function isUniqueNSquare(string) {\n  for (let i = 0; i < string.length; i++) {\n    for (let j = i + 1; j < string.length; j++) {\n      if (string[i] === string[j]) return false;\n    }\n  }\n\n  return true;\n}\n\n// Sorting and comparing adjacent characters\n// Runtime Complexity: O(NlogN) because of the sorting runtime complexity\n// Space Complexity: O(N) because of the newly created array\nexport function isUniqueWithoutDS(string) {\n  let sortedString = [...string].sort(\n    (a, b) => a.charCodeAt() - b.charCodeAt()\n  );\n\n  for (let index = 0; index < sortedString.length - 1; index++) {\n    if (sortedString[index] === sortedString[index + 1]) return false;\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/is-unique/is-unique.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport {\n  isUnique,\n  isUniqueNSquare,\n  isUniqueWithSet,\n  isUniqueWithSetSimplified,\n  isUniqueWithoutDS,\n} from './is-unique';\n\nconst unique = 'asdfghjkl';\nconst nonUnique = 'asdfghjkla';\n\ndescribe('isUnique', () => {\n  it('returns correct result', () => {\n    expect(isUnique(unique)).toBeTruthy();\n  });\n\n  it('returns false for non-unique characters', () => {\n    expect(isUnique(nonUnique)).toBeFalsy();\n  });\n});\n\ndescribe('isUniqueWithSet', () => {\n  it('returns true for unique characters', () => {\n    expect(isUniqueWithSet(unique)).toBeTruthy();\n  });\n\n  it('returns false for non-unique characters', () => {\n    expect(isUniqueWithSet(nonUnique)).toBeFalsy();\n  });\n});\n\ndescribe('isUniqueWithSetSimplified', () => {\n  it('returns true for unique characters', () => {\n    expect(isUniqueWithSetSimplified(unique)).toBeTruthy();\n  });\n\n  it('returns false for non-unique characters', () => {\n    expect(isUniqueWithSetSimplified(nonUnique)).toBeFalsy();\n  });\n});\n\ndescribe('isUniqueNSquare', () => {\n  it('returns true for unique characters', () => {\n    expect(isUniqueNSquare(unique)).toBeTruthy();\n  });\n\n  it('returns false for non-unique characters', () => {\n    expect(isUniqueNSquare(nonUnique)).toBeFalsy();\n  });\n});\n\ndescribe('isUniqueWithoutDS', () => {\n  it('returns true for unique characters', () => {\n    expect(isUniqueWithoutDS(unique)).toBeTruthy();\n  });\n\n  it('returns false for non-unique characters', () => {\n    expect(isUniqueWithoutDS(nonUnique)).toBeFalsy();\n  });\n});\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/one-away/one-away.js",
    "content": "// One Away: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character.\n// Given two strings, write a function to check if they are one edit (or zero edits) away\n\n// Examples\n// pale, ple -> true\n// pales, pale -> true\n// pale, bale -> true\n// pale, bake -> false\n\n/**\n * pale => {p: 1, a: 1, l: 1, e: 1}\n * ple => {p: 1, l: 1, e: 1}\n * bake => {b: 1, a: 1, k: 1, e: 1}\n */\n\nfunction buildCharsCount(string) {\n  let charsCount = new Map();\n\n  for (let char of string) {\n    if (charsCount.has(char)) charsCount.set(char, charsCount.get(char) + 1);\n    else charsCount.set(char, 1);\n  }\n\n  return charsCount;\n}\n\nexport function oneAway(s1, s2) {\n  if (s1.length - s2.length >= 2) return false;\n  if (s2.length - s1.length >= 2) return false;\n\n  let charsCount1 = buildCharsCount(s1);\n  let charsCount2 = buildCharsCount(s2);\n  let string = charsCount1.size >= charsCount2.size ? s1 : s2;\n  let [map1, map2] =\n    charsCount1.size >= charsCount2.size\n      ? [charsCount1, charsCount2]\n      : [charsCount2, charsCount1];\n  let numberOfEdits = 0;\n\n  for (let char of string) {\n    let count1 = map1.get(char) || 0;\n    let count2 = map2.get(char) || 0;\n    numberOfEdits += count1 - count2;\n  }\n\n  return [0, 1].includes(numberOfEdits);\n}\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/one-away/one-away.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { oneAway } from './one-away';\n\ndescribe('oneAway', () => {\n  it('', () => {\n    expect(oneAway('pale', 'ple')).toEqual(true);\n    expect(oneAway('pale', 'pale')).toEqual(true);\n    expect(oneAway('pales', 'pale')).toEqual(true);\n    expect(oneAway('pale', 'bale')).toEqual(true);\n    expect(oneAway('paalle', 'paklle')).toEqual(true);\n    expect(oneAway('paalle', 'paklle')).toEqual(true);\n    expect(oneAway('1203', '1213')).toEqual(true);\n    expect(oneAway('pale', 'bake')).toEqual(false);\n    expect(oneAway('palee', 'ple')).toEqual(false);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/palindrome-permutation/palindrome-permutation.js",
    "content": "// Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome.\n// A palindrome is a word or phrase that is the same forwards and backwards.\n// A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words.\n// You can ignore casing and non-letter characters.\n// Example:\n// Tact Coa\n//  - taco cat\n//  - atco cta\n\n// Runtime Complexity: O(N), where N = the true length of the string\n// Space Complexity: O(N), where N = the true length of the string in the hashmap\n\nfunction isAlpha(char) {\n  return /[_a-zA-Z]/.test(char);\n}\n\nfunction buildMapOsChars(string) {\n  const charsMap = new Map();\n  const downcasedString = string.toLowerCase();\n\n  for (let char of downcasedString) {\n    if (!isAlpha(char)) continue;\n    if (charsMap.has(char)) charsMap.set(char, charsMap.get(char) + 1);\n    else charsMap.set(char, 1);\n  }\n\n  return charsMap;\n}\n\nexport function palindromePermutation(string) {\n  let charsMap = buildMapOsChars(string);\n  let numberOfCharsWithOneCount = 0;\n\n  for (let [_, count] of charsMap.entries()) {\n    numberOfCharsWithOneCount += count % 2;\n  }\n\n  return numberOfCharsWithOneCount <= 1;\n}\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/palindrome-permutation/palindrome-permutation.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { palindromePermutation } from './palindrome-permutation';\n\ndescribe('palindromePermutation', () => {\n  it('', () => {\n    expect(palindromePermutation('Tact Coa')).toEqual(true);\n  });\n\n  it('', () => {\n    expect(palindromePermutation('tat')).toEqual(true);\n  });\n\n  it('', () => {\n    expect(palindromePermutation('abcd')).toEqual(false);\n  });\n\n  it('', () => {\n    expect(palindromePermutation('tactfcoa')).toEqual(false);\n  });\n\n  it('', () => {\n    expect(palindromePermutation('tactfffcoa')).toEqual(false);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/python/001.01.py",
    "content": "'''\nIs Unique: Implement an algorithm to determine if a string has all unique characters.\nWhat if you cannot use additional data structures?\n\n- Examples:\nabc => True\naaa => False\nabcdefghij => True\nabcdefghia => False\n\nSome questions:\n- Could the string be an empty string?\n- What's the memory constraints?\n'''\n\n# First approach using Hash Map\n\n\ndef all_unique_characters(string):\n    characters_counter = {}\n\n    for char in string:\n        if char in characters_counter:\n            characters_counter[char] += 1\n        else:\n            characters_counter[char] = 1\n\n    for char, counter in characters_counter.items():\n        if counter > 1:\n            return False\n\n    return True\n\n\nprint(all_unique_characters('abc'))\nprint(all_unique_characters('aaa'))\nprint(all_unique_characters('abcdefghij'))\nprint(all_unique_characters('abcdefghia'))\n\n# Second approach using Set\n\n\ndef all_unique_characters(string):\n    unique_chars = set()\n\n    for char in string:\n        unique_chars.add(char)\n\n    return len(unique_chars) == len(string)\n\n\nprint(all_unique_characters('abc'))\nprint(all_unique_characters('aaa'))\nprint(all_unique_characters('abcdefghij'))\nprint(all_unique_characters('abcdefghia'))\n\n'''\nBoth approaches are:\n- Space: O(N)\n- Time: O(N)\n'''\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/python/001.02.py",
    "content": "'''\nCheck Permutation: Given two strings, write a method to decide if one is a\npermutation of the other.\n\n- Examples:\n\"abc\" \"bca\" => True\n\"abc\" \"bca\" => True\n\"abc\" \"aab\" => False\n\"abc\" \"baca\" => False\n\nQuestions:\n- Do the strings have the same length?\n'''\n\n\ndef permutation(str1, str2):\n    if len(str1) != len(str2):\n        return False\n\n    return sorted(str1) == sorted(str2)\n\n\nprint(permutation(\"abc\", \"bca\"))\nprint(permutation(\"abc\", \"bca\"))\nprint(permutation(\"abc\", \"aab\"))\nprint(permutation(\"abc\", \"baca\"))\n\n'''\nThis is:\n- Space: O(1) (no new storage of the string)\n- Time: O(NlogN) (because of the sorting)\n'''\n\n\ndef permutation(str1, str2):\n    if len(str1) != len(str2):\n        return False\n\n    first_set = set()\n    second_set = set()\n\n    for char in str1:\n        first_set.add(char)\n\n    for char in str2:\n        second_set.add(char)\n\n    return first_set == second_set\n\n\nprint(permutation(\"abc\", \"bca\"))\nprint(permutation(\"abc\", \"bca\"))\nprint(permutation(\"abc\", \"aab\"))\nprint(permutation(\"abc\", \"baca\"))\n\n'''\nThis is:\n- Space: O(N) (for each string we have a new set with N places - N is equal to the string length)\n- Time: O(N) (just the str1 and str2 iteration)\n'''\n\n\ndef permutation(str1, str2):\n    if len(str1) != len(str2):\n        return False\n\n    characters = {}\n\n    for char in str1:\n        if char in characters:\n            characters[char] += 1\n        else:\n            characters[char] = 1\n\n    for char in str2:\n        if char not in characters or characters[char] == 0:\n            return False\n\n        characters[char] -= 1\n\n    return True\n\n\nprint(permutation(\"abc\", \"bca\"))\nprint(permutation(\"abc\", \"bca\"))\nprint(permutation(\"abc\", \"aab\"))\nprint(permutation(\"abc\", \"baca\"))\n\n'''\nThis is:\n- Space: O(N) (new dictionary for the first string with N places - N is equal to the string length)\n- Time: O(N) (just the str1 and str2 iteration)\n'''\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/python/001.03.py",
    "content": "'''\nURLify: Write a method to replace all spaces in a string with '%20'.\nYou may assume that the string has sufficient space at the end to hold\nthe additional characters, and that you are given the \"true\" length of the string.\n\nExample:\nInput: \"Mr John Smith \", 13\nOutput: \"Mr%20John%20Smith\"\n'''\n\ndef urlify(string, length):\n    original_string = string[0:length]\n    chars = []\n\n    for char in original_string:\n        if char is \" \":\n            chars.append(\"%20\")\n        else:\n            chars.append(char)\n\n    return \"\".join(chars)\n\n\nresult = urlify(\"Mr John Smith \", 13)  # => \"Mr%20John%20Smith\"\nprint(result)\nresult = urlify(\"Mr John Smith \", 14)  # => \"Mr%20John%20Smith%20\"\nprint(result)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/python/001.04.py",
    "content": "'''\nPalindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome.\nA palindrome is a word or phrase that is the same forwards and backwards. A permutation\nis a rearrangement of letters. The palindrome does not need to be limited to just dictionary words.\n\nExample\nInput: Tact Coa\nOutput: True (permutations: \"taco cat\", \"atco eta\", etc.)\n'''\n\n\ndef is_even(number):\n    return number % 2 == 0\n\n\ndef is_even_length(string):\n    return is_even(len(string))\n\n\ndef is_palindrome_permutation(string):\n    string = string.lower()\n    string = \"\".join(string.split())\n    even = is_even_length(string)\n\n    char_counter = {}\n    odd = 0\n\n    for char in string:\n        if char in char_counter:\n            char_counter[char] += 1\n        else:\n            char_counter[char] = 1\n\n    for char, counter in char_counter.items():\n        if not is_even(counter):\n            odd += 1\n\n    return (even and odd == 0) or (not even and not is_even(odd))\n\n\nresult = is_palindrome_permutation('Tact Coa')\nprint(result)  # True\n\nresult = is_palindrome_permutation('Tac Coa')\nprint(result)  # False\n\nresult = is_palindrome_permutation('Tac Tac')\nprint(result)  # True\n\ndata = [\n    ('Tact Coa', True),\n    ('Tac Coa', False),\n    ('Tac Tac', True)\n]\n\nfor [string, expected] in data:\n    actual = is_palindrome_permutation(string)\n    print(actual == expected)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/python/001.05.py",
    "content": "'''\nOne Away: There are three types of edits that can be performed on strings:\ninsert a character, remove a character, or replace a character.\nGiven two strings, write a function to check if they are one edit (or zero edits) away.\n\nExample:\n\npale, ple -> true\npales, pale -> true\npale, bale -> true\npale, bake -> false\nbla, bleble -> false\n'''\n\n\ndef is_two_chars_away(str1, str2):\n    return (len(str1) - len(str2) >= 2) or (len(str2) - len(str1) >= 2)\n\n\ndef number_of_needed_changes(bigger_str, smaller_str):\n    str_counter = {}\n\n    for char in bigger_str:\n        if char in str_counter:\n            str_counter[char] += 1\n        else:\n            str_counter[char] = 1\n\n    for char in smaller_str:\n        if char in str_counter:\n            str_counter[char] -= 1\n\n    needed_changes = 0\n\n    for char, counter in str_counter.items():\n        needed_changes += counter\n\n    return needed_changes\n\n\ndef one_away(str1, str2):\n    if is_two_chars_away(str1, str2):\n        return False\n\n    needed_changes = 0\n\n    if len(str1) >= len(str2):\n        needed_changes = number_of_needed_changes(str1, str2)\n    else:\n        needed_changes = number_of_needed_changes(str2, str1)\n\n    return needed_changes <= 1\n\n\ndata = [\n    ('pale', 'ple', True),\n    ('pales', 'pale', True),\n    ('pale', 'bale', True),\n    ('paleabc', 'pleabc', True),\n    ('pale', 'ble', False),\n    ('a', 'b', True),\n    ('', 'd', True),\n    ('d', 'de', True),\n    ('pale', 'pale', True),\n    ('pale', 'ple', True),\n    ('ple', 'pale', True),\n    ('pale', 'bale', True),\n    ('pale', 'bake', False),\n    ('pale', 'pse', False),\n    ('ples', 'pales', True),\n    ('pale', 'pas', False),\n    ('pas', 'pale', False),\n    ('pale', 'pkle', True),\n    ('pkle', 'pable', False),\n    ('pal', 'palks', False),\n    ('palks', 'pal', False),\n    ('bla', 'bleble', False)\n]\n\nfor [test_s1, test_s2, expected] in data:\n    actual = one_away(test_s1, test_s2)\n    print(actual == expected)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/python/001.06.py",
    "content": "'''\nString Compression: Implement a method to perform basic string compression using the\ncounts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3.\n\nIf the \"compressed\" string would not become smaller than the original string,\nour method should return the original string.\n\nYou can assume the string has only uppercase and lowercase letters (a - z).\n'''\n\n\ndef string_compression(string):\n    if string is '':\n        return ''\n\n    counter = 1\n    current_char = string[0]\n    compressed_string = []\n\n    for char in string[1:]:\n        if char == current_char:\n            counter += 1\n        else:\n            compressed_string.append(current_char)\n            compressed_string.append(str(counter))\n            current_char = char\n            counter = 1\n\n    compressed_string.append(current_char)\n    compressed_string.append(str(counter))\n\n    return ''.join(compressed_string)\n\n\ntest_cases = [\n    ('Aa', 'A1a1'),\n    ('aabcccccaaa', 'a2b1c5a3'),\n    ('', ''),\n    ('abcdef', 'a1b1c1d1e1f1')\n]\n\nfor [string, expected] in test_cases:\n    actual = string_compression(string)\n    print(actual == expected)\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/python/001.07.py",
    "content": "'''\nRotate Matrix: Given an image represented by an NxN matrix,\nwhere each pixel in the image is 4 bytes,\nwrite a method to rotate the image by 90 degrees.\nCan you do this in place?\n'''\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/python/bottlenecks.py",
    "content": "'''\nExample: Given an array of distinct integer values, count the number of pairs of integers that\nhave difference k. For example, given the array { 1, 7, 5, 9, 2, 12, 3 } and the difference \nk = 2,there are four pairs with difference2: (1, 3), (3, 5), (5, 7), (7, 9).\n'''\n\ndef pairs_of_difference(array, diff):\n    hash_table = {}\n\n    for num in array:\n        hash_table[num] = num\n\n    count = 0\n\n    for num in array:\n        if num + diff in hash_table: count += 1\n        if num - diff in hash_table: count += 1\n\n    return count // 2\n\nprint(pairs_of_difference([1, 7, 5, 9, 2, 12, 3], 2))\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/python/is_unique.py",
    "content": "import time\nimport unittest\nfrom collections import defaultdict\n\n\ndef is_unique_chars_using_dictionary(text):\n    char_counter = {}\n\n    for char in text:\n        if char in char_counter:\n            return False\n        else:\n            char_counter[char] = 1\n    \n    return True\n\n\n\nclass Test(unittest.TestCase):\n    test_cases = [\n        (\"abcd\", True),\n        (\"s4fad\", True),\n        (\"\", True),\n        (\"23ds2\", False),\n        (\"hb 627jh=j ()\", False),\n        (\"\".join([chr(val) for val in range(128)]), True),  # unique 128 chars\n        (\"\".join([chr(val // 2) for val in range(129)]), False),  # non-unique 129 chars\n    ]\n\n    test_functions = [\n        is_unique_chars_using_dictionary,\n        # is_unique_chars_sorting,\n    ]\n\n    def test_is_unique_chars(self):\n        num_runs = 1000\n        function_runtimes = defaultdict(float)\n\n        for _ in range(num_runs):\n            for text, expected in self.test_cases:\n                for is_unique_chars in self.test_functions:\n                    start = time.perf_counter()\n                    assert (\n                        is_unique_chars(text) == expected\n                    ), f\"{is_unique_chars.__name__} failed for value: {text}\"\n                    function_runtimes[is_unique_chars.__name__] += (\n                        time.perf_counter() - start\n                    ) * 1000\n\n        print(f\"\\n{num_runs} runs\")\n        for function_name, runtime in function_runtimes.items():\n            print(f\"{function_name}: {runtime:.1f}ms\")\n\n\nif __name__ == \"__main__\":\n    unittest.main()"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/string-compression/string-compression.js",
    "content": "// String Compression: Implement a method to perform basic string compression using the counts of repeated characters.\n// For example, the string `aabcccccaaa` would become `a2b1c5a3`.\n// If the \"compressed\" string would not become smaller than the original string, your method should return the original string.\n// You can assume the string has only uppercase and lowercase letters (a-z)\n\nfunction compress(chars) {\n  let index = 0,\n    p1 = 0;\n\n  while (p1 < chars.length) {\n    let p2 = p1;\n\n    while (p2 < chars.length && chars[p1] === chars[p2]) {\n      p2++;\n    }\n\n    let count = p2 - p1;\n    chars[index++] = chars[p1];\n\n    if (count > 1) {\n      let countString = count.toString();\n\n      for (let char of countString) {\n        chars[index++] = char;\n      }\n    }\n\n    p1 = p2;\n  }\n\n  return chars;\n}\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/urlify/urlify.js",
    "content": "// URLlify: Write a method to replace all spaces in a string with '%20'.\n// You may assume that the string has sufficient space at the end to hold the additional characters,\n// and that you are given the \"true\" length of the string\n\n// Runtime Complexity: O(N), where N = the true length of the string\n// Space Complexity: O(N), where N = the true length of the string in the new array\n\nexport function urlify(string, length, placeholder = '%20') {\n  let output = [];\n  let lastChar = '';\n  let space = ' ';\n\n  for (let index = 0; index < length; index++) {\n    let char = string[index];\n\n    if (char !== space) {\n      output.push(char);\n    }\n\n    if (char === space && lastChar !== space) {\n      output.push(placeholder);\n    }\n\n    lastChar = char;\n  }\n\n  return output.join('');\n}\n\n// Runtime Complexity: O(N), where N = the true length of the string\n// Space Complexity: O(N), where N = the true length of the string in the new array\n\nexport function urlifyForward(string, length, placeholder = '%20') {\n  let output = [];\n  let index = 0;\n  let space = ' ';\n\n  const moveForward = () => {\n    while (string[index] === space) {\n      index++;\n    }\n  };\n\n  while (index < length) {\n    if (string[index] === space) {\n      output.push(placeholder);\n      moveForward();\n    } else {\n      output.push(string[index]);\n      index++;\n    }\n  }\n\n  return output.join('');\n}\n"
  },
  {
    "path": "coding_interviews/cracking-the-coding-interview/chapter-001/urlify/urlify.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { urlify, urlifyForward } from './urlify';\n\ndescribe('urlify', () => {\n  it('', () => {\n    expect(urlify('Mr John Smith     ', 13)).toEqual('Mr%20John%20Smith');\n  });\n});\n\ndescribe('urlifyForward', () => {\n  it('', () => {\n    expect(urlifyForward('Mr John Smith     ', 13)).toEqual(\n      'Mr%20John%20Smith'\n    );\n  });\n});\n"
  },
  {
    "path": "coding_interviews/daily_code_problems/001.py",
    "content": "\"\"\"\nGiven a list of numbers and a number k, return whether any two numbers from the list add up to k.\n\nFor example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.\n\"\"\"\n\n\ndef found_sum_of_two_numbers_brute_force(k, numbers):\n    for index_1 in range(len(numbers)):\n        for index_2 in range(index_1, len(numbers)):\n            if numbers[index_1] + numbers[index_2] == k:\n                return True\n\n    return False\n\n\ndef found_sum_of_two_numbers(k, numbers):\n    start = 0\n    end = len(numbers) - 1\n    sorted_numbers = sorted(numbers)\n\n    while start < end:\n        if sorted_numbers[start] + sorted_numbers[end] == k:\n            return True\n        elif sorted_numbers[start] + sorted_numbers[end] > k:\n            end -= 1\n        else:\n            start += 1\n\n    return False\n\n\ndef test_algorithm(k, numbers):\n    print('Brute force:', found_sum_of_two_numbers_brute_force(k, numbers))\n    print('Optmized:', found_sum_of_two_numbers(k, numbers))\n    print()\n\n\ntest_algorithm(17, [10, 15, 3, 7])\ntest_algorithm(17, [15, 10, 3, 7])\ntest_algorithm(17, [15, 10, 3, 8])\n"
  },
  {
    "path": "coding_interviews/daily_code_problems/002.py",
    "content": "\"\"\"\nGiven an array of integers,\nreturn a new array such that each element at index i of the new\narray is the product of all the numbers in the original array except the one at i.\n\nFor example, if our input was [1, 2, 3, 4, 5],\nthe expected output would be [120, 60, 40, 30, 24].\nIf our input was [3, 2, 1], the expected output would be [2, 3, 6].\n\"\"\"\n\nfrom functools import reduce\n\n\ndef product_with_exception(integers):\n    product_of_all = reduce((lambda product, item: product * item), integers)\n    return list(map(lambda item: product_of_all / item, integers))\n\n\ndef test_product_with_exception(integers, result):\n    print(product_with_exception(integers) == result)\n\n\ntest_product_with_exception([1, 2, 3, 4, 5], [120, 60, 40, 30, 24])\ntest_product_with_exception([3, 2, 1], [2, 3, 6])\ntest_product_with_exception(\n    [-20, 20, 50, 10], [10000, -10000, -4000, -20000])\n"
  },
  {
    "path": "coding_interviews/daily_code_problems/003.py",
    "content": "'''\nGiven the root to a binary tree, implement serialize(root),\nwhich serializes the tree into a string, and deserialize(s),\nwhich deserializes the string back into the tree.\n\nFor example, given the following Node class\n\nclass Node:\n    def __init__(self, val, left=None, right=None):\n        self.val = val\n        self.left = left\n        self.right = right\n\nThe following test should pass:\n\nnode = Node('root', Node('left', Node('left.left')), Node('right'))\nassert deserialize(serialize(node)).left.left.val == 'left.left'\n\nserialize --> 'root' 'left' 'left.left' 'right'\ndeserialize --> Node('root', Node('left', Node('left.left')), Node('right'))\n'''\n\nfrom queue import Queue\n\n\nclass Node:\n    def __init__(self, val, left=None, right=None):\n        self.val = val\n        self.left = left\n        self.right = right\n\n\ndef serialize(node):\n    if node is None:\n        return 'X '\n\n    return node.val + ' ' + serialize(node.left) + serialize(node.right)\n\n\ndef deserialize_node(nodes):\n    value = nodes.get()\n\n    if value == 'X':\n        return None\n\n    node = Node(value)\n    node.left = deserialize_node(nodes)\n    node.right = deserialize_node(nodes)\n    return node\n\n\ndef create_nodes_queue(string):\n    nodes = string.split(' ')\n    queue = Queue()\n\n    for node in nodes:\n        queue.put(node)\n\n    return queue\n\n\ndef deserialize(string):\n    string = string.strip()\n    nodes = create_nodes_queue(string)\n    return deserialize_node(nodes)\n\n\ndef pre_order(tree):\n    if tree is None:\n        return\n\n    print(tree.val)\n    pre_order(tree.left)\n    pre_order(tree.right)\n\n\nnode = Node('root', Node('left', Node('left.left')), Node('right'))\n\nserialized_node = serialize(node)\nprint(serialized_node)\n\ntree = deserialize(serialized_node)\nprint(pre_order(tree))\n"
  },
  {
    "path": "coding_interviews/daily_code_problems/004.py",
    "content": "'''\nGiven an array of integers, find the first missing positive integer in linear time and constant space.\nIn other words, find the lowest positive integer that does not exist in the array.\nThe array can contain duplicates and negative numbers as well.\n\nFor example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.\n\nYou can modify the input array in-place.\n'''\n\n# using a hash table: linear time and linear space\n\n\ndef get_lowest(lowest, present_numbers):\n    while lowest in present_numbers:\n        lowest += 1\n\n    return lowest\n\n\ndef lowest_positive_integer(numbers):\n    present_numbers = {}\n    lowest = 1\n\n    for number in numbers:\n        present_numbers[number] = True\n\n    return get_lowest(lowest, present_numbers)\n\n\nresult = lowest_positive_integer([3, 4, -1, 1])\nprint(result)\n\nresult = lowest_positive_integer([3, 4, 2, -1, 1])\nprint(result)\n\nresult = lowest_positive_integer([5, 4, 2, -1, 1])\nprint(result)\n"
  },
  {
    "path": "coding_interviews/daily_code_problems/005.py",
    "content": "'''\ncons(a, b) constructs a pair, and car(pair) and cdr(pair)\nreturns the first and last element of that pair.\n\nFor example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.\n\nGiven this implementation of cons:\n\ndef cons(a, b):\n    def pair(f):\n        return f(a, b)\n\n    return pair\n\nImplement car and cdr.\n'''\n\n\ndef cons(a, b):\n    def pair(f):\n        return f(a, b)\n\n    return pair\n\n\ndef list_pair(a, b):\n    return [a, b]\n\n\ndef car(pair):\n    [a, _] = pair(list_pair)\n    return a\n\n\ndef cdr(pair):\n    [_, b] = pair(list_pair)\n    return b\n\n\na = 1\nb = 2\n\nresult = car(cons(a, b))\nprint(result)\n\nresult = cdr(cons(a, b))\nprint(result)\n"
  },
  {
    "path": "coding_interviews/daily_code_problems/006.py",
    "content": "'''\nAn XOR linked list is a more memory efficient doubly linked list.\nInstead of each node holding next and prev fields, it holds a field named both,\nwhich is an XOR of the next node and the previous node.\nImplement an XOR linked list; it has an add(element) which adds the element to the end,\nand a get(index) which returns the node at index.\n\nIf using a language that has no pointers (such as Python),\nyou can assume you have access to get_pointer and dereference_pointer functions\nthat converts between nodes and memory addresses.\n'''\n"
  },
  {
    "path": "coding_interviews/daily_code_problems/007.py",
    "content": "'''\nGiven the mapping a = 1, b = 2, ... z = 26, and an encoded message,\ncount the number of ways it can be decoded.\n\nFor example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'.\n\nYou can assume that the messages are decodable. For example, '001' is not allowed.\n'''\n\n\ndef count_decoded_possibilities(encoded_message):\n    pass\n\n\ncount = count_decoded_possibilities('111')\nprint(count)  # 3 - 'aaa', 'ka', and 'ak'\n\ncount = count_decoded_possibilities('121')\nprint(count)  # 3 - 'aba', 'la', 'au'\n"
  },
  {
    "path": "coding_interviews/daily_code_problems/README.md",
    "content": "# Daily Code Problem\n\n- [001](001.py)\n- [002](002.py)\n- [003](003.py)\n- [004](004.py)\n- [005](005.py)\n- [006](006.py)\n- [007](007.py)\n\nProblems: https://www.dailycodingproblem.com\n"
  },
  {
    "path": "coding_interviews/elements_of_programming_interview/array.py",
    "content": "# Your input is an array of\n# integers, and you have to reorder its entries\n# so that the even entries appear first.\n\ndef even_before_odd(numbers):\n    next_even, next_odd = 0, len(numbers)\n    \n    while next_even < next_odd:\n        if numbers[next_even] % 2 == 0:\n            next_even += 1\n        else:\n            numbers[next_even], numbers[next_odd] = numbers[next_odd], numbers[next_even]\n            next_odd -= 1\n\n## With this solution, we have a O(1) space complexity and O(N) time complexity"
  },
  {
    "path": "coding_interviews/elements_of_programming_interview/base_conversion.py",
    "content": "'''\n\"615\"\n\n\"5\" --> 5 --> 5 * (7 ** 0)\n\"1\" --> 1 --> 1 * (7 ** 1)\n\"6\" --> 6 --> 6 * (7 ** 2)\n\n=> 306\n\n306 % 13 = 7\n306 / 13 = 23\n\n23 % 13 = 10\n23 / 13 = 1\n\n1 % 13 = 1\n'''\n\nnum_representation = {\n  10: 'A',\n  11: 'B',\n  12: 'C',\n  13: 'D',\n  14: 'E',\n  15: 'F',\n}\n\ndef to_num_representation(num):\n    if num < 10:\n        return str(num)\n\n    return num_representation[num]\n\ndef base_conversion(string_num, base1, base2):\n    decimal = 0\n    reversed_string_num = string_num[::-1]\n\n    for index in range(len(reversed_string_num)):\n        char_num = reversed_string_num[index]\n        decimal += int(char_num) * (base1 ** index)\n\n    digits = []\n    \n    while decimal:\n        modulo = decimal % base2\n        decimal = decimal // base2\n        digits.append(to_num_representation(modulo))\n\n    return ''.join(digits)[::-1]\n\n\nprint(base_conversion(\"615\", 7, 13))\n"
  },
  {
    "path": "coding_interviews/elements_of_programming_interview/buy_and_sell_stock_once.py",
    "content": "# Buy and Sell stoks once\n\ndef buy_and_sell_stock_once(prices):\n    if not prices:\n        return 0\n\n    min_price, max_profit = float('inf'), 0.0\n\n    for price in prices:\n        profit_if_sell_today = price - min_price\n        max_profit = max(max_profit, profit_if_sell_today)\n        min_price = min(min_price, price)\n\n    return max_profit\n\nprices = [310, 315, 275, 295, 260, 270, 290, 230, 255, 250]\nprint(buy_and_sell_stock_once(prices))\nprint(buy_and_sell_stock_once([]))\n"
  },
  {
    "path": "coding_interviews/elements_of_programming_interview/can_reach_end.py",
    "content": "\"\"\"\nIn a particular board game, a player has to try to advance through a sequence of positions.\nEach position has a nonnegative integer associated with it, representing the maximum you can advance\nfrom that position in one move. You begin in the first position and win by getting to the last position.\nFor example, let A = (3,3,1,0,2,0,1) represent the board game, i.e., the lth entry in A is the maximum we\ncan advance from L Then the game can be won by the following sequence of advances through A: take 1 step\nfrom A[0] to A[1], then 3 steps from A[1] to A[4], then 2 steps from A[4] to A[6], which is the last position.\nNote that A[0] = 3 >= 1, A[1] =3 >= 3, and A[4] = 2 >= 2, so all moves are valid. If A instead was (3,2,0,0,2,0,1),\nit would not be possible to advance past position 3, so the game cannot be won.\n\nWrite a program that takes an array of n integers, where A[i] denotes the maximum you can advance from the index i,\nand returns whether it is possible to advance to the last index starting from the beginning of the array.\n\"\"\"\n\ndef can_reach_end(board_game):\n    furthest_reach_so_far, last_index = 0, len(board_game) - 1\n    current_index = 0\n\n    while current_index <= furthest_reach_so_far and furthest_reach_so_far < last_index:\n        furthest_reach_so_far = max(furthest_reach_so_far, board_game[current_index] + current_index)\n        current_index += 1\n    \n    return furthest_reach_so_far >= last_index\n\nprint(can_reach_end([3, 3, 7, 0, 2, 0, 1]))\nprint(can_reach_end([2, 4, 1, 1, 0, 2, 3]))\nprint(can_reach_end([3, 2, 0, 0, 2, 0, 1]))"
  },
  {
    "path": "coding_interviews/elements_of_programming_interview/delete_duplicates_from_a_sorted_array.py",
    "content": "# input: [2,3,5,5,7,11,11,11,13]\n# output: [2,3,5,7,11,13,0,0,0]\n\n# input: [-2,-2,1]\n# output: [-2,1,0]\n\n# input: [0,0,1,1]\n# output: [0,1,0,0]\n\n'''\nresult = []\ncounter = {}\n\nloop input\n    is not in the counter\n        counter[number] << True\n        result << number\n    \nn = len(input) - len(result)\n\nloop n\n    result << 0\n\nreturn result\n\nSpace: O(2N) = O(N)\nRuntime: O(N)\n'''\n\ndef delete_duplicates(numbers):\n    if not numbers:\n        return [[], 0]\n\n    result = []\n    counter_mapper = {}\n    counter = 0\n\n    for number in numbers:\n        if number not in counter_mapper:\n            counter_mapper[number] = True\n            result.append(number)\n            counter += 1\n\n    difference_of_lengths = len(numbers) - len(result)\n\n    for _ in range(difference_of_lengths):\n        result.append(0)\n\n    return [result, counter]\n\ndef test(input, expect):\n    print(delete_duplicates(input) == expect)\n\ntest([2,3,5,5,7,11,11,11,13], [[2,3,5,7,11,13,0,0,0],6])\ntest([-2,-2,1], [[-2,1,0],2])\ntest([0,0,1,1], [[0,1,0,0],2])\ntest([], [[],0])\n\ndef delete_duplicates_2(numbers):\n    counter = 1\n\n    if not numbers:\n        return [[], 0]\n\n    for index in range(1, len(numbers)):\n        if numbers[index - 1] != numbers[index]:\n            numbers[counter] = numbers[index]\n            counter += 1\n\n    difference_of_lengths = len(numbers) - counter\n\n    for index in range(difference_of_lengths):\n        numbers[len(numbers) - index - 1] = 0\n\n    return [numbers, counter]\n\ndef test_2(input, expect):\n    print(delete_duplicates(input) == expect)\n\ntest_2([2,3,5,5,7,11,11,11,13], [[2,3,5,7,11,13,0,0,0],6])\ntest_2([-2,-2,1], [[-2,1,0],2])\ntest_2([0,0,1,1], [[0,1,0,0],2])\ntest_2([], [[],0])\n"
  },
  {
    "path": "coding_interviews/elements_of_programming_interview/interconvert_string_and_integer.py",
    "content": "# Interconvert String and Integer\n\n'''\n\"123\" => 123\n\"-123\" => -123\n'''\n\ndef to_int(string):\n    sign = 1\n    \n    if string[0] == '-':\n        sign = -1\n        string = string[1:]\n\n    integer = 0\n    reversed_string = string[::-1]\n\n    for index in range(len(string)):\n        int_char = reversed_string[index]\n        digit = ord(int_char) - 48\n        integer += (digit * 10 ** index)\n\n    return integer * sign\n\nprint(to_int('123'))\nprint(to_int('-123'))\n\n'''\n123 => \"123\"\n-123 => \"-123\"\n'''\n\ndef to_string(integer):\n    sign = ''\n\n    if integer < 0:\n        sign = '-'\n\n    abs_integer = abs(integer)\n    digits = []\n\n    while abs_integer > 0:\n        digits.append(chr(ord('0') + abs_integer % 10))\n        abs_integer = abs_integer // 10\n\n    return sign + ''.join(digits[::-1])\n\nprint(to_string(123))\nprint(to_string(-123))\n"
  },
  {
    "path": "coding_interviews/elements_of_programming_interview/longest_subarray_length_with_same_integers.py",
    "content": "'''\nWrite a program that takes an array of integers and finds\nthe length of a longest subarray all of whose entries are equal.\n'''\n\ndef longest_subarray_length_with_same_integers(numbers):\n    if not numbers:\n        return 0\n\n    longest_subarray_length, counter, current_comparator = 0, 0, numbers[0]\n\n    for number in numbers:\n        if number == current_comparator:\n            counter += 1\n        else:\n            counter = 1\n            current_comparator = number\n\n        longest_subarray_length = max(longest_subarray_length, counter)\n\n    return longest_subarray_length\n\nnumbers = [260, 290, 290, 250, 250, 250]\nprices = [310, 315, 275, 295, 260, 270, 290, 230, 255, 250]\n\nprint(longest_subarray_length_with_same_integers(numbers))\nprint(longest_subarray_length_with_same_integers(prices))\nprint(longest_subarray_length_with_same_integers([]))\n"
  },
  {
    "path": "coding_interviews/elements_of_programming_interview/multiply_two_arbitrary_precision_integers.py",
    "content": "# Write a program that takes two arrays representing integers,\n# and retums an integer representing their product\n\n\"\"\"\n1234\n4321\n\nresult1 = 1 x 4 + 1 x 3 x 10 + 1 x 2 x 100 + 1 x 1 x 1000\nresult2 = ...\nresult3 = ...\nresult4 = ...\n\nresult = result1 + result2 + result3 + result4\n\"\"\"\n\ndef multiply_two_arbitrary_precision_integers(int1, int2):\n    result = 0\n\n    for integer in int1:\n        for index in range(len(int2)):\n            result += integer * int2[len(int2) - 1 - index] * pow(10, index)\n\n    return result\n\nprint(multiply_two_arbitrary_precision_integers([1,9,3,7,0,7,7,2,1], [-7,6,1,8,3,8,2,5,7,2,8,7]))\n"
  },
  {
    "path": "coding_interviews/elements_of_programming_interview/spreadsheet_column_encoding.py",
    "content": "encoding_mapper = {\n    'A': 1,\n    'B': 2,\n    'C': 3,\n    'D': 4,\n    'E': 5,\n    'F': 6,\n    'G': 7,\n    'H': 8,\n    'I': 9,\n    'J': 10,\n    'K': 11,\n    'L': 12,\n    'M': 13,\n    'N': 14,\n    'O': 15,\n    'P': 16,\n    'Q': 17,\n    'R': 18,\n    'S': 19,\n    'T': 20,\n    'U': 21,\n    'V': 22,\n    'W': 23,\n    'X': 24,\n    'Y': 25,\n    'Z': 26,\n}\n\ndef spreadcheet_column_encoding(encoding):\n    number, reversed_encoding = 0, encoding[::-1]\n\n    for index in range(len(reversed_encoding)):\n        number += (26 ** index) * (encoding_mapper[reversed_encoding[index]])\n\n    return number"
  },
  {
    "path": "coding_interviews/hackerrank_interview_prep_kit/hash_tables/count_triplets.py",
    "content": "# https://www.hackerrank.com/challenges/count-triplets-1/problem?h_l=interview&h_r=next-challenge&h_r%5B%5D%5B%5D%5B%5D=next-challenge&h_r%5B%5D%5B%5D%5B%5D=next-challenge&h_v=zen&h_v%5B%5D%5B%5D%5B%5D=zen&h_v%5B%5D%5B%5D%5B%5D=zen&isFullScreen=true&playlist_slugs%5B%5D%5B%5D%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D%5B%5D%5B%5D=dictionaries-hashmaps\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\nfrom collections import Counter\n\ndef count_triplets(arr, r):\n    number_counter = Counter(arr)\n    prev_counter = Counter()\n    triplets = 0\n\n    for number in arr:\n        prev = number // r\n        next_num = number * r\n        number_counter[number] -= 1\n\n        if prev_counter[prev] and number_counter[next_num] and number % r == 0:\n            triplets += prev_counter[prev] * number_counter[next_num]\n\n        prev_counter[number] += 1\n\n    return triplets\n\nif __name__ == '__main__':\n    fptr = open(os.environ['OUTPUT_PATH'], 'w')\n    nr = input().rstrip().split()\n    n = int(nr[0])\n    r = int(nr[1])\n    arr = list(map(int, input().rstrip().split()))\n    ans = count_triplets(arr, r)\n    fptr.write(str(ans) + '\\n')\n    fptr.close()\n"
  },
  {
    "path": "coding_interviews/hackerrank_interview_prep_kit/hash_tables/ransom_note.py",
    "content": "# https://www.hackerrank.com/challenges/ctci-ransom-note/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\ndef build_word_counter(magazine):\n    word_counter = {}\n    \n    for word in magazine:\n        if word in word_counter:\n            word_counter[word] += 1\n        else:\n            word_counter[word] = 1\n\n    return word_counter\n\ndef check_notes_on_magazine(word_counter, note):\n    for word in note:\n        if word in word_counter and word_counter[word] > 0:\n            word_counter[word] -= 1\n        else:\n            print('No')\n            return\n        \n    print('Yes')\n\ndef check_magazine(magazine, note):\n    word_counter = build_word_counter(magazine)\n    check_notes_on_magazine(word_counter, note)\n\nif __name__ == '__main__':\n    first_multiple_input = input().rstrip().split()\n    m = int(first_multiple_input[0])\n    n = int(first_multiple_input[1])\n    magazine = input().rstrip().split()\n    note = input().rstrip().split()\n    check_magazine(magazine, note)\n"
  },
  {
    "path": "coding_interviews/hackerrank_interview_prep_kit/hash_tables/sherlock_and_anagrams.py",
    "content": "# https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem?h_l=interview&h_r%5B%5D=next-challenge&h_r%5B%5D=next-challenge&h_v%5B%5D=zen&h_v%5B%5D=zen&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=dictionaries-hashmaps&isFullScreen=true\n\ndef sherlock_and_anagrams(s):\n    substrings = {}\n\n    for i in range(0, len(s) - 1):\n        for index in range(0, len(s) - i):\n            sorted_substring = ''.join(sorted(s[index:index+i+1]))\n            \n            if sorted_substring in substrings:\n                substrings[sorted_substring] += 1\n            else:\n                substrings[sorted_substring] = 1\n\n    count_anagrams = 0\n\n    for _, count in substrings.items():\n        if count > 0:\n            count_anagrams += (count * (count - 1) // 2)\n\n    return count_anagrams\n\nprint(sherlock_and_anagrams('abba'))\nprint(sherlock_and_anagrams('ifailuhkqq'))\nprint(sherlock_and_anagrams('kkkk'))\nprint(sherlock_and_anagrams('ifailuhkqqhucpoltgtyovarjsnrbfpvmupwjjjfiwwhrlkpekxxnebfrwibylcvkfealgonjkzwlyfhhkefuvgndgdnbelgruel'))\n"
  },
  {
    "path": "coding_interviews/hackerrank_interview_prep_kit/hash_tables/two_strings.py",
    "content": "# https://www.hackerrank.com/challenges/two-strings/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps&h_r=next-challenge&h_v=zen\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\ndef two_strings(s1, s2):\n    chars_presence = {}\n    \n    for char in s1:\n        if char not in chars_presence:\n            chars_presence[char] = True\n    \n    for char in s2:\n        if char in chars_presence:\n            return 'YES'\n        \n    return 'NO'\n\nif __name__ == '__main__':\n    fptr = open(os.environ['OUTPUT_PATH'], 'w')\n    q = int(input().strip())\n\n    for q_itr in range(q):\n        s1 = input()\n        s2 = input()\n        result = two_strings(s1, s2)\n        fptr.write(result + '\\n')\n\n    fptr.close()\n"
  },
  {
    "path": "coding_interviews/hackerrank_interview_prep_kit/warmup/counting_valleys.py",
    "content": "# https://www.hackerrank.com/challenges/counting-valleys/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup&h_r=next-challenge&h_v=zen\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\ndef counting_valleys(steps, path):\n    valleys_count, level = 0, 0\n    \n    for step in path:\n        if step == 'U':\n            level += 1\n            \n            if level == 0:\n                valleys_count += 1\n        else:\n            level -= 1\n            \n    return valleys_count\n\nif __name__ == '__main__':\n    fptr = open(os.environ['OUTPUT_PATH'], 'w')\n    steps = int(input().strip())\n    path = input()\n    result = counting_valleys(steps, path)\n    fptr.write(str(result) + '\\n')\n    fptr.close()\n"
  },
  {
    "path": "coding_interviews/hackerrank_interview_prep_kit/warmup/jumping_on_the_clouds.py",
    "content": "# https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\ndef won_the_game(current, end_game):\n    return current == end_game\n\ndef is_cumulus(cloud):\n    return cloud == 0\n\ndef jumping_on_clouds(c):\n    current, jumps, end_game = 0, 0, len(c) - 1\n    \n    while not won_the_game(current, end_game):\n        if current + 2 <= end_game and is_cumulus(c[current + 2]):\n            current += 2\n        else:\n            current += 1\n            \n        jumps += 1\n    \n    return jumps\n\nif __name__ == '__main__':\n    fptr = open(os.environ['OUTPUT_PATH'], 'w')\n    n = int(input().strip())\n    c = list(map(int, input().rstrip().split()))\n    result = jumping_on_clouds(c)\n    fptr.write(str(result) + '\\n')\n    fptr.close()\n"
  },
  {
    "path": "coding_interviews/hackerrank_interview_prep_kit/warmup/repeated_string.py",
    "content": "# https://www.hackerrank.com/challenges/repeated-string/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#\n# aba => 2\n# n = 10\n# abaabaabaa => 7\n# 10 / len(s) => 3\n# 10 % len(s) => 1\n# 2 * 3 + 1\n\ndef repeatedString(s, n):\n    count_as = 0\n    \n    for char in s:\n        if char == 'a':\n            count_as += 1\n    \n    times = n // len(s)\n    remaining = n % len(s)\n    \n    count_as = count_as * times\n    \n    for index in range(0, remaining):\n        if s[index] == 'a':\n            count_as += 1\n            \n    return count_as\n\nif __name__ == '__main__':\n    fptr = open(os.environ['OUTPUT_PATH'], 'w')\n    s = input()\n    n = int(input().strip())\n    result = repeatedString(s, n)\n    fptr.write(str(result) + '\\n')\n    fptr.close()\n"
  },
  {
    "path": "coding_interviews/hackerrank_interview_prep_kit/warmup/sales_by_match.py",
    "content": "# https://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\ndef sock_merchant(n, ar):\n    counter = {}\n    \n    for num in ar:\n        if num in counter:\n            counter[num] += 1\n        else:\n            counter[num] = 1\n            \n    count = 0\n    \n    for _, num_count in counter.items():\n        count += num_count // 2\n        \n    return count\n\nif __name__ == '__main__':\n    fptr = open(os.environ['OUTPUT_PATH'], 'w')\n    n = int(input().strip())\n    ar = list(map(int, input().rstrip().split()))\n    result = sock_merchant(n, ar)\n    fptr.write(str(result) + '\\n')\n    fptr.close()\n"
  },
  {
    "path": "coding_interviews/interviews/fair/decrementBinaryNumber.js",
    "content": "function countOnes(number) {\n  let counter = 0;\n\n  number.split('').forEach((char) => {\n    if (char === '1') counter++;\n  });\n\n  return counter;\n}\n\nfunction toBinary(number) {\n  return number.toString(2);\n}\n\nfunction toDecimal(number) {\n  return parseInt(number, 2);\n}\n\nfunction decrementBinary(number) {\n  return toBinary(toDecimal(number) - 1);\n}\n\nfunction decrementBinaryNumber(number, requests) {\n  const answer = [];\n\n  requests.forEach((request) => {\n    if (request === '?') {\n      answer.push(countOnes(number));\n    } else {\n      number = decrementBinary(number);\n    }\n  });\n\n  return answer;\n}\n"
  },
  {
    "path": "coding_interviews/interviews/fair/diceTotalScore.js",
    "content": "function diceTotalScore(a, b, c) {\n  if (a === b && b === c) {\n    return 1000 * a;\n  }\n\n  if (a === b) {\n    return 500 * a;\n  }\n\n  if (a === c) {\n    return 500 * a;\n  }\n\n  if (b === c) {\n    return 500 * b;\n  }\n\n  return 100 * Math.min(a, b, c);\n}\n"
  },
  {
    "path": "coding_interviews/interviews/fair/isSubmatrixFull.js",
    "content": "function isSubmatrixFull(numbers) {\n  const answer = [];\n\n  for (let i = 0; i < numbers[0].length - 2; i++) {\n    const subMatrixNumbers = new Set();\n\n    for (let row = 0; row < 3; row++) {\n      for (let col = i; col < i + 3; col++) {\n        subMatrixNumbers.add(numbers[row][col]);\n      }\n    }\n\n    answer.push(subMatrixNumbers.size === 9);\n  }\n\n  return answer;\n}\n"
  },
  {
    "path": "coding_interviews/interviews/fair/sortChessSubsquares.js",
    "content": "function sortChessSubsquares(numbers, queries) {\n  queries.forEach(([x, y, w]) => {\n    const blacks = [];\n    const whites = [];\n\n    for (let row = x; row < x + w; row++) {\n      for (let col = y; col < y + w; col++) {\n        if ((row + col) % 2 === 0) {\n          blacks.push(numbers[row][col]);\n        } else {\n          whites.push(numbers[row][col]);\n        }\n      }\n    }\n\n    whites.sort((a, b) => a - b);\n    blacks.sort((a, b) => a - b);\n\n    let whiteCounter = 0;\n    let blackCounter = 0;\n\n    for (let row = x; row < x + w; row++) {\n      for (let col = y; col < y + w; col++) {\n        if ((row + col) % 2 === 0) {\n          numbers[row][col] = blacks[blackCounter];\n          blackCounter++;\n        } else {\n          numbers[row][col] = whites[whiteCounter];\n          whiteCounter++;\n        }\n      }\n    }\n  });\n\n  return numbers;\n}\n"
  },
  {
    "path": "coding_interviews/interviews/google/printSequence/printSequence.js",
    "content": "/*\nnumber of rows: 4\nnumber of columns: 5\n\nPrint this:\n1 8  9 16 17\n2 7 10 15 18\n3 6 11 14 19\n4 5 12 13 20 \n*/\n\nfunction printSequence(rows, columns) {\n  const matrix = [];\n\n  for (let row = 0; row < rows; row++) {\n    const matrixRow = [];\n\n    for (let col = 0; col < columns; col++) {\n      if (col % 2 === 0) {\n        matrixRow.push(col * rows + 1 + row);\n      } else {\n        matrixRow.push((col + 1) * rows - row);\n      }\n    }\n\n    matrix.push(matrixRow);\n  }\n\n  return matrix;\n}\n\nconsole.log(printSequence(4, 5));\nconsole.log(printSequence(6, 6));\n"
  },
  {
    "path": "coding_interviews/interviews/mercari/cumulativeSum.js",
    "content": "const cumulativeSum = (arr, sum = 0) =>\n  arr.map((number) => {\n    sum += number;\n    return sum;\n  });\n\ncumulativeSum([1, 3, 5, 7]);\n"
  },
  {
    "path": "coding_interviews/interviews/mercari/findMaxMin.js",
    "content": "const arr = [1, 2, 3, 4, 100];\n\nconst findMaxMin = (arr = []) => {\n  let min = Infinity;\n  let max = -Infinity;\n\n  arr.forEach((number) => {\n    if (number < min) min = number;\n    if (number > max) max = number;\n  });\n\n  return {\n    min,\n    max,\n  };\n};\n\nfindMaxMin(arr);\n"
  },
  {
    "path": "coding_interviews/interviews/mercari/findSumPairs.js",
    "content": "let arr = [1, 5, 6, 1, 0, 1];\n\nconst findSumPairs = (arr, value) => {\n  const lookup = {};\n  const pairs = [];\n\n  arr.forEach((number) => {\n    const target = value - number;\n\n    if (lookup[target]) {\n      pairs.push([number, target]);\n    }\n\n    lookup[number] = true;\n  });\n\n  return pairs;\n};\n\nfindSumPairs(arr, 6);\n"
  },
  {
    "path": "coding_interviews/interviews/mercari/multipleDupesArray.js",
    "content": "const arr = [1, 1, 2, 3, 4, 5, 6, 7, 8, 6, 6, 7, 7, 7, 10, 10];\n\nconst multipleDupesArray = (arr) => {\n  const counter = {};\n  const duplicates = [];\n\n  arr.forEach((number) => {\n    if (number in counter) counter[number]++;\n    else counter[number] = 1;\n  });\n\n  Object.entries(counter).forEach(([number, count]) => {\n    if (count > 1) duplicates.push(number);\n  });\n\n  return duplicates;\n};\n\nmultipleDupesArray(arr);\n"
  },
  {
    "path": "coding_interviews/interviews/mercari/products.js",
    "content": "// Given the sample response:\n\n// data: {\n//   items: [\n//     {\n//       id: 1,\n//       name: \"Nike Shoes\",\n//       price: 1000,\n//       status: \"on_sale\",\n//       photos: [{ large: 'xxx', thumbnail: 'yyy'}, { large: 'xxx', thumbnail: 'yyy'}]\n//       verified: true,\n//       ..\n//     },\n//     ...\n//   ],\n// }\n\n// get/items\n\n// 1. Construct a query which includes name, price, photos, & status\n// 2. Using the query, bring the data in to RecommendedItems component\n// 3. Render the UI for the recommended items list\n// 4. Handle loading and error states within the component\n\nimport React from 'react';\nimport useQuery from 'react-query';\n\nconst fallBackImg = 'https/....';\n\nconst getThumbail = ({ photos }) =>\n  (photos[0] && photos[0].thumbail) || fallBackImg;\n\nconst useItems = (limit) => {\n  const { data } = useQuery(['items'], fetch(`/items?limit=${limit}`));\n\n  return data.map((item) => ({\n    ...item,\n    thumbnail: getThumbail(item),\n  }));\n};\n\n// items styles\n// toCurrency()\n\nfunction Item({ name, price, thumbnail }) {\n  return (\n    <>\n      <img src={thumbail} alt={name} />\n      <p>{name}</p>\n      <p>{toCurrency(price)}</p>\n    </>\n  );\n}\n\nconst WithLoadingErrorAndData = ({ isLoading, isError, children }) => {\n  if (isLoading) return <Loading />;\n\n  if (isError) return <Error />;\n\n  return children;\n};\n\n// Component\nfunction RecommendedItems({ limit, component }) {\n  const { data, isLoading, isError } = useItems(limit);\n\n  return (\n    <WithLoadingErrorAndData isLoading={isLoading} isError={isError}>\n      {data.items.map((item) => (\n        <Item name={item.name} price={item.price} thumbnail={item.thumbail} />\n      ))}\n    </WithLoadingErrorAndData>\n  );\n}\n"
  },
  {
    "path": "coding_interviews/interviews/mercari/removeDupes.js",
    "content": "const arr = [1, 1, 1, 1, 1, 1, 1];\n\nconst removeDupes = (arr) => [...new Set(arr)];\n\nremoveDupes(arr);\n"
  },
  {
    "path": "coding_interviews/interviews/mercari/retries.js",
    "content": "/* Implement a retryAsync function that will call an asynchronous function and then\n * recall it again on failure until a max number of retries has been reached.\n * The function receives the asynchronous function and the maximum number of retries\n * The function should return the result of the async function and throw an error\n * after the maximum number of retries\n */\n\n// Update the following function\nconst retryAsync = async (asyncFunc, maxRetries) => {\n  try {\n    return await asyncFunc();\n  } catch (error) {\n    if (maxRetries > 0) {\n      return await retryAsync(asyncFunc, maxRetries - 1);\n    } else {\n      throw new Error('error');\n    }\n  }\n};\n\n// Usage Example - DO NOT MODIFY\nconst main = async () => {\n  const myPromise = () =>\n    new Promise((resolve, reject) => {\n      setTimeout(() => {\n        reject('Promise Failed');\n      }, 3000);\n    });\n\n  const res = await retryAsync(myPromise, 3);\n  return res;\n};\nmain();\n"
  },
  {
    "path": "coding_interviews/interviews/meta/compareLettersInArray/compareLettersInArray.js",
    "content": "function hasSameLength(words, letters) {\n  return words.length !== letters.length;\n}\n\nfunction isArray(arr) {\n  return Array.isArray(arr);\n}\n\nfunction bothArrays(words, letters) {\n  return isArray(words) && isArray(letters);\n}\n\nfunction compareLettersInArray(words, letters) {\n  if (hasSameLength(words, letters) || !bothArrays(words, letters)) {\n    return false;\n  }\n\n  let firstLetterMatches = true;\n\n  for (let i = 0; i < words.length; i++) {\n    if (words[i][0] !== letters[i]) {\n      firstLetterMatches = false;\n      break;\n    }\n  }\n\n  return firstLetterMatches;\n}\n\nconst words = ['ant', 'bear', 'vulture', 'viper', 'deer'];\nconst letters = ['a', 'b', 'c', 'd', 'e'];\n\nconsole.log('answer', compareLettersInArray(words, letters));\nconsole.log('answer', compareLettersInArray(words, ['a', 'b', 'v', 'v', 'd']));\n"
  },
  {
    "path": "coding_interviews/interviews/meta/flatten/flatten.js",
    "content": "// [1, [2, [ [3, 4], 5], 6]] => [1, 2, 3, 4, 5, 6]\n\nfunction flatten(arr) {\n  const flatArray = [];\n\n  arr.forEach((element) => {\n    if (Number.isInteger(element)) {\n      flatArray.push(element);\n    } else {\n      flatArray.push(...flatten(element));\n    }\n  });\n\n  return flatArray;\n}\n\nconst flatArray = flatten([1, [2, [[3, 4], 5], 6]]);\n\nconsole.log(flatArray, [1, 2, 3, 4, 5, 6]);\n"
  },
  {
    "path": "coding_interviews/interviews/meta/flatten/flatten2.js",
    "content": "// [1, [2, null, true, [ [3, 'NaN', 4, undefined], 5], false, 6, '7']] => [1, 2, 3, 4, 5, 6]\n\nfunction isString(str) {\n  return typeof str === 'string' || str instanceof String;\n}\n\nfunction flatten(arr) {\n  const flatArray = [];\n\n  arr.forEach((element) => {\n    if (Number.isInteger(element)) {\n      flatArray.push(element);\n    }\n\n    if (element instanceof Array) {\n      flatArray.push(...flatten(element));\n    }\n\n    if (isString(element)) {\n      const numberValue = Number(element);\n\n      if (Number.isInteger(numberValue)) {\n        flatArray.push(numberValue);\n      }\n    }\n  });\n\n  return flatArray;\n}\n\nconst flatArray = flatten([\n  1,\n  [2, null, true, [[3, 'NaN', 4, undefined], 5], false, 6, '7'],\n]);\n\nconsole.log(flatArray, [1, 2, 3, 4, 5, 6, 7]);\n"
  },
  {
    "path": "coding_interviews/interviews/quintoandar/quinto1.py",
    "content": "def group_by(parsed_phone, number):\n    numbers_of_characters = len(parsed_phone)\n    result_list = []\n\n    for i in range(0, numbers_of_characters, number):\n        result_list.append(parsed_phone[i:i+number])\n\n    return result_list\n\nS = \"00-44  48 5555 8361\"\nparsed_phone = S.strip().replace(\"-\", \"\").replace(\" \", \"\")\nnumbers_of_characters = len(parsed_phone)\n\nif numbers_of_characters % 3 == 0 || numbers_of_characters % 3 == 2:\n    return '-'.join(group_by(parsed_phone, 3))\nelse:\n    grouped_by_three = group_by(parsed_phone[0:numbers_of_characters-4], 3)\n    grouped_by_two = group_by(parsed_phone[numbers_of_characters-4:], 2)\n\n    return '-'.join(grouped_by_three + grouped_by_two)\n"
  },
  {
    "path": "coding_interviews/interviews/quintoandar/quinto2.py",
    "content": "A = [0,3,3,7,5,3,11,1]\ntuple_a = [(index, el) for index, el in enumerate(A)]\nsorted_tuple = sorted(tuple_a, key=lambda x: x[1])\n\ndual = []\n\nfor index, el in enumerate(range(len(sorted_tuple) - 1)):\n    result = (sorted_tuple[index], sorted_tuple[index+1])\n    dual.append(result)\n\nsmaller_distance = 1000000000\n\nfor d in dual:\n    indice1, indice2 = d[0][0], d[1][0]\n    value1, value2 = d[0][1], d[1][1]\n\n    if indice1 < indice2:\n        if abs(value1 - value2) < smaller_distance:\n            smaller_distance = abs(value1 - value2)\n    else:\n        if abs(value2 - value1) < smaller_distance:\n            smaller_distance = abs(value2 - value1)\n\nif smaller_distance == 1000000000:\n    print(-1)\nelse:\n    print(smaller_distance)\n"
  },
  {
    "path": "coding_interviews/interviews/quintoandar/quinto3.py",
    "content": "T = [80, 80, 1000000000, 80, 80, 80, 80, 80, 80, 123456789]\n\nnumber_of_shares = int(len(T) / 2)\nnumber_of_different_types = len(set(T))\n\nif number_of_different_types < number_of_shares:\n    return number_of_different_types\nelse:\n    return number_of_shares\n"
  },
  {
    "path": "coding_interviews/interviews/quintoandar/regions.js",
    "content": "// Regions Map\n// We want to represent our operational area in memory and store it in a database.\n// The regions will be used in many different ways. We want to be able to manage them and perform different operations on top of them.\n// They will have a label that needs to be unique\n// The top-level hierarchy is pre-defined as Country > State > City,\n// but after City the regions represented could have many different levels: Zones (\"Zona Sul\"), Neighborhoods (\"Moema\") or even parts of a Neighborhood.\n\n// brasil\n// ├─ rj\n// │  ├─ buzios\n// │  ├─ marica\n// │  └─ rio-de-janeiro\n// └─ sp\n//    ├─ ...\n//    ├─ osasco\n//      |- centro\n//    └─ sao-paulo\n//       _- santana\n//       ├─ central\n//       ├─ north\n//       │  ├─ santana\n//       │  └─ tucuruvi\n//       ├─ south\n//       │  ├─ moema\n//       │  └─ vila-mariana\n//       └─ west\n//          ├─ butanta\n//             |- vila indiana\n//          └─ pinheiros\n\narea1 = buzios;\narea2 = rio - de - janeiro;\n\nconst isDiff = (area1, area2);\n\nconst isEqual = (area1, area2) => {\n  if (Object.keys(area1).length !== Object.keys(area2).length) {\n    return false;\n  }\n\n  let result;\n\n  for (const [key, value] of Object.entries(area1)) {\n    const isObj1 = typeof value === 'object';\n    const isObj2 = typeof area2[key] === 'object';\n\n    if (isObj1 && isObj2) {\n      result = result && isEqual(value, area2[key]);\n    }\n\n    if (isObj1 && !isObj2) {\n      result = false;\n      break;\n    }\n\n    if (isObj2 && !isObj1) {\n      result = false;\n      break;\n    }\n\n    // strings\n    if (value !== area2[key]) {\n      result = false;\n      break;\n    }\n  }\n\n  return result;\n};\n\ninterface Region {\n  [index: string]: string | Region;\n}\n\ninterface City {\n  [index: string]: Region;\n}\n\ninterface Country {\n  [index: string]: City;\n}\n\ninterface Area {\n  [index: string]: Country;\n}\n\n/**\n * {\n * \t\tbrazil: {\n * \t\t\t[state]: {\n * \t\t\t\t[city]: {\n * \t\t\t\t\t[neighborhood]: string | Map<string, string>\n * \t\t\t\t}\n * \t\t\t}\n * \t\t}\n * }\n **/\n"
  },
  {
    "path": "coding_interviews/interviews/smartnews/countries.js",
    "content": "function solution(A) {\n  let countries = buildCountriesMapper(A);\n  let countriesCount = 0;\n\n  for (let row = 0; row < A.length; row++) {\n    for (let col = 0; col < A[row].length; col++) {\n      const country = A[row][col];\n      if (!countries[row][col]) countriesCount++;\n      verifyCountry(A, country, row, col, countries);\n    }\n  }\n\n  return countriesCount;\n}\n\nfunction buildCountriesMapper(A) {\n  const mapper = [];\n\n  for (let row = 0; row < A.length; row++) {\n    const line = [];\n\n    for (let col = 0; col < A[row].length; col++) {\n      line.push(false);\n    }\n\n    mapper.push(line);\n  }\n\n  return mapper;\n}\n\nfunction verifyCountry(A, country, row, col, countries) {\n  if (\n    row < 0 ||\n    col < 0 ||\n    row >= A.length ||\n    col >= A[row].length ||\n    countries[row][col] ||\n    country !== A[row][col]\n  )\n    return;\n\n  countries[row][col] = true;\n  country = A[row][col];\n\n  verifyCountry(A, country, row, col - 1, countries);\n  verifyCountry(A, country, row, col + 1, countries);\n  verifyCountry(A, country, row + 1, col, countries);\n}\n"
  },
  {
    "path": "coding_interviews/interviews/smartnews/emiter.js",
    "content": "/*\n  Event Emiter\n  1. `on` & `emit`\n  2. `off`\n  3. `once`\n*/\n\nclass EventEmiter {\n  events = {};\n\n  on(eventName, fn) {\n    if (!this.events[eventName]) {\n      this.events[eventName] = [{ subscriber: 'on', fn }];\n    } else {\n      this.events[eventName].push({ subscriber: 'on', fn });\n    }\n  }\n\n  emit(eventName, ...args) {\n    if (this.events[eventName]) {\n      for (let i = 0; i < this.events[eventName].length; i++) {\n        this.events[eventName][i].fn(...args);\n\n        if (this.events[eventName][i].subscriber === 'once') {\n          this.off(eventName, this.events[eventName][i].fn);\n        }\n      }\n    }\n  }\n\n  off(eventName, fn) {\n    if (this.events[eventName]) {\n      this.events[eventName] = this.events[eventName].filter(\n        (event) => event.fn !== fn\n      );\n    }\n  }\n\n  once(eventName, fn) {\n    if (!this.events[eventName]) {\n      this.events[eventName] = [{ subscriber: 'once', fn }];\n    } else {\n      this.events[eventName].push({ subscriber: 'once', fn });\n    }\n  }\n}\n\nconst eventEmitet = new EventEmiter();\n\nconst fn1 = (param1, param2) => console.log('test 1', param1, param2);\n\neventEmitet.once('test', fn1);\neventEmitet.emit('test', 'param1', 'param2'); // log param1, param2\neventEmitet.emit('test', 'param1', 'param2'); // log nothing\n"
  },
  {
    "path": "coding_interviews/interviews/smartnews/getTriplets.js",
    "content": "// /**\n//  * Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.\n//  *\n//  * Note:\n//  * The solution set must not contain duplicate triplets.\n//  *\n//  * Example:\n//  * Given array nums = [-1, 0, 1, 2, -1, -4],\n//  *\n//  * A solution set is:\n//  * [\n//  *   [-1, 0, 1],\n//  *   [-1, -1, 2]\n//  * ]\n//  */\n\nconst getTriplets = (nums) => {\n  const triplets = [];\n  const tripletMapper = {};\n  const allNumbers = {};\n\n  nums.forEach((num) => (allNumbers[num] = true));\n\n  for (let i = 0; i < nums.length - 2; i++) {\n    for (let j = i + 1; j < nums.length - 1; j++) {\n      const firstTwoSum = nums[i] + nums[j];\n      const targetNumber = 0 - firstTwoSum;\n\n      if (allNumbers[targetNumber]) {\n        const mapperKey = stringify([nums[i], nums[j], targetNumber]);\n        if (!tripletMapper[mapperKey]) {\n          tripletMapper[mapperKey] = true;\n          triplets.push([nums[i], nums[j], targetNumber]);\n        }\n      }\n    }\n  }\n\n  return triplets;\n};\n\nconst stringify = (nums) => nums[0] + '.' + nums[1] + '.' + nums[2];\n\nconsole.log(getTriplets([0, 0, 0]));\nconsole.log(getTriplets([-1, 0, 1, 2, -1, -4]));\nconsole.log(getTriplets([0, -1, 2]));\nconsole.log(getTriplets([0, -1, Infinity]));\n"
  },
  {
    "path": "coding_interviews/interviews/uber/longest-words.js",
    "content": "// console.log('Hello world');\n\n// I would like you to write a function which takes two arguments: a list of words, each separated by comma, and a list of letters. The function should output the longest words from which can be made using the letters in the list.\n\n// ---------\n// Inputs\n// ---------\n// Words: aab,cab,abba,abacus,scabs,scab,bacca,ab\n// Letters: aabbscb\n// aab, cab, abba\n\n// ----------------------\n// Expected Output\n// ----------------------\n// abba, scab\n\n// Algorithm Analysis\n// O(L + W * CW) => O(W * CW)\n// L = letters\n// W = words\n// CW = chars of word\n\nfunction buildCounter(letters) {\n  let lettersCounter = {};\n\n  for (let char of letters) {\n    if (lettersCounter[char]) {\n      lettersCounter[char]++;\n    } else {\n      lettersCounter[char] = 1;\n    }\n  }\n\n  return lettersCounter;\n}\n\nfunction getLongestWords(words, letters) {\n  let lettersCounter = buildCounter(letters);\n  let longestLength = 0;\n  let allValidWords = {};\n\n  for (let word of words) {\n    let lettersCounterCopy = { ...lettersCounter }; // O(L)\n    let isValid = true;\n\n    for (let char of word) {\n      if (\n        lettersCounterCopy[char] == undefined ||\n        lettersCounterCopy[char] === 0\n      ) {\n        isValid = false;\n        break;\n      }\n\n      lettersCounterCopy[char] -= 1;\n    }\n\n    if (isValid) {\n      if (allValidWords[word.length]) {\n        allValidWords[word.length].push(word);\n      } else {\n        allValidWords[word.length] = [word];\n      }\n\n      longestLength = Math.max(longestLength, word.length);\n    }\n  }\n\n  return allValidWords[longestLength] || [];\n}\n\nconsole.log(\n  getLongestWords(\n    ['aab', 'cab', 'abba', 'abacus', 'scabs', 'scab', 'bacca', 'ab'],\n    'aabbscb'\n  )\n);\nconsole.log(\n  getLongestWords(\n    ['aab', 'cab', 'abba', 'abacus', 'scabs', 'scab', 'bacca', 'ab'],\n    ''\n  )\n);\nconsole.log(\n  getLongestWords(\n    ['aab', 'cab', 'abba', 'abacus', 'scabs', 'scab', 'bacca', 'ab'],\n    'aabbscbsu'\n  )\n);\nconsole.log(\n  getLongestWords(\n    ['aab', 'cab', 'abba', 'abacus', 'scabs', 'scab', 'bacca', 'ab'],\n    'aabbscbs'\n  )\n);\nconsole.log(getLongestWords([''], 'batata'));\nconsole.log(getLongestWords(['batata'], 'batata'));\nconsole.log(getLongestWords(['aaaaaaaaaaaaaa'], 'aaaaaaaaaaaaaa'));\n"
  },
  {
    "path": "coding_interviews/interviews/uber/maxFrequency.js",
    "content": "export function maxFrequency(numbers) {\n  let maxFrequencyNumber = -1;\n  let result = -1;\n  let numberToFrequencyMap = {};\n\n  for (let num of numbers) {\n    if (numberToFrequencyMap[num]) {\n      numberToFrequencyMap[num]++;\n    } else {\n      numberToFrequencyMap[num] = 1;\n    }\n  }\n\n  Object.entries(numberToFrequencyMap).forEach(([num, frequency]) => {\n    if (frequency > maxFrequencyNumber) {\n      maxFrequencyNumber = frequency;\n      result = Number(num);\n    }\n  });\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/interviews/uber/permutations.js",
    "content": "/*\n    Input [2,3]\n    Output:  [\"AD\", \"BD\", \"CD\", \"AE\", \"BE\", \"CE\", \"AF\", \"BF\", \"CF\"], 9\n\n    Input []\n    Output: [], 0\n    \n    Input [1,2]\n    Output: [\"A\", \"B\", \"C\"], 3\n    \n    Input [0,2]\n    Output: [\"+A\", \"+B\", \"+C\"], 3\n    \n    Input [2,3,4]\n    Output: [\"ADG\", \"ADH\", \"ADI\", \"AEG\", ...]\n*/\nlet numberToValues = {\n  0: '+',\n  1: ' ',\n  2: 'ABC',\n  3: 'DEF',\n  4: 'GHI',\n  5: 'JKL',\n  6: 'MNO',\n  7: 'PQRS',\n  8: 'TUV',\n  9: 'WXYZ',\n};\n\nfunction combine(permutations, chars) {\n  let combination = [];\n\n  for (let permutation of permutations) {\n    for (let char of chars) {\n      combination.push(permutation + char);\n    }\n  }\n\n  return combination;\n}\n\nfunction permutations(numbers) {\n  if (numbers.length === 0) {\n    return [];\n  }\n\n  let allPermutations = [];\n  let num = numbers[0];\n  let chars = numberToValues[num];\n\n  for (let char of chars) {\n    allPermutations.push(char);\n  }\n\n  for (let index = 1; index < numbers.length; index++) {\n    let num = numbers[index];\n    let chars = numberToValues[num];\n    allPermutations = combine(allPermutations, chars);\n  }\n\n  return allPermutations;\n}\n\nconsole.log(permutations([2, 3]));\nconsole.log(permutations([2, 3, 4]));\nconsole.log(permutations([1, 2, 3, 4]));\nconsole.log(permutations([0, 1, 2, 3, 4]));\n"
  },
  {
    "path": "coding_interviews/interviews/uber/tests/maxFrequency.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { maxFrequency } from '../maxFrequency';\n\ndescribe('maxFrequency', () => {\n  it('', () => {\n    expect(maxFrequency([2, 2, 2, 3, 3, 1])).toEqual(2);\n  });\n\n  it('', () => {\n    expect(maxFrequency([1, 1, 2, 2, 3, 3])).toEqual(1);\n  });\n\n  it('', () => {\n    expect(maxFrequency([])).toEqual(-1);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/javascript/array/binary-search.js",
    "content": "function getMiddle(start, end) {\n  return Math.floor((start + end) / 2);\n}\n\nfunction binarySearch(numbers, target) {\n  let start = 0;\n  let end = numbers.length - 1;\n  let middle = getMiddle(start, end);\n  let found = false;\n\n  while (start <= end && !found) {\n    middle = getMiddle(start, end);\n    const middleNumber = numbers[middle];\n\n    if (middleNumber === target) found = true;\n    if (middleNumber > target) end = middle - 1;\n    if (middleNumber < target) start = middle + 1;\n  }\n\n  return found;\n}\n\nfunction logResult(list, target) {\n  console.log(binarySearch(list, target));\n}\n\nlogResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5); // true\nlogResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 11); // false\nlogResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], -1); // false\nlogResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0); // false\nlogResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 9); // true\nlogResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1); // true\n"
  },
  {
    "path": "coding_interviews/javascript/array/slice.js",
    "content": "const list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\nlist.slice(0); // all elements: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nlist.slice(0, 3); // first 3 elements: [1, 2, 3]\nlist.slice(1, 4); // from 2 to 4: [2, 3, 4]\n"
  },
  {
    "path": "coding_interviews/javascript/array/subarrays.js",
    "content": "function generateSubarrays(arr, start, end, result) {\n  if (end == arr.length) return;\n  else if (start > end) generateSubarrays(arr, 0, end + 1, result);\n  else {\n    result.push(arr.slice(start, end + 1));\n    generateSubarrays(arr, start + 1, end, result);\n  }\n}\n\nlet arr = [1, 2, 3];\nlet result = [];\n\ngenerateSubarrays(arr, 0, 0, result);\n\nconsole.log(result);\n"
  },
  {
    "path": "coding_interviews/javascript/hashmap/iteration.js",
    "content": "let hashmap = {};\nlet numbers = [1, 2, 3, 4, 5, 1, 6, 1, 7, 0, 8, 9, 10, 0, 1];\n\nfor (let number of numbers) {\n  if (hashmap[number]) {\n    hashmap[number]++;\n  } else {\n    hashmap[number] = 1;\n  }\n}\n\n// if I need keys and values\nObject.entries(hashmap).forEach(([key, value]) => {\n  console.log(`${key} -> ${value}`);\n});\n\n// if I need keys only\nObject.keys(hashmap).forEach((key) => {\n  console.log(key);\n});\n\n// if I need values only\nObject.values(hashmap).forEach((value) => {\n  console.log(value);\n});\n"
  },
  {
    "path": "coding_interviews/javascript/hashmap/object.js",
    "content": "// building a hashmap to count numbers\nlet hashmap = {};\nlet numbers = [1, 2, 3, 4, 5, 1, 6, 1, 7, 0, 8, 9, 10, 0, 1];\n\nfor (let number of numbers) {\n  if (hashmap[number]) {\n    hashmap[number]++;\n  } else {\n    hashmap[number] = 1;\n  }\n}\n\nconsole.log(hashmap);\n"
  },
  {
    "path": "coding_interviews/javascript/queue/queue.js",
    "content": "let queue = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\nfunction push(queue, value) {\n  queue.push(value);\n}\n\nfunction pop(queue) {\n  return queue.shift();\n}\n\nfunction front(queue) {\n  return queue[0];\n}\n\nfunction isEmpty(queue) {\n  return queue.length === 0;\n}\n\nconsole.log(queue); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\npush(queue, 0);\nconsole.log(queue); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0]\n\npop(queue); // 1\nconsole.log(queue); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nfront(queue); // 2\nisEmpty(queue); // false\n\nwhile (!isEmpty(queue)) {\n  queue.pop();\n}\n\nisEmpty(queue); // true\nconsole.log(queue);\n"
  },
  {
    "path": "coding_interviews/javascript/stack/stack.js",
    "content": "let stack = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\nfunction push(stack, value) {\n  stack.push(value);\n}\n\nfunction pop(stack) {\n  return stack.pop();\n}\n\nfunction top(stack) {\n  return stack[stack.length - 1];\n}\n\nfunction isEmpty(stack) {\n  return stack.length === 0;\n}\n\nconsole.log(stack); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\npush(stack, 11);\nconsole.log(stack); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n\npop(stack); // 11\nconsole.log(stack); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\ntop(stack); // 10\nisEmpty(stack); // false\n\nwhile (!isEmpty(stack)) {\n  stack.pop();\n}\n\nisEmpty(stack); // true\nconsole.log(stack);\n"
  },
  {
    "path": "coding_interviews/javascript/string/alphabet.js",
    "content": "// index to alphabet char\nconst alphabet = 'abcdefghijklmnopqrstuvwxyz';\n\nalphabet[0]; // a\nalphabet[1]; // b\n\n// -------------------- // --------------------\n\n// alphabet char to index\nfunction getIndexFromChar(char) {\n  return char.charCodeAt() - 97;\n}\n\ngetIndexFromChar('a'); // 0\ngetIndexFromChar('b'); // 1\n"
  },
  {
    "path": "coding_interviews/javascript/string/charCode.js",
    "content": "'a'.charCodeAt() - 96; // 1\n'b'.charCodeAt() - 96; // 2\n"
  },
  {
    "path": "coding_interviews/javascript/string/isString.js",
    "content": "function isString(str) {\n  return typeof str === 'string' || str instanceof String;\n}\n"
  },
  {
    "path": "coding_interviews/javascript/string/methods.js",
    "content": "const string = 'nihongo';\n\nstring.replace('n', 'N'); // 'Nihongo'\n\nstring.replaceAll('n', 'N'); // 'NihoNgo'\n\nstring.slice(2, 4); // 'ho'\n\nstring.toUpperCase(); // 'NIHONGO'\n\nstring.toUpperCase().toLowerCase(); // 'nihongo'\n\n'  nihongo   '.trim(); // 'nihongo'\n"
  },
  {
    "path": "coding_interviews/javascript/string/sort.js",
    "content": "function sort(string) {\n  return [...string].sort((c1, c2) => c1.localeCompare(c2)).join('');\n}\n"
  },
  {
    "path": "coding_interviews/javascript/tree/inorder.js",
    "content": "/*\nTreeNode {\n  value: int\n  left: TreeNode | null\n  right: TreeNode | null\n}\n*/\n\nfunction inorder(node) {\n  if (!node) return;\n  inorder(node.left);\n  node.value;\n  inorder(node.right);\n}\n"
  },
  {
    "path": "coding_interviews/javascript/tree/postorder.js",
    "content": "/*\nTreeNode {\n  value: int\n  left: TreeNode | null\n  right: TreeNode | null\n}\n*/\n\nfunction postorder(node) {\n  if (!node) return;\n  postorder(node.left);\n  postorder(node.right);\n  node.value;\n}\n"
  },
  {
    "path": "coding_interviews/javascript/tree/preorder.js",
    "content": "/*\nTreeNode {\n  value: int\n  left: TreeNode | null\n  right: TreeNode | null\n}\n*/\n\nfunction preorder(node) {\n  if (!node) return;\n  node.value;\n  preorder(node.left);\n  preorder(node.right);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/a-number-after-a-double-reversal/a-number-after-a-double-reversal.js",
    "content": "function reverse(numString) {\n  const stringArray = [];\n\n  for (let i = numString.length - 1; i >= 0; i--) {\n    stringArray.push(numString[i]);\n  }\n\n  return stringArray.join('');\n}\n\nfunction removeLeadingZeros(numString) {\n  const numStringWithoutLeadingZeros = [];\n  let foundFirstNonLeadingZero = false;\n\n  for (let i = 0; i < numString.length; i++) {\n    const digitChar = numString[i];\n\n    if (\n      (!foundFirstNonLeadingZero && digitChar !== '0') ||\n      foundFirstNonLeadingZero\n    ) {\n      foundFirstNonLeadingZero = true;\n      numStringWithoutLeadingZeros.push(digitChar);\n    }\n  }\n\n  return numStringWithoutLeadingZeros.join('');\n}\n\nexport function isSameAfterReversals(num) {\n  const numString = num.toString();\n\n  if (numString.length === 1) {\n    return true;\n  }\n\n  const reversedNumString = removeLeadingZeros(reverse(numString));\n\n  return numString === reverse(reversedNumString);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/a-number-after-a-double-reversal/tests/a-number-after-a-double-reversal.test.js",
    "content": "import { describe, it, expect } from 'vitest';\nimport { isSameAfterReversals } from '../a-number-after-a-double-reversal';\n\ndescribe('isSameAfterReversals', () => {\n  it('', () => {\n    expect(isSameAfterReversals(526)).toBeTruthy();\n  });\n\n  it('', () => {\n    expect(isSameAfterReversals(1800)).toBeFalsy();\n  });\n\n  it('', () => {\n    expect(isSameAfterReversals(0)).toBeTruthy();\n  });\n\n  it('', () => {\n    expect(isSameAfterReversals(609576)).toBeTruthy();\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/add-digits/add-digits.js",
    "content": "/*\nGiven an integer num, repeatedly add all its digits until the result has only one digit, and return it.\n\nInput: num = 38\nOutput: 2\nExplanation: The process is\n38 --> 3 + 8 --> 11\n11 --> 1 + 1 --> 2 \nSince 2 has only one digit, return it.\n\nInput: num = 0\nOutput: 0\n*/\n\nfunction isSingleDigit(number) {\n  return Math.floor(number / 10) === 0;\n}\n\nfunction addDigits(number) {\n  let result = number;\n  let sumOfDigits = 0;\n\n  while (!isSingleDigit(result)) {\n    while (result) {\n      digit = result % 10;\n      result = Math.floor(result / 10);\n      sumOfDigits += digit;\n    }\n\n    result = sumOfDigits;\n    sumOfDigits = 0;\n  }\n\n  return result;\n}\n\nconsole.log('addDigits', addDigits(38));\nconsole.log('addDigits', addDigits(0));\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/add-two-integers/index.js",
    "content": "const sum = (num1, num2) => num1 + num2;\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/alternating-digit-sum/alternating-digit-sum.js",
    "content": "function isEvent(num) {\n  return num % 2 === 0;\n}\n\nfunction alternateDigitSum(n) {\n  let output = 0;\n  let nString = n.toString();\n\n  for (let index = 0; index < nString.length; index++) {\n    if (isEvent(index)) output += Number(nString[index]);\n    else output += Number(nString[index]) * -1;\n  }\n\n  return output;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/apply-operations-to-an-array/apply-operations-to-an-array.js",
    "content": "function applyOperations(nums) {\n  for (let index = 0; index < nums.length - 1; index++) {\n    if (nums[index] === nums[index + 1]) {\n      nums[index] *= 2;\n      nums[index + 1] = 0;\n    }\n  }\n\n  let zeros = 0;\n\n  for (let num of nums) {\n    if (num === 0) zeros++;\n  }\n\n  let result = [];\n\n  for (let num of nums) {\n    if (num !== 0) {\n      result.push(num);\n    }\n  }\n\n  for (let index = 1; index <= zeros; index++) {\n    result.push(0);\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/arithmetic_progression/arithmetic_progression.py",
    "content": "# https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence\n\n\ndef can_make_arithmetic_progression(arr):\n    sorted_arr, diff = sorted(arr), '-Inf'\n\n    for index in range(len(sorted_arr) - 1):\n        if diff == '-Inf':\n            diff = sorted_arr[index + 1] - sorted_arr[index]\n\n        if sorted_arr[index + 1] - sorted_arr[index] != diff:\n            return False\n\n    return True\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/array_partition.py",
    "content": "'''\nhttps://leetcode.com/problems/array-partition-i/description/\n\nInput: [1,4,3,2]\nOutput: 4\n'''\n\ndef array_pair_sum(nums):\n    return sum(sorted(nums)[::2])\n\nprint(array_pair_sum([1, 4, 3, 2]))\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/average-of-levels-in-binary-tree/average-of-levels-in-binary-tree.js",
    "content": "function averageOfLevels(root) {\n  const queue = [];\n  const averageOfLevels = [];\n\n  queue.push(root);\n\n  while (queue.length) {\n    let sumOfLevelNodes = 0;\n    let levelNumberOfNodes = queue.length;\n\n    for (let node of queue) {\n      sumOfLevelNodes += node.val;\n    }\n\n    averageOfLevels.push(sumOfLevelNodes / queue.length);\n\n    for (let index = 0; index < levelNumberOfNodes; index++) {\n      const node = queue.shift();\n      node.left && queue.push(node.left);\n      node.right && queue.push(node.right);\n    }\n  }\n\n  return averageOfLevels;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/average-salary-excluding-the-minimum-and-maximum-salary/average-salary-excluding-the-minimum-and-maximum-salary.js",
    "content": "function average(salaries) {\n  let min = Infinity;\n  let max = -Infinity;\n  let sum = 0;\n\n  for (let salary of salaries) {\n    min = Math.min(min, salary);\n    max = Math.max(max, salary);\n    sum += salary;\n  }\n\n  sum -= min + max;\n  return sum / (salaries.length - 2);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/average-value-of-even-numbers-that-are-divisible-by-three/average-value-of-even-numbers-that-are-divisible-by-three.js",
    "content": "// https://leetcode.com/problems/average-value-of-even-numbers-that-are-divisible-by-three\n\nfunction isEven(num) {\n  return num % 2 === 0;\n}\n\nfunction isDividedBy3(num) {\n  return num % 3 === 0;\n}\n\nfunction averageValue(nums) {\n  let n = 0;\n  let sum = 0;\n\n  for (let num of nums) {\n    if (isEven(num) && isDividedBy3(num)) {\n      n++;\n      sum += num;\n    }\n  }\n\n  return n ? Math.floor(sum / n) : 0;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/backspace-string-compare/index.js",
    "content": "function buildStack(string) {\n  const stack = [];\n\n  for (let index = 0; index < string.length; index++) {\n    if (string[index] === '#') {\n      stack.pop();\n    } else {\n      stack.push(string[index]);\n    }\n  }\n\n  return stack;\n}\n\nfunction isEqual(stack1, stack2) {\n  if (stack1.length !== stack2.length) {\n    return false;\n  }\n\n  for (let index = 0; index < stack1.length; index++) {\n    if (stack1[index] !== stack2[index]) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nexport function backspaceCompare(s, t) {\n  const sStack = buildStack(s);\n  const tStack = buildStack(t);\n  return isEqual(sStack, tStack);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/backspace-string-compare/tests/index.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { backspaceCompare } from '../';\n\ndescribe('backspaceCompare', () => {\n  it('', () => {\n    expect(backspaceCompare('ab#c', 'ad#c')).toBeTruthy();\n  });\n\n  it('', () => {\n    expect(backspaceCompare('ab##', 'c#d#')).toBeTruthy();\n  });\n\n  it('', () => {\n    expect(backspaceCompare('a#c', 'b')).toBeFalsy();\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/baseball-game/baseball-game.js",
    "content": "function calPoints(ops) {\n  const record = [];\n\n  for (let op of ops) {\n    if (op === 'C') {\n      record.pop();\n    } else if (op === 'D') {\n      const lastOp = record[record.length - 1];\n      record.push(lastOp * 2);\n    } else if (op === '+') {\n      const lastOp = record[record.length - 1];\n      const penultimateOp = record[record.length - 2];\n      record.push(lastOp + penultimateOp);\n    } else {\n      record.push(Number(op));\n    }\n  }\n\n  return record.reduce((recordItem, sum) => sum + recordItem, 0);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/best-poker-hand/best-poker-hand.js",
    "content": "// https://leetcode.com/problems/best-poker-hand\n\nfunction buildMap(list) {\n  let map = new Map();\n\n  for (let item of list) {\n    if (map.has(item)) map.set(item, map.get(item) + 1);\n    else map.set(item, 1);\n  }\n\n  return map;\n}\n\nfunction bestHand(ranks, suits) {\n  let suitsMap = buildMap(suits);\n\n  for (let [_, count] of suitsMap.entries()) {\n    if (count >= 5) return 'Flush';\n  }\n\n  let ranksMap = buildMap(ranks);\n  let hasPair = false;\n\n  for (let [_, count] of ranksMap.entries()) {\n    if (count >= 3) return 'Three of a Kind';\n    if (count >= 2) hasPair = true;\n  }\n\n  return hasPair ? 'Pair' : 'High Card';\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock-tle.js",
    "content": "function maxProfit(prices) {\n  let max = 0;\n\n  for (let index = 0; index < prices.length; index++) {\n    for (\n      let compareIndex = index + 1;\n      compareIndex < prices.length;\n      compareIndex++\n    ) {\n      max = Math.max(max, prices[compareIndex] - prices[index]);\n    }\n  }\n\n  return max;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.js",
    "content": "function maxProfit(prices) {\n  let max = 0;\n  let buy = 0;\n  let sell = 1;\n\n  while (sell < prices.length) {\n    if (prices[buy] < prices[sell]) {\n      let profit = prices[sell] - prices[buy];\n      max = Math.max(max, profit);\n    } else {\n      buy = sell;\n    }\n\n    sell++;\n  }\n\n  return max;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/binary-number-with-alternating-bits/binary-number-with-alternating-bits.js",
    "content": "function toBinary(n) {\n  let binary = [];\n\n  while (n) {\n    binary.push((n % 2).toString());\n    n = Math.floor(n / 2);\n  }\n\n  return binary.join('');\n}\n\nfunction isAlternating(binary) {\n  let previous = binary[0];\n\n  for (let index = 1; index < binary.length; index++) {\n    let current = binary[index];\n    if (previous === current) return false;\n    previous = current;\n  }\n\n  return true;\n}\n\nfunction hasAlternatingBits(n) {\n  return isAlternating(toBinary(n));\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/binary-search/binary-search.js",
    "content": "function search(nums, target) {\n  let start = 0;\n  let end = nums.length - 1;\n  let middle = Math.floor((end + start) / 2);\n  let index = -1;\n  let found = false;\n\n  while (start <= end && !found) {\n    if (target > nums[middle]) {\n      start = middle + 1;\n      middle = Math.floor((end + start) / 2);\n    } else if (target < nums[middle]) {\n      end = middle - 1;\n      middle = Math.floor((end + start) / 2);\n    } else {\n      index = middle;\n      found = true;\n    }\n  }\n\n  return index;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/binary-tree-inorder-traversal/binary-tree-inorder-traversal.js",
    "content": "function inorderTraversal(root) {\n  if (!root) {\n    return [];\n  }\n\n  return [\n    ...inorderTraversal(root.left),\n    root.val,\n    ...inorderTraversal(root.right),\n  ];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/binary-tree-paths/binary-tree-paths.js",
    "content": "function traversal(node, paths, path) {\n  if (!node.left && !node.right) {\n    paths.push(path.join('->'));\n  }\n\n  if (node.left) {\n    traversal(node.left, paths, [...path, node.left.val]);\n  }\n\n  if (node.right) {\n    traversal(node.right, paths, [...path, node.right.val]);\n  }\n}\n\nfunction binaryTreePaths(root) {\n  let paths = [];\n  traversal(root, paths, [root.val]);\n  return paths;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/binary-tree-postorder-traversal/binary-tree-postorder-traversal.js",
    "content": "function postorderTraversal(root) {\n  if (!root) {\n    return [];\n  }\n\n  return [\n    ...postorderTraversal(root.left),\n    ...postorderTraversal(root.right),\n    root.val,\n  ];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/binary-tree-preorder-traversal/binary-tree-preorder-traversal.js",
    "content": "function preorderTraversal(root) {\n  if (!root) {\n    return [];\n  }\n\n  return [\n    root.val,\n    ...preorderTraversal(root.left),\n    ...preorderTraversal(root.right),\n  ];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/binary-tree-tilt/binary-tree-tilt-optimized.js",
    "content": "// https://leetcode.com/problems/binary-tree-tilt\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n\nlet sum;\n\nfunction sumNodes(node) {\n  if (!node) return 0;\n\n  let leftSum = sumNodes(node.left);\n  let rightSum = sumNodes(node.right);\n\n  sum += Math.abs(leftSum - rightSum);\n\n  return node.val + leftSum + rightSum;\n}\n\nfunction findTilt(root) {\n  sum = 0;\n  sumNodes(root);\n  return sum;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/binary-tree-tilt/binary-tree-tilt.js",
    "content": "// https://leetcode.com/problems/binary-tree-tilt\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n\nfunction sumNodes(node) {\n  if (!node) return 0;\n  return node.val + sumNodes(node.left) + sumNodes(node.right);\n}\n\nfunction findTilt(root) {\n  if (!root) return 0;\n  return (\n    Math.abs(sumNodes(root.left) - sumNodes(root.right)) +\n    findTilt(root.left) +\n    findTilt(root.right)\n  );\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/binary_in_linked_list/binary_in_linked_list.py",
    "content": "def get_decimal_value(head):\n    numbers = [head.val]\n\n    while head.next:\n        head = head.next\n        numbers.append(head.val)\n\n    decimal_number = 0\n    base = 1\n\n    for index in range(len(numbers)):\n        decimal_number += base * numbers[len(numbers) - index - 1]\n        base *= 2\n\n    return decimal_number\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/build_an_array_with_stack_operations/build_an_array_with_stack_operations.py",
    "content": "# https://leetcode.com/problems/build-an-array-with-stack-operations\n\ndef build_array(target, n):\n    hash = {}\n    \n    for num in target:\n        hash[num] = True\n    \n    result = []\n    \n    for num in range(1, n + 1):\n        if len(hash) == 0: break\n            \n        result.append('Push')\n        \n        if num in hash: del hash[num]\n        else: result.append('Pop')\n            \n    return result\n\ndef build_array(target, n):\n    s = set(target)\n    result = []\n\n    for index in range(1, target[-1] + 1):\n        result.append('Push')\n        if index not in s: result.append('Pop')\n            \n    return result\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/build_array_from_permutation/build_array_from_permutation.js",
    "content": "// https://leetcode.com/problems/build-array-from-permutation\n\nconst buildArray = function (nums) {\n  return nums.map((num) => nums[num]);\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/buy-two-chocolates/buy-two-chocolates-on.js",
    "content": "// https://leetcode.com/problems/buy-two-chocolates\n\nfunction buyChoco(prices, money) {\n  let min1 = Infinity;\n  let min2 = Infinity;\n\n  for (let num of prices) {\n    if (num < min1) {\n      min2 = min1;\n      min1 = num;\n    } else if (num <= min2) {\n      min2 = num;\n    }\n  }\n\n  return money - min1 - min2 >= 0 ? money - min1 - min2 : money;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/buy-two-chocolates/buy-two-chocolates-sort.js",
    "content": "// https://leetcode.com/problems/buy-two-chocolates\n\nfunction buyChoco(prices, money) {\n  prices.sort((a, b) => a - b);\n  const first = prices[0];\n  const second = prices[1];\n  const diff = money - first - second;\n  return diff >= 0 ? diff : money;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/buy-two-chocolates/buy-two-chocolates.js",
    "content": "// https://leetcode.com/problems/buy-two-chocolates\n\nfunction buyChocolate(prices, money) {\n  let price = Infinity;\n  let priceIndex = 0;\n\n  for (let index = 0; index < prices.length; index++) {\n    if (prices[index] <= money && prices[index] < price) {\n      price = prices[index];\n      priceIndex = index;\n    }\n  }\n\n  prices[priceIndex] = Infinity;\n  return money - price;\n}\n\nfunction buyChoco(prices, money) {\n  let restMoney = buyChocolate(prices, buyChocolate(prices, money));\n  return restMoney >= 0 ? restMoney : money;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/calculate-amount-paid-in-taxes/calculate-amount-paid-in-taxes.js",
    "content": "// https://leetcode.com/problems/calculate-amount-paid-in-taxes\n\nfunction calculateTax(brackets, income) {\n  let taxes = 0;\n  let appliedIncome = 0;\n  let moneyToApplyTax;\n  let tax;\n\n  for (let index = 0; index < brackets.length && income > 0; index++) {\n    moneyToApplyTax = Math.min(income, brackets[index][0] - appliedIncome);\n    appliedIncome += moneyToApplyTax;\n    tax = moneyToApplyTax * (brackets[index][1] / 100);\n    taxes += tax;\n    income -= moneyToApplyTax;\n  }\n\n  return taxes;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/calculate-delayed-arrival-time/calculate-delayed-arrival-time.js",
    "content": "// https://leetcode.com/problems/calculate-delayed-arrival-time\n\nfunction findDelayedArrivalTime(arrivalTime, delayedTime) {\n  return (arrivalTime + delayedTime) % 24;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/calculate-digit-sum-of-a-string/calculate-digit-sum-of-a-string.js",
    "content": "function buildSubsets(s, k) {\n  const subsets = [];\n\n  for (let index = 0; index < s.length; index += k) {\n    subsets.push(s.substring(index, index + k));\n  }\n\n  return subsets;\n}\n\nfunction sumDigits(digits) {\n  let sumOfDigits = 0;\n\n  for (let digit of digits) {\n    sumOfDigits += Number(digit);\n  }\n\n  return sumOfDigits;\n}\n\nfunction sumDigitsOfSubsets(subsets) {\n  return subsets.map(sumDigits);\n}\n\nfunction digitSum(s, k) {\n  if (s.length <= k) return s;\n\n  const subsets = buildSubsets(s, k);\n  const sumOfDigitsOfSubsets = sumDigitsOfSubsets(subsets);\n  const newString = sumOfDigitsOfSubsets.join('');\n\n  return digitSum(newString, k);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/calculate-money-in-leetcode-bank/calculate-money-in-leetcode-bank.js",
    "content": "function totalMoney(n) {\n  let monday = 0;\n  let previousDay = monday;\n  let counter = monday;\n\n  for (let index = 0; index < n; index++) {\n    if (index % 7 === 0) {\n      monday++;\n      counter += monday;\n      previousDay = monday;\n    } else {\n      previousDay++;\n      counter += previousDay;\n    }\n  }\n\n  return counter;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/can-place-flowers/can-place-flowers.js",
    "content": "function canPlaceFlowers(flowerbed, n) {\n  let counter = 0;\n\n  for (let index = 0; index < flowerbed.length; index++) {\n    if (flowerbed[index] === 0) {\n      let isLeftPlotEmpty = index === 0 || flowerbed[index - 1] === 0;\n      let isRightPlotEmpty =\n        index === flowerbed.length - 1 || flowerbed[index + 1] === 0;\n\n      if (isLeftPlotEmpty && isRightPlotEmpty) {\n        flowerbed[index] = 1;\n        counter++;\n      }\n    }\n  }\n\n  return counter >= n;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/capitalize-the-title/capitalize-the-title.js",
    "content": "function isUppercase(char) {\n  return char.charCodeAt() >= 65 && char.charCodeAt() <= 90;\n}\n\nfunction isLowercase(char) {\n  return char.charCodeAt() >= 97 && char.charCodeAt() <= 122;\n}\n\nfunction capitalizeChar(char) {\n  return isUppercase(char) ? char : String.fromCharCode(char.charCodeAt() - 32);\n}\n\nfunction lowercaseChar(char) {\n  return isLowercase(char) ? char : String.fromCharCode(char.charCodeAt() + 32);\n}\n\nfunction capitalize(string) {\n  return capitalizeChar(string[0]) + lowercase(string.slice(1));\n}\n\nfunction lowercase(string) {\n  return string.split('').map(lowercaseChar).join('');\n}\n\nfunction parse(string) {\n  return string.length <= 2 ? lowercase(string) : capitalize(string);\n}\n\nfunction capitalizeTitle(title) {\n  return title.split(' ').map(parse).join(' ');\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/cells-in-a-range-on-an-excel-sheet/cells-in-a-range-on-an-excel-sheet.js",
    "content": "const alphabet = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n\nexport function cellsInRange(s) {\n  const result = [];\n\n  for (\n    let alpha = alphabet.indexOf(s[0]);\n    alpha <= alphabet.indexOf(s[3]);\n    alpha++\n  ) {\n    for (let i = Number(s[1]); i <= Number(s[4]); i++) {\n      result.push(alphabet[alpha] + i.toString());\n    }\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/cells-in-a-range-on-an-excel-sheet/tests/cells-in-a-range-on-an-excel-sheet.test.js",
    "content": "import { describe, it, expect } from 'vitest';\nimport { cellsInRange } from '../cells-in-a-range-on-an-excel-sheet';\n\ndescribe('cellsInRange', () => {\n  it('', () => {\n    expect(cellsInRange('U7:X9')).toEqual([\n      'U7',\n      'U8',\n      'U9',\n      'V7',\n      'V8',\n      'V9',\n      'W7',\n      'W8',\n      'W9',\n      'X7',\n      'X8',\n      'X9',\n    ]);\n  });\n\n  it('', () => {\n    expect(cellsInRange('P7:Z7')).toEqual([\n      'P7',\n      'Q7',\n      'R7',\n      'S7',\n      'T7',\n      'U7',\n      'V7',\n      'W7',\n      'X7',\n      'Y7',\n      'Z7',\n    ]);\n  });\n\n  it('', () => {\n    expect(cellsInRange('K1:L2')).toEqual(['K1', 'K2', 'L1', 'L2']);\n  });\n\n  it('', () => {\n    expect(cellsInRange('A1:F1')).toEqual(['A1', 'B1', 'C1', 'D1', 'E1', 'F1']);\n  });\n\n  it('', () => {\n    expect(cellsInRange('K2:L3')).toEqual(['K2', 'K3', 'L2', 'L3']);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/check-array-formation-through-concatenation/check-array-formation-through-concatenation.js",
    "content": "function buildMap(pieces) {\n  let hashmap = new Map();\n\n  for (let piece of pieces) {\n    hashmap.set(piece[0], piece);\n  }\n\n  return hashmap;\n}\n\nfunction canFormArray(arr, pieces) {\n  let index = 0;\n  let hashmap = buildMap(pieces);\n  let output = [];\n\n  while (index < arr.length) {\n    let num = arr[index];\n    if (!hashmap.has(num)) return false;\n    output = [...output, ...hashmap.get(num)];\n    index += hashmap.get(num).length;\n  }\n\n  if (arr.length !== output.length) return false;\n\n  for (let index = 0; index < arr.length; index++) {\n    if (arr[index] !== output[index]) return false;\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/check-distances-between-same-letters/check-distances-between-same-letters.js",
    "content": "function getDistanceIndex(char) {\n  return char.charCodeAt() - 97;\n}\n\nfunction checkDistances(string, distance) {\n  const hashmap = new Map();\n\n  for (let index = 0; index < string.length; index++) {\n    const char = string[index];\n\n    if (hashmap.has(char)) {\n      const distanceIndex = getDistanceIndex(char);\n      const charDistance = distance[distanceIndex];\n      const previousIndex = hashmap.get(char);\n      if (index - previousIndex - 1 !== charDistance) return false;\n    } else {\n      hashmap.set(char, index);\n    }\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/check-if-a-string-is-an-acronym-of-words/check-if-a-string-is-an-acronym-of-words.js",
    "content": "// https://leetcode.com/problems/check-if-a-string-is-an-acronym-of-words\n\nfunction isAcronym(words, s) {\n  if (words.length !== s.length) return false;\n\n  for (let index = 0; index < s.length; index++) {\n    if (words[index][0] !== s[index]) {\n      return false;\n    }\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js",
    "content": "function hasPrefix(word, searchWord) {\n  if (searchWord.length > word.length) return false;\n\n  for (let index = 0; index < searchWord.length; index++) {\n    if (searchWord[index] !== word[index]) return false;\n  }\n\n  return true;\n}\n\nfunction isPrefixOfWord(sentence, searchWord) {\n  const words = sentence.split(' ');\n\n  for (let index = 0; index < words.length; index++) {\n    if (hasPrefix(words[index], searchWord)) return index + 1;\n  }\n\n  return -1;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/check-if-all-as-appears-before-all-bs/check-if-all-as-appears-before-all-bs.js",
    "content": "function checkString(s) {\n  let gotFirstB = false;\n\n  for (let char of s) {\n    if (char === 'b' && !gotFirstB) {\n      gotFirstB = true;\n    }\n\n    if (char === 'a' && gotFirstB) {\n      return false;\n    }\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/check-if-matrix-is-x-matrix/check-if-matrix-is-x-matrix.js",
    "content": "function isInGrid(grid, row, col) {\n  return row >= 0 && col >= 0 && row < grid.length && col < grid.length;\n}\n\nconst DIAGONAL = -1;\n\nfunction getDiagonalFromLeftToRight(grid) {\n  let row = 0;\n  let col = 0;\n  let values = [];\n\n  while (isInGrid(grid, row, col)) {\n    values.push(grid[row][col]);\n    grid[row][col] = DIAGONAL;\n    row++;\n    col++;\n  }\n\n  return values;\n}\n\nfunction getDiagonalFromRightToLeft(grid) {\n  let row = 0;\n  let col = grid.length - 1;\n  let values = [];\n\n  while (isInGrid(grid, row, col)) {\n    if (grid[row][col] !== DIAGONAL) {\n      values.push(grid[row][col]);\n      grid[row][col] = DIAGONAL;\n    }\n\n    row++;\n    col--;\n  }\n\n  return values;\n}\n\nfunction isDiagonalNonZero(diagonal) {\n  return diagonal.filter((value) => value === 0).length === 0;\n}\n\nfunction isOtherZero(grid) {\n  for (let row = 0; row < grid.length; row++) {\n    for (let col = 0; col < grid.length; col++) {\n      if (grid[row][col] !== DIAGONAL && grid[row][col] !== 0) {\n        return false;\n      }\n    }\n  }\n\n  return true;\n}\n\nfunction checkXMatrix(grid) {\n  const fromLeftToRightDiagonalValues = getDiagonalFromLeftToRight(grid);\n  const fromRightToLeftDiagonalValues = getDiagonalFromRightToLeft(grid);\n  const isFromLeftToRightNonZero = isDiagonalNonZero(\n    fromLeftToRightDiagonalValues\n  );\n  const isFromRightToLeftNonZero = isDiagonalNonZero(\n    fromRightToLeftDiagonalValues\n  );\n  const isOtherElementsZero = isOtherZero(grid);\n\n  return (\n    isFromLeftToRightNonZero && isFromRightToLeftNonZero && isOtherElementsZero\n  );\n}\n\nfunction checkXMatrix(grid) {\n  const n = grid.length;\n\n  for (let i = 0; i < grid.length; i++) {\n    for (let j = 0; j < grid[0].length; j++) {\n      if (i == j || i + j + 1 == n) {\n        if (grid[i][j] == 0) return false;\n      } else {\n        if (grid[i][j] != 0) return false;\n      }\n    }\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/check-if-number-has-equal-digit-count-and-digit-value/check-if-number-has-equal-digit-count-and-digit-value.js",
    "content": "function digitCount(num) {\n  let counter = new Map();\n\n  for (let digit of num) {\n    if (counter.has(digit)) {\n      counter.set(digit, counter.get(digit) + 1);\n    } else {\n      counter.set(digit, 1);\n    }\n  }\n\n  for (let index = 0; index < num.length; index++) {\n    let digit = num[index];\n    let indexString = index.toString();\n\n    if (\n      counter.has(indexString) &&\n      counter.get(indexString) !== Number(digit)\n    ) {\n      return false;\n    }\n\n    if (!counter.has(indexString) && digit !== '0') {\n      return false;\n    }\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/check-if-numbers-are-ascending-in-a-sentence/check-if-numbers-are-ascending-in-a-sentence.js",
    "content": "function getNumbers(string) {\n  const tokens = string.split(' ');\n  const numbersStrings = tokens.filter((token) => !Number.isNaN(Number(token)));\n  return numbersStrings.map((numberString) => Number(numberString));\n}\n\nfunction isIncreasing(numbers) {\n  for (let index = 0; index < numbers.length - 1; index++) {\n    if (numbers[index + 1] <= numbers[index]) return false;\n  }\n\n  return true;\n}\n\nfunction areNumbersAscending(string) {\n  const numbers = getNumbers(string);\n  return isIncreasing(numbers);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/check-if-the-sentence-is-pangram/check-if-the-sentence-is-pangram.py",
    "content": "# https://leetcode.com/problems/check-if-the-sentence-is-pangram\n\ndef check_if_pangram(sentence):\n    if len(sentence) < 26: return False\n        \n    unique_chars = set()\n    \n    for char in sentence:\n        unique_chars.add(char)\n        \n    return len(unique_chars) == 26\n\ndef check_if_pangram(sentence):\n    return len(set(sentence)) == 26\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/check-whether-two-strings-are-almost-equivalent/check-whether-two-strings-are-almost-equivalent.js",
    "content": "function createCounter(word) {\n  const counter = new Map();\n\n  for (let char of word) {\n    if (counter.has(char)) counter.set(char, counter.get(char) + 1);\n    else counter.set(char, 1);\n  }\n\n  return counter;\n}\n\nfunction isSimilar(word, counter1, counter2) {\n  for (let char of word) {\n    const count1 = counter1.get(char);\n    const count2 = (counter2.has(char) && counter2.get(char)) || 0;\n    if (Math.abs(count1 - count2) > 3) return false;\n  }\n\n  return true;\n}\n\nfunction checkAlmostEquivalent(word1, word2) {\n  const word1Counter = createCounter(word1);\n  const word2Counter = createCounter(word2);\n  return (\n    isSimilar(word1, word1Counter, word2Counter) &&\n    isSimilar(word2, word2Counter, word1Counter)\n  );\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/check_if_all_characters_have_equal_number_of_occurrences/check_if_all_characters_have_equal_number_of_occurrences.js",
    "content": "// https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences\n\nconst areOccurrencesEqual = function (s) {\n  const counter = {};\n\n  for (let i = 0; i < s.length; i++) {\n    if (s[i] in counter) counter[s[i]]++;\n    else counter[s[i]] = 1;\n  }\n\n  return new Set(Object.values(counter)).size === 1;\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/check_if_two_string_arrays_are_equivalent/check_if_two_string_arrays_are_equivalent.py",
    "content": "# https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent\n\n\ndef array_strings_are_equal(word1, word2):\n    return ''.join(word1) == ''.join(word2)"
  },
  {
    "path": "coding_interviews/leetcode/easy/circular-sentence/circular-sentence.js",
    "content": "function isCircularSentence(sentence) {\n  const words = sentence.split(' ');\n  const lastWord = words[words.length - 1];\n  const lastCharEqualFirstChar = lastWord[lastWord.length - 1] === words[0][0];\n\n  if (!lastCharEqualFirstChar) return false;\n\n  for (let index = 0; index < words.length - 1; index++) {\n    const firstWord = words[index];\n    const nextWord = words[index + 1];\n    if (firstWord[firstWord.length - 1] !== nextWord[0]) return false;\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/climbing-stairs/climbing-stairs.js",
    "content": "function climbStairs(n) {\n  let memo = [0, 1, 2, 3];\n\n  for (let i = 4; i <= n; i++) {\n    memo.push(memo[i - 1] + memo[i - 2]);\n  }\n\n  return memo[n];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/climbing_stairs.py",
    "content": "# https://leetcode.com/problems/climbing-stairs/description/\n\ndef climb_stairs(n):\n    memo = [0, 1, 2, 3]\n\n    for i in range(4, n + 1):\n        memo.append(memo[i - 1] + memo[i - 2])\n\n    return memo[n]\n\nprint climb_stairs(1)\nprint climb_stairs(2)\nprint climb_stairs(3)\nprint climb_stairs(4)\nprint climb_stairs(5)\nprint climb_stairs(6)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/concatenation_of_array/concatenation_of_array.js",
    "content": "const getConcatenation = function (nums) {\n  nums.forEach((num) => nums.push(num));\n  return nums;\n};\n\nconst getConcatenation = function (nums) {\n  return [...nums, ...nums];\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/consecutive-characters/consecutive-characters.js",
    "content": "function maxPower(string) {\n  let power = 1;\n  let max = 1;\n  let currentChar = string[0];\n\n  for (let index = 1; index < string.length; index++) {\n    let char = string[index];\n\n    if (char === currentChar) max++;\n    if (char !== currentChar || index === string.length - 1) {\n      currentChar = char;\n      power = Math.max(max, power);\n      max = 1;\n    }\n  }\n\n  return power;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/construct-string-from-binary-tree/construct-string-from-binary-tree.js",
    "content": "// https://leetcode.com/problems/construct-string-from-binary-tree\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n\n// Time complexity : O(n). The preorder traversal is done over the n nodes of the given Binary Tree.\n// Space complexity : O(n). The depth of the recursion tree can go upto n in case of a skewed tree.\n\nfunction tree2str(root) {\n  if (!root) return '';\n\n  let left = tree2str(root.left);\n  let right = tree2str(root.right);\n\n  if (right) {\n    return `${root.val}(${left})(${right})`;\n  }\n\n  if (left) {\n    return `${root.val}(${left})`;\n  }\n\n  return root.val.toString();\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/contains-duplicate/contains-duplicate-hashmap.js",
    "content": "/*\nnums = [1,2,3,4,4]\nnumToCounter = {\n  1: 1,\n  2: 1,\n  3: 1,\n  4: 2\n}\n*/\n\nfunction containsDuplicate(nums) {\n  let numToCounter = {};\n  let appearsAtLeastTwice = false;\n\n  for (let num of nums) {\n    if (numToCounter[num]) {\n      numToCounter[num]++;\n    } else {\n      numToCounter[num] = 1;\n    }\n  }\n\n  Object.values(numToCounter).forEach((num) => {\n    if (num >= 2) {\n      appearsAtLeastTwice = true;\n    }\n  });\n\n  return appearsAtLeastTwice;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/contains-duplicate/contains-duplicate.js",
    "content": "function containsDuplicate(nums) {\n  return !(nums.length === new Set(nums).size);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/contains-duplicate/contains-duplicate.py",
    "content": "# https://leetcode.com/problems/contains-duplicate-ii\n\ndef contains_nearby_duplicate(nums, k):\n    for index in range(len(nums)):\n        for comp_index in range(len(nums)):\n            if index != comp_index and nums[index] == nums[comp_index] and abs(comp_index - index) <= k:\n                return True\n    return False\n\n\ndef contains_nearby_duplicate(nums, k):\n    index_mapper = {}\n\n    for index, num in enumerate(nums):\n        if num in index_mapper and index - index_mapper[num] <= k: return True\n        index_mapper[num] = index\n\n    return False"
  },
  {
    "path": "coding_interviews/leetcode/easy/convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.js",
    "content": "function sortedArrayToBST(nums) {\n  if (nums.length === 0) return null;\n\n  const middle = Math.floor(nums.length / 2);\n  const num = nums[middle];\n  const node = new TreeNode(num);\n\n  node.left = sortedArrayToBST(nums.slice(0, middle));\n  node.right = sortedArrayToBST(nums.slice(middle + 1, nums.length));\n\n  return node;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/convert-the-temperature/convert-the-temperature.js",
    "content": "function convertTemperature(celsius) {\n  return [celsius + 273.15, celsius * 1.8 + 32.0];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-asterisks/count-asterisks.js",
    "content": "function toggleCanCount(canCount) {\n  return !canCount;\n}\n\nfunction countAsterisks(s) {\n  let asteristics = 0;\n  let canCount = true;\n\n  for (let char of s) {\n    if (canCount && char === '*') {\n      asteristics++;\n    }\n\n    if (char === '|') {\n      canCount = toggleCanCount(canCount);\n    }\n  }\n\n  return asteristics;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-common-words-with-one-occurrence/count-common-words-with-one-occurrence.js",
    "content": "function buildHashmap(words) {\n  let hashmap = new Map();\n\n  for (let word of words) {\n    if (hashmap.has(word)) {\n      hashmap.set(word, hashmap.get(word) + 1);\n    } else {\n      hashmap.set(word, 1);\n    }\n  }\n\n  return hashmap;\n}\n\nfunction countWords(words1, words2) {\n  let words1Counter = buildHashmap(words1);\n  let words2Counter = buildHashmap(words2);\n  let words = 0;\n\n  for (let [word, counter] of words1Counter) {\n    if (\n      counter === 1 &&\n      words2Counter.has(word) &&\n      words2Counter.get(word) === 1\n    ) {\n      words++;\n    }\n  }\n\n  return words;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-complete-tree-nodes/count-complete-tree-nodes.js",
    "content": "// https://leetcode.com/problems/count-complete-tree-nodes\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\nfunction countNodes(node) {\n  return node ? 1 + countNodes(node.left) + countNodes(node.right) : 0;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-equal-and-divisible-pairs-in-an-array/count-equal-and-divisible-pairs-in-an-array-2.js",
    "content": "/*\nlist = [3, 1, 2, 2, 2, 1, 3]\n\ndata structure\n{\n  3: [0, 6],\n  1: [1, 5],\n  2: [2, 3, 4]\n}\n\nworst case scenario\n{\n  x: [0, 1, 2, 3, ..., 100]\n}\n*/\n\nexport function countPairs(numbers, k) {\n  let counter = 0;\n\n  for (let i = 0; i < numbers.length - 1; i++) {\n    for (let j = i + 1; j < numbers.length; j++) {\n      if (numbers[i] === numbers[j] && (i * j) % k === 0) {\n        counter++;\n      }\n    }\n  }\n\n  return counter;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-equal-and-divisible-pairs-in-an-array/count-equal-and-divisible-pairs-in-an-array.js",
    "content": "/*\nlist = [3, 1, 2, 2, 2, 1, 3]\n\ndata structure\n{\n  3: [0, 6],\n  1: [1, 5],\n  2: [2, 3, 4]\n}\n\nworst case scenario\n{\n  x: [0, 1, 2, 3, ..., 100]\n}\n*/\n\nexport function countPairs(numbers, k) {\n  const numberToIndices = {};\n\n  numbers.forEach((number, index) => {\n    if (number in numberToIndices) {\n      numberToIndices[number].push(index);\n    } else {\n      numberToIndices[number] = [index];\n    }\n  });\n\n  let counter = 0;\n\n  Object.values(numberToIndices).forEach((indices) => {\n    for (let i = 0; i < indices.length - 1; i++) {\n      for (let j = i + 1; j < indices.length; j++) {\n        if ((indices[i] * indices[j]) % k === 0) {\n          counter++;\n        }\n      }\n    }\n  });\n\n  return counter;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-equal-and-divisible-pairs-in-an-array/tests/count-equal-and-divisible-pairs-in-an-array-2.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { countPairs } from '../count-equal-and-divisible-pairs-in-an-array-2';\n\ndescribe('countPairs', () => {\n  it('', () => {\n    expect(countPairs([3, 1, 2, 2, 2, 1, 3], 2)).toEqual(4);\n  });\n\n  it('', () => {\n    expect(countPairs([1, 2, 3, 4], 1)).toEqual(0);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-equal-and-divisible-pairs-in-an-array/tests/count-equal-and-divisible-pairs-in-an-array.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { countPairs } from '../count-equal-and-divisible-pairs-in-an-array';\n\ndescribe('countPairs', () => {\n  it('', () => {\n    expect(countPairs([3, 1, 2, 2, 2, 1, 3], 2)).toEqual(4);\n  });\n\n  it('', () => {\n    expect(countPairs([1, 2, 3, 4], 1)).toEqual(0);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-good-triplets/count-good-triplets.py",
    "content": "# https://leetcode.com/problems/count-good-triplets\n\n'''\nTime Complexity: O(N^3)\nSpace Complexity: O(1) - no extra space rather than the input\n'''\n\ndef count_good_triplets(arr, a, b, c):\n    counter = 0\n    \n    for i in range(len(arr)):\n        for j in range(i+1, len(arr)):\n            for k in range(j+1, len(arr)):\n                if abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c:\n                    counter += 1\n                    \n    return counter\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-integers-with-even-digit-sum/count-integers-with-even-digit-sum.js",
    "content": "function sumDigits(numString) {\n  let sum = 0;\n\n  for (let digit of numString) {\n    sum += Number(digit);\n  }\n\n  return sum;\n}\n\nfunction isEven(num) {\n  return num % 2 === 0;\n}\n\nfunction countEven(num) {\n  let counter = 0;\n\n  for (let number = 1; number <= num; number++) {\n    let numString = number.toString();\n    let digitSum = sumDigits(numString);\n    if (isEven(digitSum)) counter++;\n  }\n\n  return counter;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-k-difference/count-k-difference.js",
    "content": "/*\nGiven an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k.\n\nThe value of |x| is defined as:\n\nx if x >= 0.\n-x if x < 0.\n \nExample 1:\nInput: nums = [1,2,2,1], k = 1\nOutput: 4\nExplanation: The pairs with an absolute difference of 1 are:\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]\n\nExample 2:\nInput: nums = [1,3], k = 3\nOutput: 0\nExplanation: There are no pairs with an absolute difference of 3.\n\nExample 3:\nInput: nums = [3,2,1,5,4], k = 2\nOutput: 3\nExplanation: The pairs with an absolute difference of 2 are:\n- [3,2,1,5,4]\n- [3,2,1,5,4]\n- [3,2,1,5,4]\n*/\n\nfunction countKDifference(nums, k) {\n  const numsMap = {};\n\n  nums.forEach((num) => {\n    if (num in numsMap) numsMap[num] += 1;\n    else numsMap[num] = 1;\n  });\n\n  let count = 0;\n\n  nums.forEach((num) => {\n    const rest = num + k;\n\n    if (rest in numsMap) {\n      count += numsMap[rest];\n    }\n  });\n\n  return count;\n}\n\nconsole.log(countKDifference([1, 2, 2, 1], 1), 4);\nconsole.log(countKDifference([1, 3], 3), 0);\nconsole.log(countKDifference([3, 2, 1, 5, 4], 2), 3);\nconsole.log(countKDifference([7, 10, 10, 6, 10, 1, 9, 10, 4, 9], 7), 0);\nconsole.log(countKDifference([2, 3, 2, 10, 3, 9, 4, 9, 5, 8], 1), 11);\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-largest-group/count-largest-group.js",
    "content": "// https://leetcode.com/problems/count-largest-group\n\nfunction sumDigits(num) {\n  let numString = num.toString();\n  let sum = 0;\n\n  for (let digit of numString) {\n    sum += Number(digit);\n  }\n\n  return sum;\n}\n\nfunction countLargestGroup(n) {\n  let hashmap = new Map();\n\n  for (let num = 1; num <= n; num++) {\n    let sum = sumDigits(num);\n    if (hashmap.has(sum)) hashmap.set(sum, [...hashmap.get(sum), num]);\n    else hashmap.set(sum, [num]);\n  }\n\n  let largest = -Infinity;\n\n  for (let [_, values] of hashmap.entries()) {\n    largest = Math.max(largest, values.length);\n  }\n\n  let size = 0;\n\n  for (let [_, values] of hashmap.entries()) {\n    if (values.length === largest) size++;\n  }\n\n  return size;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-operations-to-obtain-zero/count-operations-to-obtain-zero.js",
    "content": "export function countOperations(num1, num2) {\n  let counter = 0;\n\n  while (num1 > 0 && num2 > 0) {\n    if (num1 >= num2) {\n      num1 -= num2;\n    } else {\n      num2 -= num1;\n    }\n\n    counter++;\n  }\n\n  return counter;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-operations-to-obtain-zero/tests/count-operations-to-obtain-zero.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { countOperations } from '../count-operations-to-obtain-zero';\n\ndescribe('countOperations', () => {\n  it('', () => {\n    expect(countOperations(2, 3)).toEqual(3);\n  });\n\n  it('', () => {\n    expect(countOperations(10, 10)).toEqual(1);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-pairs-of-similar-strings/count-pairs-of-similar-strings.js",
    "content": "function buildCharsMap(word) {\n  const map = new Map();\n\n  for (let char of word) {\n    if (map.has(char)) map.set(char, map.get(char) + 1);\n    else map.set(char, 1);\n  }\n\n  return map;\n}\n\nfunction hasAllChars(word, charsMap) {\n  for (let char of word) {\n    if (!charsMap.has(char)) return false;\n  }\n\n  return true;\n}\n\nfunction isSimilar(word1, word2) {\n  const word1CharsMap = buildCharsMap(word1);\n  const word2CharsMap = buildCharsMap(word2);\n  return hasAllChars(word1, word2CharsMap) && hasAllChars(word2, word1CharsMap);\n}\n\nfunction similarPairs(words) {\n  let count = 0;\n\n  for (let i = 0; i < words.length - 1; i++) {\n    for (let j = i + 1; j < words.length; j++) {\n      if (isSimilar(words[i], words[j])) count++;\n    }\n  }\n\n  return count;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-pairs-whose-sum-is-less-than-target/count-pairs-whose-sum-is-less-than-target-two-pointers.js",
    "content": "// https://leetcode.com/problems/count-pairs-whose-sum-is-less-than-target\n\nfunction countPairs(nums, target) {\n  nums.sort((num1, num2) => num1 - num2);\n  let counter = 0;\n  let start = 0;\n  let end = nums.length - 1;\n\n  while (start < end) {\n    if (nums[start] + nums[end] < target) {\n      counter += end - start;\n      start++;\n    } else {\n      end--;\n    }\n  }\n\n  return counter;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-pairs-whose-sum-is-less-than-target/count-pairs-whose-sum-is-less-than-target.js",
    "content": "// https://leetcode.com/problems/count-pairs-whose-sum-is-less-than-target\n\nfunction countPairs(nums, target) {\n  let counter = 0;\n\n  for (let i = 0; i < nums.length; i++) {\n    for (let j = i + 1; j < nums.length; j++) {\n      if (nums[i] + nums[j] < target) counter++;\n    }\n  }\n\n  return counter;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-prefixes-of-a-given-string/count-prefixes-of-a-given-string.js",
    "content": "function hasPrefix(word, s) {\n  for (let index = 0; index < word.length; index++) {\n    if (word[index] !== s[index]) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nfunction countPrefixes(words, s) {\n  let counter = 0;\n\n  for (let word of words) {\n    if (word.length <= s.length && hasPrefix(word, s)) {\n      counter++;\n    }\n  }\n\n  return counter;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-square-sum-triples/count-square-sum-triples.js",
    "content": "function countTriples(n) {\n  let hashmap = new Map();\n  let counter = 0;\n\n  for (let num = 1; num <= n; num++) {\n    hashmap.set(num * num, num);\n  }\n\n  for (let a = 1; a <= n; a++) {\n    for (let b = 1; b <= n; b++) {\n      const c = a * a + b * b;\n\n      if (hashmap.has(c)) {\n        counter++;\n      }\n    }\n  }\n\n  return counter;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-symmetric-integers/count-symmetric-integers.js",
    "content": "// https://leetcode.com/problems/count-symmetric-integers\n\nfunction isSymmetricIntegers(num) {\n  let numString = num.toString();\n\n  if (numString.length % 2 !== 0) return false;\n\n  let firstHalfSum = 0;\n  let lastHalfSum = 0;\n\n  for (let index = 0; index < numString.length; index++) {\n    let digit = numString[index];\n    if (index < numString.length / 2) firstHalfSum += Number(digit);\n    else lastHalfSum += Number(digit);\n  }\n\n  return firstHalfSum === lastHalfSum;\n}\n\nfunction countSymmetricIntegers(low, high) {\n  let count = 0;\n\n  for (let num = low; num <= high; num++) {\n    if (isSymmetricIntegers(num)) {\n      count++;\n    }\n  }\n\n  return count;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-the-digits-that-divide-a-number/count-the-digits-that-divide-a-number.js",
    "content": "function countDigits(num) {\n  let digitsCount = 0;\n  let numString = num.toString();\n\n  for (let numChar of numString) {\n    if (num % Number(numChar) === 0) digitsCount++;\n  }\n\n  return digitsCount;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-the-number-of-vowel-strings-in-range/count-the-number-of-vowel-strings-in-range.js",
    "content": "const VOWELS = ['a', 'e', 'i', 'o', 'u'];\n\nfunction isVowelString(string) {\n  return (\n    VOWELS.includes(string[0]) && VOWELS.includes(string[string.length - 1])\n  );\n}\n\nfunction vowelStrings(words, left, right) {\n  let vowelsStrings = 0;\n\n  for (let index = left; index <= right; index++) {\n    if (isVowelString(words[index])) {\n      vowelsStrings++;\n    }\n  }\n\n  return vowelsStrings;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count-vowel-substrings-of-a-string/count-vowel-substrings-of-a-string.js",
    "content": "const VOWELS = ['a', 'e', 'i', 'o', 'u'];\n\nfunction isVowel(char) {\n  return VOWELS.includes(char);\n}\n\nfunction hasAllVowels(foundVowels) {\n  return (\n    foundVowels.has('a') &&\n    foundVowels.has('e') &&\n    foundVowels.has('i') &&\n    foundVowels.has('o') &&\n    foundVowels.has('u')\n  );\n}\n\nfunction countVowelSubstrings(word) {\n  let vowelSubstringCount = 0;\n\n  for (let i = 0; i < word.length - 4; i++) {\n    if (!isVowel(word[i])) continue;\n\n    const foundVowels = new Map();\n    foundVowels.set(word[i], 1);\n\n    for (let index = i + 1; index < word.length; index++) {\n      const char = word[index];\n      if (!isVowel(char)) break;\n      if (foundVowels.has(char))\n        foundVowels.set(char, foundVowels.get(char) + 1);\n      else foundVowels.set(char, 1);\n      if (hasAllVowels(foundVowels)) vowelSubstringCount++;\n    }\n  }\n\n  return vowelSubstringCount;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count_good_rectangles/count_good_rectangles.py",
    "content": "# https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square\n\n'''\nTime Complexity: O(N)\nSpace Complexity: O(N)\n'''\n\ndef count_good_rectangles(rectangles):\n    max_len, all_max_lens = 0, []\n    \n    for rec in rectangles:\n        square_len = min(rec[0], rec[1])\n        max_len = max(max_len, square_len)\n        all_max_lens.append(square_len)\n        \n    counter = 0\n\n    for length in all_max_lens:\n        if length == max_len:\n            counter += 1\n            \n    return counter\n\n\ndef count_good_rectangles_optimized(rectangles):\n    max_len, counter = 0, 0\n        \n    for rec in rectangles:\n        square_len = min(rec[0], rec[1])\n        \n        if square_len > max_len:\n            max_len = square_len\n            counter = 0\n            \n        if square_len == max_len:                \n            counter += 1\n\n    return counter"
  },
  {
    "path": "coding_interviews/leetcode/easy/count_matches/count_matches.py",
    "content": "# https://leetcode.com/problems/count-items-matching-a-rule\n\ndef count_matches(items, ruleKey, ruleValue):\n    counter = 0\n\n    for item in items:\n        if ruleKey == 'type' and item[0] == ruleValue: counter += 1\n        if ruleKey == 'color' and item[1] == ruleValue: counter += 1\n        if ruleKey == 'name' and item[2] == ruleValue: counter += 1\n    \n    return counter\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count_of_matches_in_tournament/count_of_matches_in_tournament.py",
    "content": "# https://leetcode.com/problems/count-of-matches-in-tournament\n'''\nRuntime: O(N)\nSpace: O(1)\n'''\n\n\ndef number_of_matches(n):\n    if n <= 0:\n        return 0\n\n    number_of_games = 0\n\n    while n > 1:\n        games = n // 2\n        number_of_games += games\n\n        if n % 2 == 0:\n            n = games\n        else:\n            n = games + 1\n\n    return number_of_games\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/count_students/count_students.py",
    "content": "# https://leetcode.com/problems/number-of-students-unable-to-eat-lunch\n\ndef is_empty(arr):\n    return len(arr) == 0\n    \ndef count_students(students, sandwiches):\n    preferred_circles = 0\n    preferred_squares = 0\n    \n    for student in students:\n        if student:\n            preferred_squares += 1\n        else:\n            preferred_circles += 1\n            \n    while not is_empty(students) and not is_empty(sandwiches):\n        if students[0] == sandwiches[0]:\n            if students[0]:\n                preferred_squares -= 1\n            else:\n                preferred_circles -= 1\n            \n            del students[0]\n            del sandwiches[0]\n        else:\n            students.append(students[0])\n            del students[0]\n            \n        if not is_empty(sandwiches) and (sandwiches[0] and preferred_squares == 0 or sandwiches[0] == 0 and preferred_circles == 0):\n            break\n            \n    return len(students)\n\n\n\ndef count_students(students, sandwiches):\n    preferences = [0, 0]\n        \n    for student in students:\n        preferences[student] += 1\n\n    index = 0\n\n    while index < len(students):\n        if preferences[sandwiches[index]] > 0:\n            preferences[sandwiches[index]] -= 1\n        else:\n            break\n            \n        index += 1\n\n    return len(students) - index"
  },
  {
    "path": "coding_interviews/leetcode/easy/count_the_number_of_consistent_strings/count_the_number_of_consistent_strings.py",
    "content": "# https://leetcode.com/problems/count-the-number-of-consistent-strings\n\n'''\nTime complexity: O(WN), where W = number of words and N = number of character of the longest string\nSpace complexity: O(N)\n'''\n\ndef count_consistent_strings(allowed, words):\n    allowed_mapper = {}\n    \n    for char in allowed:\n        allowed_mapper[char] = True\n        \n    counter = 0\n    \n    for word in words:\n        all_chars_allowed = True\n        \n        for char in word:\n            if char not in allowed_mapper:\n                all_chars_allowed = False\n                break\n        \n        if all_chars_allowed:\n            counter += 1\n            \n    return counter\n\n'''\nTime complexity: O(WNA), where W = number of words and N = number of character of the longest string, and A = length of the allowed string\nSpace complexity: O(1)\n'''\n\ndef count_consistent_strings(allowed, words):\n    counter = 0\n\n    for word in words:\n        counter += 1\n\n        for char in word:\n            if char not in allowed:\n                counter -= 1\n                break\n\n    return counter\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/counting-bits/counting-bits.js",
    "content": "function countOnesInBinaryTransformation(number) {\n  let counter = 0;\n\n  while (number) {\n    let remainder = number % 2;\n    if (remainder) counter++;\n    number = Math.floor(number / 2);\n  }\n\n  return counter;\n}\n\nfunction countBits(n) {\n  let answer = [];\n\n  for (let num = 0; num <= n; num++) {\n    answer.push(countOnesInBinaryTransformation(num));\n  }\n\n  return answer;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/counting-words-with-a-given-prefix/counting-words-with-a-given-prefix.js",
    "content": "function hasPrefix(word, pref) {\n  if (pref.length > word.length) {\n    return false;\n  }\n\n  let matchesPrefix = true;\n\n  for (let i = 0; i < pref.length; i++) {\n    if (word[i] !== pref[i]) {\n      matchesPrefix = false;\n      break;\n    }\n  }\n\n  return matchesPrefix;\n}\n\nexport function prefixCount(words, pref) {\n  let count = 0;\n\n  words.forEach((word) => {\n    if (hasPrefix(word, pref)) {\n      count++;\n    }\n  });\n\n  return count;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/counting-words-with-a-given-prefix/tests/counting-words-with-a-given-prefix.test.js",
    "content": "import { describe, it, expect } from 'vitest';\nimport { prefixCount } from '../counting-words-with-a-given-prefix';\n\ndescribe('prefixCount', () => {\n  it('matches 2 words', () => {\n    expect(\n      prefixCount(['pay', 'attention', 'practice', 'attend'], 'at')\n    ).toEqual(2);\n  });\n\n  it('matches 3 words', () => {\n    expect(\n      prefixCount(['pay', 'attention', 'practice', 'attend', 'at'], 'at')\n    ).toEqual(3);\n  });\n\n  it('matches no word', () => {\n    expect(\n      prefixCount(['leetcode', 'win', 'loops', 'success'], 'code')\n    ).toEqual(0);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/crawler-log-folder/crawler-log-folder.js",
    "content": "function minOperations(logs) {\n  let fileLevel = 0;\n\n  for (let log of logs) {\n    if (log === '../' && fileLevel) fileLevel--;\n    else if (log === '../') {\n    } else if (log === './') {\n    } else fileLevel++;\n  }\n\n  return Math.abs(fileLevel);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/create_target_array/create_target_array.py",
    "content": "# https://leetcode.com/problems/create-target-array-in-the-given-order/\n\n\ndef createTargetArray(nums, index):\n    target = []\n\n    for i in range(len(nums)):\n        target.insert(index[i], nums[i])\n\n    return target\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/decode-the-message/decode-the-message.js",
    "content": "export function decodeMessage(key, message) {\n  let hashmap = new Map();\n  let alphabet = 'abcdefghijklmnopqrstuvwxyz';\n  let counter = 0;\n\n  hashmap.set(' ', ' ');\n\n  for (let char of key) {\n    if (!hashmap.has(char)) {\n      hashmap.set(char, alphabet[counter]);\n      counter++;\n    }\n  }\n\n  let result = [];\n\n  for (let char of message) {\n    result.push(hashmap.get(char));\n  }\n\n  return result.join('');\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/decode-the-message/tests/decode-the-message.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { decodeMessage } from '../decode-the-message';\n\ndescribe('decodeMessage', () => {\n  it('', () => {\n    expect(\n      decodeMessage(\n        'eljuxhpwnyrdgtqkviszcfmabo',\n        'zwx hnfx lqantp mnoeius ycgk vcnjrdb'\n      )\n    ).toEqual('the five boxing wizards jump quickly');\n  });\n\n  it('', () => {\n    expect(\n      decodeMessage(\n        'the quick brown fox jumps over the lazy dog',\n        'vkbs bs t suepuv'\n      )\n    ).toEqual('this is a secret');\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/decode_xored_array/decode_xored_array.py",
    "content": "# https://leetcode.com/problems/decode-xored-array\n\ndef decode(encoded, first):\n    original = [first]\n    \n    for num in encoded:\n        original.append(original[-1] ^ num)\n        \n    return original\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/decompressed_encoded_list/decompressed_encoded_list.py",
    "content": "# https://leetcode.com/problems/decompress-run-length-encoded-list\n\n'''\nWe are given a list nums of integers representing a list compressed with run-length encoding.\n\nConsider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0).  For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.\n\nReturn the decompressed list.\n\nInput: nums = [1,2,3,4]\nOutput: [2,4,4,4]\n\nInput: nums = [1,1,2,3]\nOutput: [1,3,3]\n'''\n\n\ndef build_frequencies(frequency, num):\n    return [num for i in range(frequency)]\n\n\ndef decompress_list(nums):\n    result_list = []\n\n    for index in range(0, len(nums), 2):\n        result_list += build_frequencies(nums[index], nums[index+1])\n\n    return result_list\n\n\ndata_tests = [\n    ([1, 2, 3, 4], [2, 4, 4, 4]),\n    ([1, 1, 2, 3], [1, 3, 3])\n]\n\n\nfor nums, expected in data_tests:\n    result = decompress_list(nums)\n    print(result, result == expected)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/decrypt_string/decrypt_string.py",
    "content": "# https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping\n\ndef alpha(num):\n    return chr(int(num) + ord('a') - 1)\n\ndef freqAlphabets(s):\n    result, index, s_length = [], 0, len(s)\n\n    while index < s_length:\n        if index + 2 < len(s) and s[index + 2] == '#':\n            result.append(alpha(s[index:index+2]))\n            index += 3\n        else:\n            result.append(alpha(s[index]))\n            index += 1\n\n    return ''.join(result)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/defanging_an_ip_address/defanging_an_ip_address.py",
    "content": "# https://leetcode.com/problems/defanging-an-ip-address/\n\n'''\n\"1.1.1.1\"\n\"1[.]1[.]1[.]1\"\n\n\"255.100.50.0\"\n\"255[.]100[.]50[.]0\"\n'''\n\n\ndef defang_ip_address(address):\n    address_chars_list = []\n\n    for char in address:\n        if char == '.':\n            address_chars_list.append('[.]')\n        else:\n            address_chars_list.append(char)\n\n    return ''.join(address_chars_list)\n\n\ndata_tests = [\n    (\"1.1.1.1\", \"1[.]1[.]1[.]1\"),\n    (\"255.100.50.0\", \"255[.]100[.]50[.]0\")\n]\n\nfor address, expected in data_tests:\n    result = defang_ip_address(address)\n    print(result, result == expected)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/defuse-the-bomb/defuse-the-bomb.js",
    "content": "function sumNextK(code, from, k) {\n  let sum = 0;\n\n  for (let index = from + 1; index <= from + k; index++) {\n    sum += code[index];\n  }\n\n  return sum;\n}\n\nfunction decryptNext(code, k) {\n  let newCode = [...code, ...code];\n  let sum = sumNextK(newCode, 0, k);\n  let nextSum = [sum];\n\n  for (let index = 1; index < code.length; index++) {\n    sum = sum - newCode[index] + newCode[index + k];\n    nextSum.push(sum);\n  }\n\n  return nextSum;\n}\n\nfunction sumPreviousK(code, from, k) {\n  let sum = 0;\n\n  for (let index = from - 1; index >= from - k; index--) {\n    sum += code[index];\n  }\n\n  return sum;\n}\n\nfunction decryptPrevious(code, k) {\n  let newCode = [...code, ...code];\n  let sum = sumPreviousK(code, code.length - 1, k);\n  let previousSum = [sum];\n\n  for (let index = newCode.length - 2; index >= code.length; index--) {\n    sum = sum - newCode[index] + newCode[index - k];\n    previousSum.push(sum);\n  }\n\n  return previousSum.reverse();\n}\n\nfunction decryptWithZeros(code) {\n  return code.map((_) => 0);\n}\n\nfunction decrypt(code, k) {\n  if (k > 0) return decryptNext(code, k);\n  if (k < 0) return decryptPrevious(code, k * -1);\n  return decryptWithZeros(code);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/delete-greatest-value-in-each-row/delete-greatest-value-in-each-row.js",
    "content": "function isEmpty(grid) {\n  let lastRow = grid[grid.length - 1];\n\n  for (let col = 0; col < grid[0].length; col++) {\n    if (lastRow[col] !== 0) return false;\n  }\n\n  return true;\n}\n\nfunction deleteGreatestValue(grid) {\n  let result = 0;\n\n  while (!isEmpty(grid)) {\n    let max = -Infinity;\n\n    for (let row = 0; row < grid.length; row++) {\n      let maxCell = -Infinity;\n      let maxCol = -Infinity;\n\n      for (let col = 0; col < grid[row].length; col++) {\n        const cell = grid[row][col];\n\n        if (cell > maxCell) {\n          maxCell = Math.max(cell, maxCell);\n          maxCol = col;\n        }\n      }\n\n      max = Math.max(maxCell, max);\n      grid[row][maxCol] = 0;\n    }\n\n    result += max;\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/delete_columns_to_make_sorted/delete_columns_to_make_sorted.py",
    "content": "# https://leetcode.com/problems/delete-columns-to-make-sorted\n\ndef min_deletion_size(strs):\n    counter = 0\n\n    for col in range(len(strs[0])):\n        column = []\n        \n        for row in range(len(strs)):\n            column.append(strs[row][col])\n\n        if column != sorted(column): counter += 1\n            \n    return counter\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/design-an-ordered-stream/design-an-ordered-stream.js",
    "content": "const OrderedStream = function (n) {\n  this.n = n;\n  this.key = 1;\n  this.hashmap = new Map();\n};\n\nOrderedStream.prototype.insert = function (idKey, value) {\n  this.hashmap.set(idKey, value);\n\n  if (this.key === idKey) {\n    const chunk = [];\n\n    for (let index = this.key; index <= this.n + 1; index++) {\n      if (this.hashmap.has(index)) {\n        const value = this.hashmap.get(index);\n        chunk.push(value);\n        this.hashmap.delete(index);\n        this.key++;\n      } else {\n        return chunk;\n      }\n    }\n  }\n\n  return [];\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/design-hashmap/design-hashmap.js",
    "content": "const MyHashMap = function () {\n  this.map = [];\n};\n\nMyHashMap.prototype.put = function (key, value) {\n  let found = false;\n\n  this.map.forEach(([k], index) => {\n    if (key === k) {\n      this.map[index] = [key, value];\n      found = true;\n    }\n  });\n\n  if (!found) this.map.push([key, value]);\n};\n\nMyHashMap.prototype.get = function (key) {\n  let value = -1;\n\n  this.map.forEach(([k, v]) => {\n    if (key === k) {\n      value = v;\n    }\n  });\n\n  return value;\n};\n\nMyHashMap.prototype.remove = function (key) {\n  this.map.forEach(([k], index) => {\n    if (key === k) {\n      this.map = [...this.map.slice(0, index), ...this.map.slice(index + 1)];\n    }\n  });\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/design-hashset/design-hashset.js",
    "content": "const MyHashSet = function () {\n  this.hashmap = new Map();\n};\n\nMyHashSet.prototype.add = function (key) {\n  this.hashmap.set(key, true);\n};\n\nMyHashSet.prototype.remove = function (key) {\n  this.hashmap.delete(key);\n};\n\nMyHashSet.prototype.contains = function (key) {\n  return this.hashmap.has(key);\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/design_parking_system/design_parking_system.py",
    "content": "# https://leetcode.com/problems/design-parking-system\n\nclass ParkingSystem:\n    def __init__(self, big, medium, small):\n        self.big = big\n        self.medium = medium\n        self.small = small\n\n    def add_car(self, car_type):\n        if car_type == 1:\n            if self.big >= 1:\n                self.big -= 1\n                return True\n            else:\n                return False\n        \n        if car_type == 2:\n            if self.medium >= 1:\n                self.medium -= 1\n                return True\n            else:\n                return False\n        \n        if car_type == 3:\n            if self.small >= 1:\n                self.small -= 1\n                return True\n            else:\n                return False\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/destination_city/destination_city.py",
    "content": "def dest_city(paths):\n    all_origins = []\n    all_destinations = []\n\n    for [city1, city2] in paths:\n        all_origins.append(city1)\n        all_destinations.append(city2)\n\n    return [d for d in all_destinations if d not in all_origins][0]\n\n\ndef dest_city(paths):\n    all_origins = set()\n    all_destinations = set()\n\n    for [city1, city2] in paths:\n        all_origins.add(city1)\n        all_destinations.add(city2)\n\n    return (all_destinations - all_origins).pop()\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/detect-capital/detect-capital.js",
    "content": "function allCapitals(word) {\n  return word === word.toUpperCase();\n}\n\nfunction allNotCapitals(word) {\n  return word === word.toLowerCase();\n}\n\nfunction firstCapital(word) {\n  return allCapitals(word[0]) && allNotCapitals(word.slice(1));\n}\n\nfunction detectCapitalUse(word) {\n  return allCapitals(word) || allNotCapitals(word) || firstCapital(word);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/determine-if-string-halves-are-alike/determine-if-string-halves-are-alike.js",
    "content": "const VOWELS = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];\n\nfunction getVowelsCount(string) {\n  let count = 0;\n\n  for (let char of string) {\n    if (VOWELS.includes(char)) count++;\n  }\n\n  return count;\n}\n\nfunction halvesAreAlike(s) {\n  let halfIndex = s.length / 2;\n  let firstHalf = s.slice(0, halfIndex);\n  let secondHalf = s.slice(halfIndex);\n  let firstHalfVowelsCount = getVowelsCount(firstHalf);\n  let secondHalfVowelsCount = getVowelsCount(secondHalf);\n\n  return firstHalfVowelsCount === secondHalfVowelsCount;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/determine_color_of_a_chessboard_square/determine_color_of_a_chessboard_square.py",
    "content": "# https://leetcode.com/problems/determine-color-of-a-chessboard-square/\n\nmapper = {\n    'a': 1,\n    'b': 2,\n    'c': 3,\n    'd': 4,\n    'e': 5,\n    'f': 6,\n    'g': 7,\n    'h': 8\n}\n\ndef is_even(num):\n    return num % 2 == 0\n\ndef square_is_white(coordinates):\n    x, y = mapper[coordinates[0]], int(coordinates[1])\n    if x == y or (is_even(x - y)): return False\n    return True\n\ndef square_is_white(coordinates):\n    x, y = mapper[coordinates[0]], int(coordinates[1])\n    return not (x == y or (is_even(x - y)))\n\ndef square_is_white(coordinates):\n    return ord(coordinates[0]) % 2 != int(coordinates[1]) % 2\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/di_string_match/di_string_match.py",
    "content": "# https://leetcode.com/problems/di-string-match\n\ndef di_string_match(S):\n    permutation, top, bottom = [], len(S), 0\n\n    for char in S:\n        if char == 'I':\n            permutation.append(bottom)\n            bottom += 1\n        else:\n            permutation.append(top)\n            top -= 1\n            \n    permutation.append(top)\n    return permutation\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/difference-between-element-sum-and-digit-sum-of-an-array/difference-between-element-sum-and-digit-sum-of-an-array.js",
    "content": "function getDigitsSum(num) {\n  let digits = 0;\n  let numString = num.toString();\n\n  for (let numChar of numString) {\n    digits += Number(numChar);\n  }\n\n  return digits;\n}\n\nfunction differenceOfSum(nums) {\n  let elementSum = 0;\n  let digitSum = 0;\n\n  for (let num of nums) {\n    elementSum += num;\n    digitSum += getDigitsSum(num);\n  }\n\n  return Math.abs(elementSum - digitSum);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/discount_price/discount_price.py",
    "content": "def finalPrices(prices):\n    result = []\n\n    for index, price in enumerate(prices):\n        discount = get_discount(prices, index, price)\n        result.append(price - discount)\n\n    return result\n\n\ndef get_discount(prices, index, price):\n    for other_price in prices[index + 1:]:\n        if other_price <= price:\n            return other_price\n\n    return 0\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/distribute-candies-among-children-i/distribute-candies-among-children-i.js",
    "content": "// https://leetcode.com/problems/distribute-candies-among-children-i\n\nfunction distributeCandies(n, limit) {\n  let count = 0;\n\n  for (let i = limit; i >= 0; i--) {\n    for (let j = limit; j >= 0; j--) {\n      for (let k = limit; k >= 0; k--) {\n        if (i + j + k === n) {\n          count++;\n        }\n      }\n    }\n  }\n\n  return count;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/distribute-candies-among-children-i/distribute-candies-among-children-ii.js",
    "content": "// https://leetcode.com/problems/distribute-candies-among-children-i\n\nfunction distributeCandies(n, limit) {\n  let count = 0;\n\n  for (let i = limit; i >= 0; i--) {\n    for (let j = limit; j >= 0; j--) {\n      let k = n - i - j;\n      if (k >= 0 && k <= limit) {\n        count++;\n      }\n    }\n  }\n\n  return count;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/distribute-candies-to-people/distribute-candies-to-people.js",
    "content": "function initPeopleCandies(numPeople) {\n  let peopleCandies = [];\n\n  for (let i = 0; i < numPeople; i++) {\n    peopleCandies.push(0);\n  }\n\n  return peopleCandies;\n}\n\nfunction distributeCandies(candies, numPeople) {\n  let peopleCandies = initPeopleCandies(numPeople);\n  let numOfCandies = 1;\n  let index = 0;\n\n  while (candies) {\n    let candiesToAssign = numOfCandies > candies ? candies : numOfCandies;\n    peopleCandies[index] += candiesToAssign;\n    candies -= candiesToAssign;\n    numOfCandies++;\n    index = (index + 1) % numPeople;\n  }\n\n  return peopleCandies;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/divide-a-string-into-groups-of-size-k/divide-a-string-into-groups-of-size-k.js",
    "content": "function fillChar(lastGroup, fill, length) {\n  let chars = [];\n\n  for (let i = 1; i <= length; i++) {\n    chars.push(fill);\n  }\n\n  return lastGroup + chars.join('');\n}\n\nfunction divideString(s, k, fill) {\n  let groups = [];\n  let groupSize = 0;\n  let group = [];\n\n  for (let index = 0; index < s.length; index++) {\n    group.push(s[index]);\n    groupSize++;\n\n    if (groupSize === k) {\n      groups.push(group.join(''));\n      groupSize = 0;\n      group = [];\n    } else if (index === s.length - 1) {\n      groups.push(group.join(''));\n    }\n  }\n\n  let lastGroup = groups[groups.length - 1];\n  let lastGroupLength = lastGroup.length;\n\n  if (lastGroupLength !== k) {\n    lastGroup = fillChar(lastGroup, fill, k - lastGroupLength);\n    groups[groups.length - 1] = lastGroup;\n  }\n\n  return groups;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/divide-array-into-equal-pairs/divide-array-into-equal-pairs.js",
    "content": "export function divideArray(nums) {\n  const map = {};\n\n  for (let num of nums) {\n    if (map[num]) {\n      map[num] += 1;\n    } else {\n      map[num] = 1;\n    }\n  }\n\n  let hasEqualPairs = true;\n\n  for (let num of Object.values(map)) {\n    if (num % 2 !== 0) {\n      hasEqualPairs = false;\n      break;\n    }\n  }\n\n  return hasEqualPairs;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/divide-array-into-equal-pairs/tests/divide-array-into-equal-pairs.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { divideArray } from '../divide-array-into-equal-pairs';\n\ndescribe('divideArray', () => {\n  it('', () => {\n    expect(divideArray([3, 2, 3, 2, 2, 2])).toEqual(true);\n  });\n\n  it('', () => {\n    expect(divideArray([1, 2, 3, 4])).toEqual(false);\n  });\n\n  it('', () => {\n    expect(divideArray([2, 2])).toEqual(true);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/divisible-and-non-divisible-sums-difference/divisible-and-non-divisible-sums-difference.js",
    "content": "// https://leetcode.com/problems/divisible-and-non-divisible-sums-difference\n\nfunction differenceOfSums(n, m) {\n  let num1 = 0,\n    num2 = 0;\n\n  for (let num = 1; num <= n; num++) {\n    if (num % m === 0) num2 += num;\n    else num1 += num;\n  }\n\n  return num1 - num2;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/divisor-game/divisor-game.js",
    "content": "// https://leetcode.com/problems/divisor-game\n\nfunction divisorGame(n) {\n  return n % 2 === 0;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/equal_reversed_arrays/equal_reversed_arrays.py",
    "content": "# https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays\n\n'''\nGiven two integer arrays of equal length target and arr.\nIn one step, you can select any non-empty sub-array of arr and reverse it.\nYou are allowed to make any number of steps.\n\nReturn True if you can make arr equal to target, or False otherwise.\n\nInput: target = [1,2,3,4], arr = [2,4,1,3]\nOutput: true\n\nInput: target = [7], arr = [7]\nOutput: true\n\nInput: target = [1,12], arr = [12,1]\nOutput: true\n'''\n\n# 0(nlogn)\n\n\ndef can_be_equal(target, arr):\n    return target == arr or sorted(target) == sorted(arr)\n\n\n# 0(n)\n\ndef can_be_equal(target, arr):\n    counter = {}\n\n    for index in range(len(target)):\n        target_item, arr_item = target[index], arr[index]\n\n        if target_item in counter:\n            counter[target_item] += 1\n        else:\n            counter[target_item] = 1\n\n        if arr_item in counter:\n            counter[arr_item] += 1\n        else:\n            counter[arr_item] = 1\n\n    for _, value in counter.items():\n        if value % 2 != 0:\n            return False\n\n    return True\n\n\ndef can_be_equal(target, arr):\n    return collections.Counter(target) == collections.Counter(arr)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/evaluate-boolean-binary-tree/evaluate-boolean-binary-tree.js",
    "content": "const values = {\n  or: 2,\n  and: 3,\n};\n\nfunction evaluateTree(root) {\n  if ([0, 1].includes(root.val)) return Boolean(root.val);\n\n  const left = evaluateTree(root.left);\n  const right = evaluateTree(root.right);\n\n  return root.val === values.or ? left || right : left && right;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/even_digits/even_digits.py",
    "content": "# https://leetcode.com/problems/find-numbers-with-even-number-of-digits/\n\n\ndef find_numbers(nums):\n    counter = 0\n\n    for num in nums:\n        if len(str(num)) % 2 == 0:\n            counter += 1\n\n    return counter\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/excel-sheet-column-number/excel-sheet-column-number.js",
    "content": "function toNumber(char) {\n  return char.charCodeAt(0) - 64;\n}\n\nfunction titleToNumber(columnTitle) {\n  let columnNumber = 0;\n\n  for (let col of columnTitle) {\n    const num = toNumber(col);\n    columnNumber = columnNumber * 26 + num;\n  }\n\n  return columnNumber;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/fair-candy-swap/fair-candy-swap-optimized.js",
    "content": "function sum(nums) {\n  let sumOfNums = 0;\n\n  for (let num of nums) {\n    sumOfNums += num;\n  }\n\n  return sumOfNums;\n}\n\nfunction buildMap(bobSizes) {\n  let hashmap = new Map();\n\n  for (let bobSize of bobSizes) {\n    hashmap.set(bobSize, bobSize);\n  }\n\n  return hashmap;\n}\n\nfunction fairCandySwap(aliceSizes, bobSizes) {\n  let aliceCandies = sum(aliceSizes);\n  let bobCandies = sum(bobSizes);\n  let hashmap = buildMap(bobSizes);\n\n  for (let aliceSize of aliceSizes) {\n    let bobCandy = (bobCandies + 2 * aliceSize - aliceCandies) / 2;\n    if (hashmap.has(bobCandy)) {\n      return [aliceSize, bobCandy];\n    }\n  }\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/fair-candy-swap/fair-candy-swap.js",
    "content": "function sum(nums) {\n  let sumOfNums = 0;\n\n  for (let num of nums) {\n    sumOfNums += num;\n  }\n\n  return sumOfNums;\n}\n\nfunction fairCandySwap(aliceSizes, bobSizes) {\n  let aliceCandies = sum(aliceSizes);\n  let bobCandies = sum(bobSizes);\n\n  for (let i = 0; i < aliceSizes.length; i++) {\n    for (let j = 0; j < bobSizes.length; j++) {\n      let aliceCandy = aliceSizes[i];\n      let bobCandy = bobSizes[j];\n\n      if (\n        aliceCandies - aliceCandy + bobCandy ===\n        bobCandies - bobCandy + aliceCandy\n      ) {\n        return [aliceCandy, bobCandy];\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/faulty-keyboard/faulty-keyboard.js",
    "content": "// https://leetcode.com/problems/faulty-keyboard\n\nfunction reverse(s) {\n  let reversedS = [];\n\n  for (let index = s.length - 1; index >= 0; index--) {\n    reversedS.push(s[index]);\n  }\n\n  return reversedS;\n}\n\nfunction finalString(s) {\n  let subS = [];\n\n  for (let char of s) {\n    if (char === 'i') subS = reverse(subS);\n    else subS.push(char);\n  }\n\n  return subS.join('');\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/fibonacci_number/fibonacci_number.py",
    "content": "# https://leetcode.com/problems/fibonacci-number\n\ndef fib(n):\n    cache = [0, 1]\n    prev_1, prev_2 = 0, 1\n    \n    if n == 0: return 0\n    if n == 1: return 1\n    \n    for _ in range(2, n + 1):\n        cache.append(cache[prev_1] + cache[prev_2])\n        prev_1 += 1\n        prev_2 += 1\n        \n    return cache[-1]"
  },
  {
    "path": "coding_interviews/leetcode/easy/final-value-after-operations/final-value-after-operations.js",
    "content": "/*\nThere is a programming language with only four operations and one variable X:\n\n++X and X++ increments the value of the variable X by 1.\n--X and X-- decrements the value of the variable X by 1.\nInitially, the value of X is 0.\n\nGiven an array of strings operations containing a list of operations, return the final value of X after performing all the operations.\n\n# Example 1\nInput: operations = [\"--X\",\"X++\",\"X++\"]\nOutput: 1\nExplanation: The operations are performed as follows:\nInitially, X = 0.\n--X: X is decremented by 1, X =  0 - 1 = -1.\nX++: X is incremented by 1, X = -1 + 1 =  0.\nX++: X is incremented by 1, X =  0 + 1 =  1.\n\n# Example 2\nInput: operations = [\"++X\",\"++X\",\"X++\"]\nOutput: 3\nExplanation: The operations are performed as follows:\nInitially, X = 0.\n++X: X is incremented by 1, X = 0 + 1 = 1.\n++X: X is incremented by 1, X = 1 + 1 = 2.\nX++: X is incremented by 1, X = 2 + 1 = 3.\n\n# Example 3\nInput: operations = [\"X++\",\"++X\",\"--X\",\"X--\"]\nOutput: 0\nExplanation: The operations are performed as follows:\nInitially, X = 0.\nX++: X is incremented by 1, X = 0 + 1 = 1.\n++X: X is incremented by 1, X = 1 + 1 = 2.\n--X: X is decremented by 1, X = 2 - 1 = 1.\nX--: X is decremented by 1, X = 1 - 1 = 0.\n*/\n\nconst operationsMap = {\n  '--X': -1,\n  'X--': -1,\n  '++X': +1,\n  'X++': +1,\n};\n\nfunction finalValueAfterOperations(operations = []) {\n  let x = 0;\n\n  operations.forEach((operation) => {\n    x += operationsMap[operation];\n  });\n\n  return x;\n}\n\nconsole.log(finalValueAfterOperations(['--X', 'X++', 'X++']), 1);\nconsole.log(finalValueAfterOperations(['++X', '++X', 'X++']), 3);\nconsole.log(finalValueAfterOperations(['X++', '++X', '--X', 'X--']), 0);\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-all-k-distant-indices-in-an-array/find-all-k-distant-indices-in-an-array.js",
    "content": "function getJs(nums, key) {\n  let js = [];\n\n  for (let index = 0; index < nums.length; index++) {\n    if (nums[index] === key) js.push(index);\n  }\n\n  return js;\n}\n\nfunction isKDistant(index, js, k) {\n  for (let j of js) {\n    if (Math.abs(index - j) <= k) return true;\n  }\n\n  return false;\n}\n\nfunction findKDistantIndices(nums, key, k) {\n  const js = getJs(nums, key);\n  const output = [];\n  console.log('js', js);\n\n  for (let index = 0; index < nums.length; index++) {\n    if (isKDistant(index, js, k)) {\n      output.push(index);\n    }\n  }\n\n  return output;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-all-numbers-disappeared-in-an-array/find-all-numbers-disappeared-in-an-array.js",
    "content": "function buildMap(nums) {\n  let hashmap = new Map();\n\n  for (let num of nums) {\n    hashmap.set(num, true);\n  }\n\n  return hashmap;\n}\n\nfunction findDisappearedNumbers(nums) {\n  let hashmap = buildMap(nums);\n  let output = [];\n\n  for (let num = 1; num <= nums.length; num++) {\n    if (!hashmap.has(num)) output.push(num);\n  }\n\n  return output;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-center-of-star-graph/find-center-of-star-graph.js",
    "content": "function addConnection(nodeToConnectionsCount, node) {\n  if (nodeToConnectionsCount[node]) {\n    nodeToConnectionsCount[node]++;\n  } else {\n    nodeToConnectionsCount[node] = 1;\n  }\n}\n\nfunction findCenter(edges) {\n  let nodeToConnectionsCount = {};\n\n  for (let [first, second] of edges) {\n    addConnection(nodeToConnectionsCount, first);\n    addConnection(nodeToConnectionsCount, second);\n  }\n\n  let star;\n  let maxConnections = -Infinity;\n\n  Object.entries(nodeToConnectionsCount).forEach(([node, count]) => {\n    if (count > maxConnections) {\n      star = node;\n      maxConnections = count;\n    }\n  });\n\n  return star;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-champion-i/find-champion-i-no-map.js",
    "content": "// https://leetcode.com/problems/find-champion-i\n\nfunction findChampion(grid) {\n  for (let i = 0; i < grid.length; i++) {\n    let count = 0;\n\n    for (let j = 0; j < grid[i].length; j++) {\n      if (grid[i][j] === 1) {\n        count++;\n      }\n    }\n\n    if (count === grid.length - 1) {\n      return i;\n    }\n  }\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-champion-i/find-champion-i.js",
    "content": "// https://leetcode.com/problems/find-champion-i\n\nfunction findChampion(grid) {\n  let winners = new Map();\n\n  for (let i = 0; i < grid.length; i++) {\n    for (let j = 0; j < grid[i].length; j++) {\n      if (grid[i][j] === 1) {\n        winners.set(i, (winners.get(i) || 0) + 1);\n      }\n    }\n  }\n\n  for (let [key, value] of winners.entries()) {\n    if (value === grid.length - 1) {\n      return key;\n    }\n  }\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-first-palindromic-string-in-the-array/find-first-palindromic-string-in-the-array.js",
    "content": "export function isPalindrome(word) {\n  for (let i = 0; i < Math.floor(word.length / 2); i++) {\n    if (word[i] !== word[word.length - 1 - i]) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nexport function firstPalindrome(words) {\n  let palindromicWord = '';\n\n  for (let i = 0; i < words.length; i++) {\n    if (isPalindrome(words[i])) {\n      palindromicWord = words[i];\n      break;\n    }\n  }\n\n  return palindromicWord;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-first-palindromic-string-in-the-array/tests/find-first-palindromic-string-in-the-array.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport {\n  firstPalindrome,\n  isPalindrome,\n} from '../find-first-palindromic-string-in-the-array';\n\ndescribe('firstPalindrome', () => {\n  it('', () => {\n    expect(firstPalindrome(['abc', 'car', 'ada', 'racecar', 'cool'])).toEqual(\n      'ada'\n    );\n  });\n\n  it('', () => {\n    expect(firstPalindrome(['notapalindrome', 'racecar'])).toEqual('racecar');\n  });\n\n  it('', () => {\n    expect(firstPalindrome(['def', 'ghi'])).toEqual('');\n  });\n});\n\ndescribe('isPalindrome', () => {\n  it('', () => {\n    expect(isPalindrome('ada')).toBeTruthy();\n  });\n\n  it('', () => {\n    expect(isPalindrome('')).toBeTruthy();\n  });\n\n  it('', () => {\n    expect(isPalindrome('eda')).toBeFalsy();\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-greatest-common-divisor-of-array/find-greatest-common-divisor-of-array.js",
    "content": "// https://leetcode.com/problems/find-greatest-common-divisor-of-array\n\nconst findSmallestAndLargest = (nums) => {\n  let smallest = Infinity;\n  let largest = -Infinity;\n\n  for (let i = 0; i < nums.length; i++) {\n    smallest = Math.min(smallest, nums[i]);\n    largest = Math.max(largest, nums[i]);\n  }\n\n  return [smallest, largest];\n};\n\nconst gcd = (num1, num2) => (num2 ? gcd(num2, num1 % num2) : num1);\n\nconst findGCD = (nums) => {\n  const [smallest, largest] = findSmallestAndLargest(nums);\n  return gcd(smallest, largest);\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-indices-with-index-and-value-difference-i/find-indices-with-index-and-value-difference-i.js",
    "content": "// https://leetcode.com/problems/find-indices-with-index-and-value-difference-i\n\nfunction findIndices(nums, indexDifference, valueDifference) {\n  for (let i = 0; i < nums.length; i++) {\n    for (let j = 0; j < nums.length; j++) {\n      if (\n        Math.abs(i - j) >= indexDifference &&\n        Math.abs(nums[i] - nums[j]) >= valueDifference\n      ) {\n        return [i, j];\n      }\n    }\n  }\n\n  return [-1, -1];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-lucky-integer-in-an-array/find-lucky-integer-in-an-array.js",
    "content": "function buildNumCounter(nums) {\n  let counter = new Map();\n\n  for (let num of nums) {\n    if (counter.has(num)) counter.set(num, counter.get(num) + 1);\n    else counter.set(num, 1);\n  }\n\n  return counter;\n}\n\nfunction findLucky(nums) {\n  let largestLuckyInteger = -1;\n  let counter = buildNumCounter(nums);\n\n  for (let num of nums) {\n    if (num === counter.get(num) && num > largestLuckyInteger) {\n      largestLuckyInteger = num;\n    }\n  }\n\n  return largestLuckyInteger;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-maximum-number-of-string-pairs/find-maximum-number-of-string-pairs.js",
    "content": "// https://leetcode.com/problems/find-maximum-number-of-string-pairs\n\nfunction paired(s1, s2) {\n  for (let i = 0; i < s1.length; i++) {\n    if (s1[i] !== s2[s2.length - 1 - i]) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nfunction maximumNumberOfStringPairs(words) {\n  let max = 0;\n\n  for (let i = 0; i < words.length - 1; i++) {\n    for (let j = i + 1; j < words.length; j++) {\n      if (paired(words[i], words[j])) {\n        max++;\n      }\n    }\n  }\n\n  return max;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-nearest-point-that-has-the-same-x-or-y-coordinate/find-nearest-point-that-has-the-same-x-or-y-coordinate.js",
    "content": "// https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate\n// points = [] - not empty\n// x and y positive numbers\n\nconst nearestValidPoint = (x, y, points) => {\n  let minDistance = Infinity;\n  let pointIndex = -1;\n\n  points.forEach((point, index) => {\n    if (isValid([x, y], point)) {\n      const manhattanDistance = calculateManhattanDistance([x, y], point);\n      if (manhattanDistance < minDistance) {\n        pointIndex = index;\n        minDistance = manhattanDistance;\n      }\n    }\n  });\n\n  return pointIndex;\n};\n\nconst isValid = (position, point) => {\n  const [x, y] = position;\n  const [pointX, pointY] = point;\n  return x === pointX || y === pointY;\n};\n\nconst calculateManhattanDistance = (position, point) => {\n  const [x, y] = position;\n  const [pointX, pointY] = point;\n  return Math.abs(x - pointX) + Math.abs(y - pointY);\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-subarrays-with-equal-sum/find-subarrays-with-equal-sum.js",
    "content": "function findSubarrays(nums) {\n  for (let i = 0; i < nums.length - 2; i++) {\n    for (let j = i + 1; j < nums.length - 1; j++) {\n      if (nums[i] + nums[i + 1] === nums[j] + nums[j + 1]) return true;\n    }\n  }\n\n  return false;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-target-indices-after-sorting-array/find-target-indices-after-sorting-array.js",
    "content": "export function targetIndices(nums, target) {\n  const sortedNums = nums.sort((num1, num2) => num1 - num2);\n  const result = [];\n\n  sortedNums.forEach((num, index) => {\n    if (num === target) {\n      result.push(index);\n    }\n  });\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-target-indices-after-sorting-array/tests/find-target-indices-after-sorting-array.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { targetIndices } from '../find-target-indices-after-sorting-array';\n\ndescribe('targetIndices', () => {\n  it('', () => {\n    expect(\n      targetIndices(\n        [\n          48, 90, 9, 21, 31, 35, 19, 69, 29, 52, 100, 54, 21, 86, 6, 45, 42, 5,\n          62, 77, 15, 38,\n        ],\n        6\n      )\n    ).toEqual([1]);\n  });\n\n  it('', () => {\n    expect(targetIndices([1, 2, 5, 2, 3], 2)).toEqual([1, 2]);\n  });\n\n  it('', () => {\n    expect(targetIndices([1, 2, 5, 2, 3], 3)).toEqual([3]);\n  });\n\n  it('', () => {\n    expect(targetIndices([1, 2, 5, 2, 3], 5)).toEqual([4]);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-the-array-concatenation-value/find-the-array-concatenation-value.js",
    "content": "function concat(num1, num2) {\n  return Number(num1.toString() + num2.toString());\n}\n\nfunction findTheArrayConcVal(nums) {\n  let pointer1 = 0;\n  let pointer2 = nums.length - 1;\n  let output = 0;\n\n  while (pointer1 <= pointer2) {\n    if (pointer1 === pointer2) output += nums[pointer1];\n    else output += concat(nums[pointer1], nums[pointer2]);\n    pointer1++;\n    pointer2--;\n  }\n\n  return output;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-the-difference/find-the-difference.js",
    "content": "function buildMap(string) {\n  let hashmap = new Map();\n\n  for (let char of string) {\n    if (hashmap.has(char)) hashmap.set(char, hashmap.get(char) + 1);\n    else hashmap.set(char, 1);\n  }\n\n  return hashmap;\n}\n\nfunction findTheDifference(s, t) {\n  let hashmap = buildMap(s);\n\n  for (let char of t) {\n    if (hashmap.has(char) && hashmap.get(char) > 0) {\n      hashmap.set(char, hashmap.get(char) - 1);\n      continue;\n    }\n\n    return char;\n  }\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-the-difference-of-two-arrays/find-the-difference-of-two-arrays.js",
    "content": "function buildHashmap(nums) {\n  let hashmap = new Map();\n\n  for (let num of nums) {\n    hashmap.set(num, true);\n  }\n\n  return hashmap;\n}\n\nfunction buildDistinct(nums, hashmap) {\n  let distinct = [];\n\n  for (let num of nums) {\n    if (!hashmap.has(num)) {\n      distinct.push(num);\n      hashmap.set(num, true);\n    }\n  }\n\n  return distinct;\n}\n\nfunction findDifference(nums1, nums2) {\n  let hashmap1 = buildHashmap(nums1);\n  let hashmap2 = buildHashmap(nums2);\n  let distinct1 = buildDistinct(nums1, hashmap2);\n  let distinct2 = buildDistinct(nums2, hashmap1);\n\n  return [distinct1, distinct2];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-the-distance-value-between-two-arrays/find-the-distance-value-between-two-arrays.js",
    "content": "// https://leetcode.com/problems/find-the-distance-value-between-two-arrays\n\nfunction hasSmallerValue(num, arr, d) {\n  for (let number of arr) {\n    if (Math.abs(num - number) <= d) return true;\n  }\n\n  return false;\n}\n\nfunction findTheDistanceValue(arr1, arr2, d) {\n  let count = 0;\n\n  for (let num1 of arr1) {\n    if (!hasSmallerValue(num1, arr2, d)) count++;\n  }\n\n  return count;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-the-distinct-difference-array/find-the-distinct-difference-array.js",
    "content": "// https://leetcode.com/problems/find-the-distinct-difference-array\n\nfunction countDistinct(nums, startIndex, endIndex) {\n  let count = 0;\n  let distinct = new Map();\n\n  for (let i = startIndex; i <= endIndex; i++) {\n    if (!distinct.has(nums[i])) {\n      distinct.set(nums[i], nums[i]);\n      count++;\n    }\n  }\n\n  return count;\n}\n\nfunction countDistinctPrefix(nums, index) {\n  return countDistinct(nums, 0, index);\n}\n\nfunction countDistinctSufix(nums, index) {\n  return countDistinct(nums, index + 1, nums.length - 1);\n}\n\nfunction distinctDifferenceArray(nums) {\n  let diff = [];\n\n  for (let index = 0; index < nums.length; index++) {\n    let prefix = countDistinctPrefix(nums, index);\n    let sufix = countDistinctSufix(nums, index);\n    diff.push(prefix - sufix);\n  }\n\n  return diff;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-the-distinct-difference-array/optimized-find-the-distinct-difference-array.js",
    "content": "// https://leetcode.com/problems/find-the-distinct-difference-array\n\nfunction distinctDifferenceArray(nums) {\n  let distinctDiff = [];\n  let countInLeft = 0;\n  let countInRight = 0;\n  let leftCounterMap = new Map();\n  let rightCounterMap = new Map();\n\n  for (let num of nums) {\n    if (leftCounterMap.has(num)) {\n      leftCounterMap.set(num, leftCounterMap.get(num) + 1);\n    } else {\n      leftCounterMap.set(num, 1);\n      countInLeft++;\n    }\n  }\n\n  distinctDiff.unshift(countInLeft - countInRight);\n\n  for (let index = nums.length - 1; index > 0; index--) {\n    let num = nums[index];\n    leftCounterMap.set(num, leftCounterMap.get(num) - 1);\n    if (leftCounterMap.get(num) === 0) countInLeft--;\n    rightCounterMap.set(num, (rightCounterMap.get(num) || 0) + 1);\n    if (rightCounterMap.get(num) === 1) countInRight++;\n    distinctDiff.unshift(countInLeft - countInRight);\n  }\n\n  return distinctDiff;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-the-maximum-achievable-number/find-the-maximum-achievable-number.js",
    "content": "// https://leetcode.com/problems/find-the-maximum-achievable-number\n\nfunction theMaximumAchievableX(num, t) {\n  return t * 2 + num;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-the-middle-index-in-array/find-the-middle-index-in-array.js",
    "content": "function sum(nums) {\n  return nums.reduce((sumOfNums, num) => sumOfNums + num, 0);\n}\n\nfunction findMiddleIndex(nums) {\n  let sumOfNums = sum(nums) - nums[0];\n  let firstHalfSum = 0;\n  let index = 0;\n\n  while (index < nums.length - 1 && sumOfNums !== firstHalfSum) {\n    sumOfNums -= nums[index + 1];\n    firstHalfSum += nums[index];\n    index++;\n  }\n\n  return sumOfNums === firstHalfSum ? index : -1;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-the-pivot-integer/find-the-pivot-integer.js",
    "content": "const NO_PIVOT = -1;\n\nfunction sum(n) {\n  let sumOfNs = 0;\n\n  for (let num = 1; num <= n; num++) {\n    sumOfNs += num;\n  }\n\n  return sumOfNs;\n}\n\nfunction pivotInteger(n) {\n  let sumOfNs = sum(n);\n  let leftSum = 0;\n\n  for (let num = 1; num <= n; num++) {\n    leftSum += num;\n    if (sumOfNs === leftSum) return num;\n    sumOfNs -= num;\n  }\n\n  return NO_PIVOT;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-the-width-of-columns-of-a-grid/find-the-width-of-columns-of-a-grid.js",
    "content": "// https://leetcode.com/problems/find-the-width-of-columns-of-a-grid\n\nfunction findColumnWidth(grid) {\n  let output = [];\n\n  for (let col = 0; col < grid[0].length; col++) {\n    let max = -Infinity;\n    for (let row = 0; row < grid.length; row++) {\n      let cell = grid[row][col];\n      let length = cell.toString().length;\n      max = Math.max(max, length);\n    }\n    output.push(max);\n  }\n\n  return output;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-words-containing-character/find-words-containing-character.js",
    "content": "// https://leetcode.com/problems/find-words-containing-character\n\nfunction findWordsContaining(words, x) {\n  let indices = [];\n\n  for (let index = 0; index < words.length; index++) {\n    for (let char of words[index]) {\n      if (char === x) {\n        indices.push(index);\n        break;\n      }\n    }\n  }\n\n  return indices;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find-words-that-can-be-formed-by-characters/find-words-that-can-be-formed-by-characters.js",
    "content": "function buildCounter(chars) {\n  let counter = new Map();\n\n  for (let char of chars) {\n    if (counter.has(char)) counter.set(char, counter.get(char) + 1);\n    else counter.set(char, 1);\n  }\n\n  return counter;\n}\n\nfunction isGood(word, counterCopy) {\n  for (let char of word) {\n    if (counterCopy.has(char) && counterCopy.get(char) > 0)\n      counterCopy.set(char, counterCopy.get(char) - 1);\n    else return false;\n  }\n\n  return true;\n}\n\nfunction countCharacters(words, chars) {\n  let counter = buildCounter(chars);\n  let counterCopy;\n  let goodWords = [];\n\n  for (let word of words) {\n    counterCopy = new Map(counter);\n    if (isGood(word, counterCopy)) goodWords.push(word);\n  }\n\n  return goodWords.reduce((lengths, word) => lengths + word.length, 0);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find_common_characters/find_common_characters.py",
    "content": "# https://leetcode.com/problems/find-common-characters\n\ndef common_chars(A):\n    if len(A) == 1: return [char for char in A]\n\n    word = A[0]\n    words = A[1:]\n    result = []\n\n    for char in word:\n        all = True\n        \n        for index, other_word in enumerate(words):\n            if char in other_word:\n                other_word_index = other_word.index(char)\n                words[index] = words[index][:other_word_index] + words[index][other_word_index+1:]\n            else:\n                all = False\n                break\n                \n        if all: result.append(char)\n            \n    return result\n\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/find_the_highest_altitude/find_the_highest_altitude.py",
    "content": "# https://leetcode.com/problems/find-the-highest-altitude\n\ndef largest_altitude(gain):\n    highest_altitude, current_altitude = 0, 0 \n\n    for net_gain in gain:\n        current_altitude += net_gain\n        if current_altitude > highest_altitude:\n            highest_altitude = current_altitude\n        \n    return highest_altitude"
  },
  {
    "path": "coding_interviews/leetcode/easy/first-bad-version/first-bad-version-binary-search.js",
    "content": "function getMiddle(start, end) {\n  return Math.floor((start + end) / 2);\n}\n\nfunction binarySearchFirstBadVersion(isBadVersion) {\n  return (n) => {\n    let start = 1;\n    let end = n;\n    let middle = getMiddle(start, end);\n    let firstBadVersion = middle;\n\n    while (start < end) {\n      if (isBadVersion(middle)) {\n        end = middle - 1;\n      } else {\n        start = middle + 1;\n      }\n\n      middle = getMiddle(start, end);\n\n      if (isBadVersion(middle)) {\n        firstBadVersion = middle;\n      }\n    }\n\n    return firstBadVersion;\n  };\n}\n\nfunction solution(isBadVersion) {\n  return binarySearchFirstBadVersion(isBadVersion);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/first-bad-version/first-bad-version.js",
    "content": "function solution(isBadVersion) {\n  return function (n) {\n    for (let version = 1; version <= n; version++) {\n      if (isBadVersion(version)) {\n        return version;\n      }\n    }\n  };\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/first-letter-to-appear-twice/first-letter-to-appear-twice.js",
    "content": "function repeatedCharacter(s) {\n  let counter = new Map();\n\n  for (let char of s) {\n    if (counter.has(char)) {\n      return char;\n    }\n\n    counter.set(char, 1);\n  }\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/first-unique-character-in-a-string/first-unique-character-in-a-string.js",
    "content": "function firstUniqChar(s) {\n  let charCount = {};\n\n  for (let char of s) {\n    if (charCount[char]) {\n      charCount[char]++;\n    } else {\n      charCount[char] = 1;\n    }\n  }\n\n  for (let index = 0; index < s.length; index++) {\n    if (charCount[s[index]] === 1) {\n      return index;\n    }\n  }\n\n  return -1;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/first_bad_version/first_bad_version.py",
    "content": "'''\nApproach #1 (Linear Scan) [Time Limit Exceeded]\nThe straight forward way is to brute force it by doing a linear scan.\n\nComplexity analysis\n\nTime complexity : O(n)O(n). Assume that isBadVersion(version)isBadVersion(version) takes constant time to check if a version is bad. It takes at most n - 1n−1 checks, therefore the overall time complexity is O(n)O(n).\n\nSpace complexity : O(1)O(1).\n\nApproach #2 (Binary Search) [Accepted]\nIt is not difficult to see that this could be solved using a classic algorithm - Binary search. Let us see how the search space could be halved each time below.\n\nScenario #1: isBadVersion(mid) => false\n\n 1 2 3 4 5 6 7 8 9\n G G G G G G B B B       G = Good, B = Bad\n |       |       |\nleft    mid    right\nLet us look at the first scenario above where isBadVersion(mid) \\Rightarrow falseisBadVersion(mid)⇒false. We know that all versions preceding and including midmid are all good. So we set left = mid + 1left=mid+1 to indicate that the new search space is the interval [mid + 1, right][mid+1,right] (inclusive).\n\nScenario #2: isBadVersion(mid) => true\n\n 1 2 3 4 5 6 7 8 9\n G G G B B B B B B       G = Good, B = Bad\n |       |       |\nleft    mid    right\nThe only scenario left is where isBadVersion(mid) \\Rightarrow trueisBadVersion(mid)⇒true. This tells us that midmid may or may not be the first bad version, but we can tell for sure that all versions after midmid can be discarded. Therefore we set right = midright=mid as the new search space of interval [left,mid][left,mid] (inclusive).\n\nIn our case, we indicate leftleft and rightright as the boundary of our search space (both inclusive). This is why we initialize left = 1left=1 and right = nright=n. How about the terminating condition? We could guess that leftleft and rightright eventually both meet and it must be the first bad version, but how could you tell for sure?\n\nThe formal way is to prove by induction, which you can read up yourself if you are interested. Here is a helpful tip to quickly prove the correctness of your binary search algorithm during an interview. We just need to test an input of size 2. Check if it reduces the search space to a single element (which must be the answer) for both of the scenarios above. If not, your algorithm will never terminate.\n\nIf you are setting mid = \\frac{left + right}{2}mid=\n2\nleft+right\n​\n , you have to be very careful. Unless you are using a language that does not overflow such as Python, left + rightleft+right could overflow. One way to fix this is to use left + \\frac{right - left}{2}left+\n2\nright−left\n​\n  instead.\n\nIf you fall into this subtle overflow bug, you are not alone. Even Jon Bentley's own implementation of binary search had this overflow bug and remained undetected for over twenty years.\n\nComplexity analysis\n\nTime complexity : O(logn). The search space is halved each time, so the time complexity is O(\\log n)O(logn).\n\nSpace complexity : O(1).\n'''\n\n\ndef is_bad_version(version):\n    True\n\n\ndef first_bad_version(n):\n    start = 1\n    last = n\n\n    while start < last:\n        middle = (start + last) / 2\n\n        if is_bad_version(middle):\n            last = middle\n        else:\n            start = middle + 1\n\n    return start\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/fizz-buzz/fizz-buzz.js",
    "content": "function fizzBuzz(n) {\n  const answer = [];\n\n  for (let i = 1; i <= n; i++) {\n    if (i % 3 === 0 && i % 5 === 0) {\n      answer.push('FizzBuzz');\n      continue;\n    }\n\n    if (i % 3 === 0) {\n      answer.push('Fizz');\n      continue;\n    }\n\n    if (i % 5 === 0) {\n      answer.push('Buzz');\n      continue;\n    }\n\n    answer.push(String(i));\n  }\n\n  return answer;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/flipping_an_image.py",
    "content": "# https://leetcode.com/problems/flipping-an-image/description/\n\n# input: [[1,1,0], [1,0,1], [0,0,0]]\n# output: [[1,0,0], [0,1,0], [1,1,1]]\n\ndef flip_and_invert_image(image):\n    for i in range(len(image)):\n        image[i] = image[i][::-1]\n\n    for i in range(len(image)):\n        for j in range(len(image[i])):\n            image[i][j] = 1 - image[i][j]\n\n    return image\n\nprint(flip_and_invert_image([[1,1,0], [1,0,1], [0,0,0]]))\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/flood-fill/flood-fill-without-visited.js",
    "content": "function isInsideTheGrid(image, row, col) {\n  const validRow = row >= 0 && row < image.length;\n  const validCol = col >= 0 && col < image[0].length;\n  return validRow && validCol;\n}\n\nfunction dfs(image, row, col, newColor, startingPixel) {\n  if (isInsideTheGrid(image, row, col) && image[row][col] === startingPixel) {\n    image[row][col] = newColor;\n    dfs(image, row - 1, col, newColor, startingPixel);\n    dfs(image, row, col + 1, newColor, startingPixel);\n    dfs(image, row, col - 1, newColor, startingPixel);\n    dfs(image, row + 1, col, newColor, startingPixel);\n  }\n}\n\nfunction floodFill(image, row, col, newColor) {\n  if (image[row][col] !== newColor) {\n    dfs(image, row, col, newColor, image[row][col]);\n  }\n\n  return image;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/flood-fill/flood-fill.js",
    "content": "/**\n- is it inside the grid?\n- is it equal to the target value?\n  - update the pixe with newColor\n  - recursive call for: top, left, right, bottom\n */\n\nfunction isInsideTheGrid(image, row, col) {\n  const validRow = row >= 0 && row < image.length;\n  const validCol = col >= 0 && col < image[0].length;\n  return validRow && validCol;\n}\n\nfunction floodFillHelper(image, sr, sc, newColor, startingPixel, visited) {\n  if (isInsideTheGrid(image, sr, sc)) {\n    let currentPixel = image[sr][sc];\n\n    if (currentPixel === startingPixel && !visited[sr][sc]) {\n      image[sr][sc] = newColor;\n      visited[sr][sc] = true;\n\n      let topPosition = {\n        row: sr - 1,\n        col: sc,\n      };\n\n      let rightPosition = {\n        row: sr,\n        col: sc + 1,\n      };\n\n      let leftPosition = {\n        row: sr,\n        col: sc - 1,\n      };\n\n      let bottomPosition = {\n        row: sr + 1,\n        col: sc,\n      };\n\n      floodFillHelper(\n        image,\n        topPosition.row,\n        topPosition.col,\n        newColor,\n        startingPixel,\n        visited\n      );\n\n      floodFillHelper(\n        image,\n        rightPosition.row,\n        rightPosition.col,\n        newColor,\n        startingPixel,\n        visited\n      );\n\n      floodFillHelper(\n        image,\n        leftPosition.row,\n        leftPosition.col,\n        newColor,\n        startingPixel,\n        visited\n      );\n\n      floodFillHelper(\n        image,\n        bottomPosition.row,\n        bottomPosition.col,\n        newColor,\n        startingPixel,\n        visited\n      );\n    }\n  }\n}\n\nfunction buildVisitedMatrix(image) {\n  let matrix = [];\n\n  for (let row = 0; row < image.length; row++) {\n    let r = [];\n\n    for (let col = 0; col < image[row].length; col++) {\n      r.push(false);\n    }\n\n    matrix.push(r);\n  }\n\n  return matrix;\n}\n\nfunction floodFill(image, sr, sc, newColor) {\n  let visited = buildVisitedMatrix(image);\n  floodFillHelper(image, sr, sc, newColor, image[sr][sc], visited);\n  return image;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/furthest-point-from-origin/furthest-point-from-origin.js",
    "content": "// https://leetcode.com/problems/furthest-point-from-origin\n\nfunction furthestDistanceFromOrigin(moves) {\n  let diff = 0;\n  let underlines = 0;\n\n  for (let move of moves) {\n    if (move === '_') underlines++;\n    if (move === 'R') diff++;\n    if (move === 'L') diff--;\n  }\n\n  return Math.abs(diff) + underlines;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/generate_the_string/generate_the_string.py",
    "content": "# https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts\n\ndef generate_the_string(n):\n    if n % 2 == 0:\n        return 'a' * (n - 1) + 'b'\n    \n    return 'a' * n"
  },
  {
    "path": "coding_interviews/leetcode/easy/goal_parser_interpretation/goal_parser_interpretation.py",
    "content": "# https://leetcode.com/problems/goal-parser-interpretation\n\n\ndef interpret(command):\n    result, empty_paren = [], True\n\n    for char in command:\n        if char == 'G':\n            result.append('G')\n        else:\n            if char == ')':\n                if empty_paren:\n                    result.append('o')\n                else:\n                    result.append('al')\n                empty_paren = True\n            elif char != '(':\n                empty_paren = False\n\n    return ''.join(result)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/greatest-english-letter-in-upper-and-lower-case/greatest-english-letter-in-upper-and-lower-case.js",
    "content": "function greatestLetter(string) {\n  let greatest = [-Infinity, ''];\n  let charsToCode = new Map();\n\n  for (let char of string) {\n    let lowerCasedChar = char.toLowerCase();\n    let charCode = char.charCodeAt();\n\n    if (\n      charsToCode.has(lowerCasedChar) &&\n      charsToCode.get(lowerCasedChar) !== charCode\n    ) {\n      const greaterCharCode = Math.max(\n        charCode,\n        charsToCode.get(lowerCasedChar)\n      );\n      greatest =\n        greaterCharCode > greatest[0]\n          ? [greaterCharCode, char.toUpperCase()]\n          : greatest;\n    } else if (!charsToCode.has(lowerCasedChar)) {\n      charsToCode.set(lowerCasedChar, charCode);\n    }\n  }\n\n  return greatest[1];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/greatest_candies/greatest_candies.py",
    "content": "# https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/\n\n'''\n[2, 3, 3, 1, 3] 2\n[True, True, True, True, True]\n'''\n\n\ndef kids_with_candies(candies, extra_candies):\n    greatest = get_greatest(candies)\n    return map_can_be_greatest(candies, extra_candies, greatest)\n\n\ndef map_can_be_greatest(candies, extra_candies, greatest_candy):\n    greatest_possibilities = []\n\n    for candy in candies:\n        greatest_possibilities.append(candy + extra_candies >= greatest_candy)\n\n    return greatest_possibilities\n\n\ndef get_greatest(candies):\n    greatest = candies[0]\n\n    for candy in candies:\n        if candy > greatest:\n            greatest = candy\n\n    return greatest\n\n\ndata_tests = [\n    ([2, 3, 3, 1, 3], 2, [True, True, True, True, True]),\n    ([4, 2, 1, 1, 2], 1, [True, False, False, False, False]),\n    ([12, 1, 12], 10, [True, False, True]),\n]\n\nfor candies, extra_candies, expected in data_tests:\n    result = kids_with_candies(candies, extra_candies)\n    print(result, result == expected)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/guess-number-higher-or-lower/guess-number-higher-or-lower.js",
    "content": "// https://leetcode.com/problems/guess-number-higher-or-lower\n\nfunction guessNumber(n) {\n  let start = 1;\n  let end = n;\n  let middle = Math.round(n / 2);\n\n  while (guess(middle)) {\n    if (guess(middle) > 0) {\n      start = middle + 1;\n    } else {\n      end = middle - 1;\n    }\n\n    middle = Math.round(end + start) / 2;\n  }\n\n  return middle;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/halves_are_alike/halves_are_alike.py",
    "content": "# https://leetcode.com/problems/determine-if-string-halves-are-alike/\n\n\ndef halves_are_alike(s):\n    vowels = {\n        'a': True, \n        'e': True, \n        'i': True, \n        'o': True, \n        'u': True, \n        'A': True, \n        'E': True, \n        'I': True, \n        'O': True, \n        'U': True, \n    }\n    \n    \n    middle_index = len(s) // 2\n    a, b = s[:middle_index], s[middle_index:]\n    a_counter, b_counter = 0, 0\n    \n    for char in a:\n        if char in vowels:\n            a_counter += 1\n            \n    for char in b:\n        if char in vowels:\n            b_counter += 1\n            \n    return a_counter == b_counter"
  },
  {
    "path": "coding_interviews/leetcode/easy/hamming_distance/hamming_distance.py",
    "content": "def get_bit(number):\n    return \"{0:b}\".format(number)\n\ndef hamming_distance(x, y):\n    x_bit = get_bit(x)\n    y_bit = get_bit(y)\n    \n    min_len = min(len(x_bit), len(y_bit))\n    max_len = max(len(x_bit), len(y_bit))\n    diff_len = max_len - min_len\n    \n    if len(x_bit) > len(y_bit):\n        max_bit = x_bit\n        min_bit = y_bit\n    else:\n        max_bit = y_bit\n        min_bit = x_bit\n        \n    min_bit = '0' * diff_len + min_bit\n    \n    counter = 0\n    \n    for index in range(max_len):\n        if max_bit[index] != min_bit[index]: counter += 1\n            \n    return counter\n\ndef hamming_distance_2(x, y):\n    counter = 0\n\n    while x or y:\n        if (x % 2) != (y % 2): counter += 1\n        x //= 2\n        y //= 2\n\n    return counter"
  },
  {
    "path": "coding_interviews/leetcode/easy/height_checker/height_checker.py",
    "content": "# https://leetcode.com/problems/height-checker\n\ndef height_checker(heights):\n    sorted_heights, counter = sorted(heights), 0\n    \n    for index in range(len(heights)):\n        if heights[index] != sorted_heights[index]:\n            counter += 1\n            \n    return counter"
  },
  {
    "path": "coding_interviews/leetcode/easy/implement-queue-using-stacks/implement-queue-using-stacks.js",
    "content": "const MyQueue = function () {\n  this.list = [];\n};\n\nMyQueue.prototype.push = function (x) {\n  this.list.push(x);\n};\n\nMyQueue.prototype.pop = function () {\n  return this.list.shift();\n};\n\nMyQueue.prototype.peek = function () {\n  return this.list[0];\n};\n\nMyQueue.prototype.empty = function () {\n  return this.list.length === 0;\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/implement-stack-using-queues/implement-stack-using-queues.js",
    "content": "function MyStack() {\n  this.items = [];\n}\n\nMyStack.prototype.push = function (x) {\n  this.items.push(x);\n};\n\nMyStack.prototype.pop = function () {\n  return this.items.pop();\n};\n\nMyStack.prototype.top = function () {\n  return this.items.at(-1);\n};\n\nMyStack.prototype.empty = function () {\n  return this.items.length === 0;\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/increasing_decreasing_string/incresing_decreasin_string.py",
    "content": "\n# https://leetcode.com/problems/increasing-decreasing-string/\n\n\ndef sort_string(s):\n    result = []\n    \n    while len(s):\n        last_appended, to_be_appended, chosen_index = float('-Inf'), float('Inf'), float('Inf')\n\n        while chosen_index is not None:\n            chosen_index = None\n\n            for index, char in enumerate(s):\n                unicode_char = ord(char)\n\n                if unicode_char > last_appended and unicode_char < to_be_appended:\n                    to_be_appended = unicode_char\n                    chosen_index = index\n\n            if chosen_index is not None:\n                result.append(chr(to_be_appended))\n                last_appended = to_be_appended\n                to_be_appended = float('Inf')\n                s = s[0:chosen_index] + s[chosen_index+1:]\n\n        last_appended, to_be_appended, chosen_index = float('Inf'), float('-Inf'), float('Inf')\n\n        while chosen_index is not None:\n            chosen_index = None\n\n            for index, char in enumerate(s):\n                unicode_char = ord(char)\n\n                if unicode_char < last_appended and unicode_char > to_be_appended:\n                    to_be_appended = unicode_char\n                    chosen_index = index\n\n            if chosen_index is not None:\n                result.append(chr(to_be_appended))\n                last_appended = to_be_appended\n                to_be_appended = float('-Inf')\n                s = s[0:chosen_index] + s[chosen_index+1:]\n            \n    return ''.join(result)"
  },
  {
    "path": "coding_interviews/leetcode/easy/increasing_order_search_tree/increasing_order_search_tree.py",
    "content": "def increasingBST(root):\n    arr = []\n    helper(root, arr)\n\n    ans = current = TreeNode(arr[0])\n    \n    for val in arr[1:]:\n        current.right = TreeNode(val)\n        current = current.right\n        \n    return ans\n        \ndef helper(self, old_tree, arr):\n    if old_tree.left: helper(old_tree.left, arr)\n    arr.append(old_tree.val)\n    if old_tree.right: helper(old_tree.right, arr)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/intersection-of-multiple-arrays/intersection-of-multiple-arrays.js",
    "content": "function intersection(nums) {\n  const numberCounts = new Map();\n  const numsLength = nums.length;\n  const intersectionNums = [];\n\n  for (let numsList of nums) {\n    for (let num of numsList) {\n      if (numberCounts.has(num)) {\n        numberCounts.set(num, numberCounts.get(num) + 1);\n      } else {\n        numberCounts.set(num, 1);\n      }\n    }\n  }\n\n  for (let [num, count] of numberCounts.entries()) {\n    if (count === numsLength) {\n      intersectionNums.push(num);\n    }\n  }\n\n  return intersectionNums.sort((a, b) => a - b);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/intersection-of-two-arrays-ii/intersection-of-two-arrays-ii.js",
    "content": "/*\nnums1 = [1,2,2,1], nums2 = [2,2] => [2] => []\nresult = [2,2]\nRuntime: O(N^3)\nSpace: O(N)\n\nnums1 = [1,2,2,1], nums2 = [2,2]\nhashmap = { 1: 2, 2: 2 }; => { 1: 2, 2: 1 }; => { 1: 2, 2: 0 };\nresult = [2, 2]\nRuntime: O(N) + O(N) => O(N)\nSpace: O(N) + O(N) => O(N)\n*/\n\nfunction intersect(nums1, nums2) {\n  let numsCount = {};\n\n  for (let num of nums1) {\n    if (numsCount[num]) {\n      numsCount[num]++;\n    } else {\n      numsCount[num] = 1;\n    }\n  }\n\n  let result = [];\n\n  for (let num of nums2) {\n    if (numsCount[num]) {\n      numsCount[num]--;\n      result.push(num);\n    }\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/intersection_of_two_arrays/intersection_of_two_arrays.py",
    "content": "# https://leetcode.com/problems/intersection-of-two-arrays/\n\n\ndef intersection(nums1, nums2):\n    intersect_set = set()\n    \n    for num1 in nums1:\n        for num2 in nums2:\n            if num1 == num2:\n                intersect_set.add(num1)\n                \n    return intersect_set\n\ndef intersection(nums1, nums2):\n    return set(nums1).intersection(nums2)\n\n\ndef intersection(nums1, nums2):\n    nums_mapper = {}\n\n    for num in nums1:\n        nums_mapper[num] = True\n\n    nums = set()\n\n    for num in nums2:\n        if num in nums_mapper:\n            nums.add(num)\n\n    return nums"
  },
  {
    "path": "coding_interviews/leetcode/easy/intersection_of_two_arrays_ii/intersection_of_two_arrays.py",
    "content": "# https://leetcode.com/problems/intersection-of-two-arrays-ii\n\n\ndef intersection(nums1, nums2):\n    hash_map = {}\n\n    for num in nums1:\n        if num in hash_map:\n            hash_map[num] += 1\n        else:\n            hash_map[num] = 1\n\n    nums = []\n\n    for num in nums2:\n        if num in hash_map and hash_map[num]:\n            nums.append(num)\n            hash_map[num] -= 1\n\n    return nums"
  },
  {
    "path": "coding_interviews/leetcode/easy/invert-binary-tree/invert-binary-tree.js",
    "content": "function invertTree(root) {\n  if (!root) {\n    return root;\n  }\n\n  let leftNode = root.left;\n  let rightNode = root.right;\n\n  root.left = invertTree(rightNode);\n  root.right = invertTree(leftNode);\n\n  return root;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/is-subsequence/is-subsequence.js",
    "content": "// https://leetcode.com/problems/is-subsequence\n\nfunction isSubsequence(s, t) {\n  let sIndex = 0;\n  let tIndex = 0;\n\n  while (sIndex < s.length && tIndex < t.length) {\n    let sChar = s[sIndex];\n    let tChar = t[tIndex];\n\n    if (sChar === tChar) {\n      sIndex++;\n      tIndex++;\n    } else {\n      tIndex++;\n    }\n  }\n\n  return sIndex === s.length;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/is_palindrome.py",
    "content": "# https://leetcode.com/problems/palindrome-number/description/\n\ndef is_palindrome(x):\n    if x < 0:\n        return False\n\n    s = ''\n\n    while x > 0:\n        s += str(x % 10)\n        x /= 10\n\n    return s == s[::-1]\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/is_sum_equal/is_sum_equal.py",
    "content": "# https://leetcode.com/problems/check-if-word-equals-summation-of-two-words\n\nalphabet = {\n    'a': '0',\n    'b': '1',\n    'c': '2',\n    'd': '3',\n    'e': '4',\n    'f': '5',\n    'g': '6',\n    'h': '7',\n    'i': '8',\n    'j': '9',\n}\n\ndef get_numerical_value(word):\n    list_of_chars = []\n    \n    for char in word:\n        list_of_chars.append(alphabet[char])\n        \n    return int(''.join(list_of_chars))\n\ndef is_sum_equal(first_word, second_word, target_word):\n    first_num = get_numerical_value(first_word)\n    second_num = get_numerical_value(second_word)\n    target_num = get_numerical_value(target_word)\n    return first_num + second_num == target_num\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/island-perimeter/island-perimeter.js",
    "content": "function isOffGrid(grid, row, col) {\n  return row < 0 || row >= grid.length || col < 0 || col >= grid[0].length;\n}\n\nfunction isWater(grid, row, col) {\n  return grid[row][col] === 0;\n}\n\nfunction isPartOfIsland(grid, row, col) {\n  return grid[row][col] === 1;\n}\n\nfunction wasAlreadyVisited(grid, row, col) {\n  return grid[row][col] === 2;\n}\n\nfunction dfs(grid, row, col) {\n  if (isOffGrid(grid, row, col) || isWater(grid, row, col)) {\n    return 1;\n  }\n\n  if (wasAlreadyVisited(grid, row, col)) {\n    return 0;\n  }\n\n  grid[row][col] = 2;\n\n  return (\n    dfs(grid, row, col - 1) +\n    dfs(grid, row, col + 1) +\n    dfs(grid, row - 1, col) +\n    dfs(grid, row + 1, col)\n  );\n}\n\nfunction islandPerimeter(grid) {\n  let perimeter = 0;\n\n  for (let row = 0; row < grid.length; row++) {\n    for (let col = 0; col < grid[row].length; col++) {\n      if (isPartOfIsland(grid, row, col)) {\n        perimeter += dfs(grid, row, col);\n      }\n    }\n  }\n\n  return perimeter;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/jewels_and_stones.py",
    "content": "# https://leetcode.com/problems/jewels-and-stones/description/\n\n# input: J = \"aA\" | S = \"aAAbbbb\"\n# output: 3\n\n# input: J = \"z\", S = \"ZZ\"\n# output: 0\n\n# Solution: O(N^2)\n\n\ndef num_jewels_in_stones(J, S):\n    jewels = 0\n\n    for j in J:\n        for s in S:\n            if s == j:\n                jewels += 1\n\n    return jewels\n\n\nprint(num_jewels_in_stones(\"aA\", \"aAAbbbb\"))\nprint(num_jewels_in_stones(\"z\", \"ZZ\"))\n\n# Solution: O(N)\n\n\ndef num_jewels_in_stones_opt(J, S):\n    number_by_chars = {}\n    counter = 0\n\n    for char in J:\n        if char in number_by_chars:\n            number_by_chars[char] += 1\n        else:\n            number_by_chars[char] = 1\n\n    for char in S:\n        if char in number_by_chars:\n            counter += number_by_chars[char]\n\n    return counter\n\n\nprint(num_jewels_in_stones_opt(\"aA\", \"aAAbbbb\"))\nprint(num_jewels_in_stones_opt(\"z\", \"ZZ\"))\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/judge_route_circle.py",
    "content": "'''\nhttps://leetcode.com/problems/judge-route-circle/description/\n\nExample 1:\nInput: \"UD\"\nOutput: true\n\nExample 2:\nInput: \"LL\"\nOutput: false\n'''\n\ndef judge_circle(moves):\n    horizontal, vertical = 0, 0\n    moves_mapper = { 'U': 1, 'D': -1, 'R': 1, 'L': -1 }\n    for move in moves:\n        if move in ['U', 'D']:\n            vertical += moves_mapper[move]\n        else:\n            horizontal += moves_mapper[move]\n\n    return horizontal == 0 and vertical == 0\n\nprint(judge_circle(\"UD\"))\nprint(judge_circle(\"LL\"))\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/judge_route_circle_one_line.py",
    "content": "'''\nhttps://leetcode.com/problems/judge-route-circle/description/\n\nExample 1:\nInput: \"UD\"\nOutput: true\n\nExample 2:\nInput: \"LL\"\nOutput: false\n'''\n\ndef judge_circle(moves):\n    return moves.count(\"U\") == moves.count(\"D\") and moves.count(\"R\") == moves.count(\"L\")\n\nprint(judge_circle(\"UD\"))\nprint(judge_circle(\"LL\"))\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/k-items-with-the-maximum-sum/k-items-with-the-maximum-sum-second.js",
    "content": "// https://leetcode.com/problems/k-items-with-the-maximum-sum\n\nfunction kItemsWithMaximumSum(numOnes, numZeros, numNegOnes, k) {\n  if (k <= numOnes) {\n    return k;\n  }\n\n  let sum = 0;\n\n  if (numOnes) {\n    sum += numOnes;\n    k -= numOnes;\n  }\n\n  if (k > 0 && numZeros) {\n    k -= numZeros;\n  }\n\n  if (k > 0 && numNegOnes) {\n    sum -= k;\n  }\n\n  return sum;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/k-items-with-the-maximum-sum/k-items-with-the-maximum-sum.js",
    "content": "// https://leetcode.com/problems/k-items-with-the-maximum-sum\n\nfunction kItemsWithMaximumSum(numOnes, numZeros, numNegOnes, k) {\n  let max = 0;\n  let mutK = k;\n\n  mutK -= numOnes;\n  if (mutK <= 0) return k;\n  max += numOnes;\n  mutK -= numZeros;\n  if (mutK <= 0) return max;\n  if (mutK - numNegOnes < 0) return max - mutK;\n  max -= numNegOnes;\n  return max;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/keep-multiplying-found-values-by-two/keep-multiplying-found-values-by-two.js",
    "content": "function findFinalValue(nums, original) {\n  let keepProcessing = true;\n  let originalCopy = original;\n\n  while (keepProcessing) {\n    let foundOriginal = false;\n\n    for (let num of nums) {\n      if (num === originalCopy) {\n        foundOriginal = true;\n      }\n    }\n\n    if (foundOriginal) {\n      originalCopy *= 2;\n    } else {\n      keepProcessing = false;\n    }\n  }\n\n  return originalCopy;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/keyboard-row/keyboard-row.js",
    "content": "function stringToMap(string) {\n  const map = new Map();\n\n  for (let char of string) {\n    map.set(char, true);\n  }\n\n  return map;\n}\n\nconst firstRow = stringToMap('qwertyuiop');\nconst secondRow = stringToMap('asdfghjkl');\nconst thirdRow = stringToMap('zxcvbnm');\n\nfunction belongsToRow(word, row) {\n  for (let char of word) {\n    if (!row.has(char)) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nfunction belongsToSomeRow(word) {\n  let belongsToARow = belongsToRow(word, firstRow);\n  if (belongsToARow) return true;\n  belongsToARow = belongsToRow(word, secondRow);\n  if (belongsToARow) return true;\n  belongsToARow = belongsToRow(word, thirdRow);\n  return belongsToARow;\n}\n\nfunction findWords(words) {\n  const result = [];\n\n  for (let word of words) {\n    if (belongsToSomeRow(word.toLowerCase())) {\n      result.push(word);\n    }\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/kth-distinct-string-in-an-array/kth-distinct-string-in-an-array.js",
    "content": "function kthDistinct(arr, k) {\n  let count = 0;\n  let hashmap = new Map();\n\n  for (let string of arr) {\n    if (hashmap.has(string)) {\n      hashmap.set(string, hashmap.get(string) + 1);\n    } else {\n      hashmap.set(string, 1);\n    }\n  }\n\n  let distinctStrings = [];\n\n  hashmap.forEach((count, string) => {\n    if (count === 1) {\n      distinctStrings.push(string);\n    }\n  });\n\n  for (let string of distinctStrings) {\n    count++;\n    if (count === k) return string;\n  }\n\n  return '';\n}\n\nfunction kthDistinct(arr, k) {\n  let hashmap = new Map();\n\n  for (let string of arr) {\n    if (hashmap.has(string)) {\n      hashmap.set(string, hashmap.get(string) + 1);\n    } else {\n      hashmap.set(string, 1);\n    }\n  }\n\n  let distinctStrings = [];\n\n  hashmap.forEach((count, string) => {\n    if (count === 1) {\n      distinctStrings.push(string);\n    }\n  });\n\n  return distinctStrings[k - 1] || '';\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/largest-local-values-in-a-matrix/largest-local-values-in-a-matrix.js",
    "content": "function getLargestFromGrid(grid, startRow, startCol, endRow, endCol) {\n  let largest = -Infinity;\n\n  for (let row = startRow; row <= endRow; row++) {\n    for (let col = startCol; col <= endCol; col++) {\n      largest = Math.max(largest, grid[row][col]);\n    }\n  }\n\n  return largest;\n}\n\nfunction largestLocal(grid) {\n  const generatedGrid = [];\n\n  for (let row = 0; row < grid.length - 2; row++) {\n    const generatedRow = [];\n\n    for (let col = 0; col < grid[row].length - 2; col++) {\n      generatedRow.push(getLargestFromGrid(grid, row, col, row + 2, col + 2));\n    }\n\n    generatedGrid.push(generatedRow);\n  }\n\n  return generatedGrid;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/largest-number-after-digit-swaps-by-parity/largest-number-after-digit-swaps-by-parity.js",
    "content": "// https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity\n\nconst isEven = (num) => num % 2 === 0;\nconst isOdd = (num) => !isEven(num);\n\nfunction largestInteger(num) {\n  let numString = num.toString().split('');\n\n  for (let index = 0; index < numString.length - 1; index++) {\n    let digit = Number(numString[index]);\n    let isDigitEven = isEven(digit);\n    let maxDigit = digit;\n    let swapIndex1 = index;\n    let swapIndex2;\n\n    for (\n      let digitIndex = index + 1;\n      digitIndex < numString.length;\n      digitIndex++\n    ) {\n      let otherDigit = Number(numString[digitIndex]);\n      let isOtherDigitEven = isEven(otherDigit);\n\n      if (isDigitEven && isOtherDigitEven && otherDigit > maxDigit) {\n        maxDigit = otherDigit;\n        swapIndex2 = digitIndex;\n      }\n\n      if (!isDigitEven && !isOtherDigitEven && otherDigit > maxDigit) {\n        maxDigit = otherDigit;\n        swapIndex2 = digitIndex;\n      }\n    }\n\n    if (swapIndex2) {\n      let aux = numString[swapIndex1];\n      numString[swapIndex1] = numString[swapIndex2];\n      numString[swapIndex2] = aux;\n    }\n  }\n\n  return numString.join('');\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/largest-positive-integer-that-exists-with-its-negative/largest-positive-integer-that-exists-with-its-negative.js",
    "content": "function findMaxK(nums) {\n  const hashmap = new Map();\n\n  for (let num of nums) {\n    if (!hashmap.has(num)) hashmap.set(num, true);\n  }\n\n  let output = -1;\n\n  for (let num of nums) {\n    if (num > output && hashmap.has(num * -1)) {\n      output = num;\n    }\n  }\n\n  return output;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/last-stone-weight/last-stone-weight.js",
    "content": "function getTwoHaviest(stones) {\n  const first = stones[0];\n  const second = stones[1];\n\n  let heaviest = first > second ? first : second;\n  let secondHeaviest = first > second ? second : first;\n\n  for (let i = 2; i < stones.length; i++) {\n    const stone = stones[i];\n\n    if (stone > heaviest) {\n      secondHeaviest = heaviest;\n      heaviest = stone;\n      continue;\n    }\n\n    if (stone > secondHeaviest) {\n      secondHeaviest = stone;\n      continue;\n    }\n  }\n\n  return { heaviest, secondHeaviest };\n}\n\nfunction removeStone(stones, stoneToBeRemoved) {\n  for (let i = 0; i < stones.length; i++) {\n    if (stones[i] === stoneToBeRemoved) {\n      stones.splice(i, 1);\n      return;\n    }\n  }\n}\n\nfunction updateStone(stones, stone, stoneWeight) {\n  for (let i = 0; i < stones.length; i++) {\n    if (stones[i] === stone) {\n      stones[i] = stoneWeight;\n      return;\n    }\n  }\n}\n\nexport function lastStoneWeight(stones) {\n  while (stones.length > 1) {\n    const { heaviest, secondHeaviest } = getTwoHaviest(stones);\n\n    if (heaviest === secondHeaviest) {\n      removeStone(stones, heaviest);\n      removeStone(stones, secondHeaviest);\n    }\n\n    if (heaviest !== secondHeaviest) {\n      updateStone(stones, heaviest, heaviest - secondHeaviest);\n      removeStone(stones, secondHeaviest);\n    }\n  }\n\n  return stones[0] || 0;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/last-stone-weight/tests/last-stone-weight.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { lastStoneWeight } from '../last-stone-weight';\n\ndescribe('lastStoneWeight', () => {\n  it('', () => {\n    expect(lastStoneWeight([2, 7, 4, 1, 8, 1])).toEqual(1);\n  });\n\n  it('', () => {\n    expect(lastStoneWeight([1])).toEqual(1);\n  });\n\n  it('', () => {\n    expect(lastStoneWeight([2, 2])).toEqual(0);\n  });\n\n  it('', () => {\n    expect(lastStoneWeight([10, 4, 2, 10])).toEqual(2);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/last-visited-integers/last-visited-integers.js",
    "content": "// https://leetcode.com/problems/last-visited-integers\n\nfunction getLastInteger(words, lastNumberIndex, consecutivePrevs) {\n  for (let index = lastNumberIndex; index >= 0; index--) {\n    while (words[index] === 'prev') {\n      index--;\n    }\n\n    if (index < 0) {\n      return -1;\n    }\n\n    if (consecutivePrevs === 0) {\n      return words[index];\n    }\n\n    if (words[index] !== 'prev') {\n      consecutivePrevs--;\n    }\n  }\n\n  return -1;\n}\n\nfunction lastVisitedIntegers(words) {\n  let result = [];\n  let consecutivePrevs = 0;\n  let lastNumberIndex;\n\n  for (let index = 0; index < words.length; index++) {\n    if (words[index] === 'prev') {\n      result.push(getLastInteger(words, lastNumberIndex, consecutivePrevs));\n      consecutivePrevs++;\n    } else {\n      lastNumberIndex = index;\n      consecutivePrevs = 0;\n    }\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/leaf-similar-trees/leaf-similar-trees.js",
    "content": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n\nfunction getLeafValueSequence(node, leafValueSequence) {\n  if (!node) return;\n  if (!node.left && !node.right) {\n    leafValueSequence.push(node.val);\n    return;\n  }\n\n  getLeafValueSequence(node.left, leafValueSequence);\n  getLeafValueSequence(node.right, leafValueSequence);\n}\n\nfunction hasSimilarLeafSequence(leafValueSequence1, leafValueSequence2) {\n  if (leafValueSequence1.length !== leafValueSequence2.length) return false;\n\n  for (let index = 0; index < leafValueSequence1.length; index++) {\n    if (leafValueSequence1[index] !== leafValueSequence2[index]) return false;\n  }\n\n  return true;\n}\n\nfunction leafSimilar(root1, root2) {\n  let leafValueSequence1 = [];\n  let leafValueSequence2 = [];\n\n  getLeafValueSequence(root1, leafValueSequence1);\n  getLeafValueSequence(root2, leafValueSequence2);\n\n  return hasSimilarLeafSequence(leafValueSequence1, leafValueSequence2);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/left-and-right-sum-differences/left-and-right-sum-differences.js",
    "content": "function sum(nums) {\n  let sumOfNums = 0;\n\n  for (let num of nums) {\n    sumOfNums += num;\n  }\n\n  return sumOfNums;\n}\n\nfunction leftRigthDifference(nums) {\n  let rightSum = sum(nums);\n  let leftSum = 0;\n  let previous = 0;\n  let answer = [];\n\n  for (let num of nums) {\n    leftSum += previous;\n    rightSum -= num;\n    previous = num;\n    answer.push(Math.abs(leftSum - rightSum));\n  }\n\n  return answer;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/length-of-last-word/length-of-last-word.js",
    "content": "// https://leetcode.com/problems/length-of-last-word\n\nconst lengthOfLastWord = (s) => {\n  const words = s.trim().split(' ');\n  return words[words.length - 1].length;\n};\n\nconst lengthOfLastWord = (s) => {\n  let lastWordLength = 0;\n\n  for (let i = s.length - 1; i >= 0; i--) {\n    if (s[i] !== ' ') lastWordLength++;\n    if (s[i] === ' ' && lastWordLength > 0) break;\n  }\n\n  return lastWordLength;\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/lexicographically-smallest-palindrome/lexicographically-smallest-palindrome.js",
    "content": "function makeSmallestPalindrome(string) {\n  let start = 0;\n  let end = string.length - 1;\n  let palindrome = [];\n\n  while (start <= end) {\n    let charCode1 = string.charCodeAt(start);\n    let charCode2 = string.charCodeAt(end);\n\n    if (charCode1 <= charCode2) {\n      palindrome[start] = string[start];\n      palindrome[end] = string[start];\n    }\n\n    if (charCode2 < charCode1) {\n      palindrome[start] = string[end];\n      palindrome[end] = string[end];\n    }\n\n    start++;\n    end--;\n  }\n\n  return palindrome.join('');\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/linked-list-cycle/linked-list-cycle.js",
    "content": "function hasCycle(head) {\n  let fast = head;\n\n  while (fast && fast.next) {\n    head = head.next;\n    fast = fast.next.next;\n\n    if (head === fast) {\n      return true;\n    }\n  }\n\n  return false;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/longer-contiguous-segments-of-ones-than-zeros/longer-contiguous-segments-of-ones-than-zeros.js",
    "content": "function checkZeroOnes(s) {\n  let zerosLongestContinuousSegment = 0;\n  let onesLongestContinuousSegment = 0;\n  let zerosContinuousSegment = 0;\n  let onesContinuousSegment = 0;\n\n  for (let index = 0; index < s.length; index++) {\n    let char = s[index];\n\n    if (char === '1') {\n      zerosLongestContinuousSegment = Math.max(\n        zerosLongestContinuousSegment,\n        zerosContinuousSegment\n      );\n      zerosContinuousSegment = 0;\n      onesContinuousSegment++;\n    } else {\n      onesLongestContinuousSegment = Math.max(\n        onesLongestContinuousSegment,\n        onesContinuousSegment\n      );\n      onesContinuousSegment = 0;\n      zerosContinuousSegment++;\n    }\n\n    if (index === s.length - 1) {\n      if (char === '1') {\n        onesLongestContinuousSegment = Math.max(\n          onesLongestContinuousSegment,\n          onesContinuousSegment\n        );\n      } else {\n        zerosLongestContinuousSegment = Math.max(\n          zerosLongestContinuousSegment,\n          zerosContinuousSegment\n        );\n      }\n    }\n  }\n\n  return onesLongestContinuousSegment > zerosLongestContinuousSegment;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/longest-nice-substring/longest-nice-substring.js",
    "content": "function isNice(substring, map) {\n  for (let char of substring) {\n    if (!map.has(char.toLowerCase()) || !map.has(char.toUpperCase())) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nfunction longestNiceSubstring(s) {\n  let substring = '';\n\n  for (let i = 0; i < s.length; i++) {\n    let newSubstring = [s[i]];\n    let map = new Map([[s[i], true]]);\n\n    for (let j = i + 1; j < s.length; j++) {\n      newSubstring.push(s[j]);\n      map.set(s[j], true);\n\n      if (isNice(newSubstring, map) && newSubstring.length > substring.length) {\n        substring = newSubstring.join('');\n      }\n    }\n  }\n\n  return substring;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/longest-subsequence-with-limited-sum/longest-subsequence-with-limited-sum.js",
    "content": "function immutableSort(nums) {\n  return [...nums].sort((a, b) => a - b);\n}\n\nfunction buildAllSums(nums) {\n  let allSums = [];\n  let sum = 0;\n\n  for (num of nums) {\n    sum += num;\n    allSums.push(sum);\n  }\n\n  return allSums;\n}\n\nfunction answerQueries(nums, queries) {\n  let answer = [];\n  let sortedNums = immutableSort(nums);\n  let allSums = buildAllSums(sortedNums);\n\n  for (let query of queries) {\n    let num;\n\n    for (let index = 0; index < allSums.length; index++) {\n      let sum = allSums[index];\n\n      if (sum <= query) {\n        num = index + 1;\n        if (index === allSums.length - 1) answer.push(num);\n      } else {\n        if (num) answer.push(num);\n        break;\n      }\n    }\n\n    if (!num) answer.push(0);\n  }\n\n  return answer;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/longest_palindrome.py",
    "content": "def count_pairs(letters):\n    hash = {}\n    result = {\"pair\": 0, \"single\": 0}\n\n    for letter in letters:\n        if hash.get(letter):\n            hash[letter] += 1\n        else:\n            hash[letter] = 1\n\n    for k, v in hash.items():\n        if v > 1:\n            result[\"pair\"] += v - (v % 2)\n            result[\"single\"] += v % 2\n        else:\n            result[\"single\"] += 1\n\n    return result\n\n\ndef main(letters):\n    counter = 0\n\n    pairs = count_pairs(letters)\n    counter += pairs[\"pair\"]\n\n    if pairs[\"single\"] > 0:\n        counter += 1\n\n    return counter\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/lowest-common-ancestor-of-a-binary-search-tree/lowest-common-ancestor-of-a-binary-search-tree.js",
    "content": "function lowestCommonAncestor(root, p, q) {\n  if (root === p || root === q) {\n    return root;\n  }\n\n  if (\n    (p.val < root.val && q.val > root.val) ||\n    (p.val > root.val && q.val < root.val)\n  ) {\n    return root;\n  }\n\n  if (p.val < root.val && q.val < root.val) {\n    return lowestCommonAncestor(root.left, p, q);\n  }\n\n  if (p.val > root.val && q.val > root.val) {\n    return lowestCommonAncestor(root.right, p, q);\n  }\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/lucky_numbers_in_a_matrix/lucky_numbers_in_a_matrix.py",
    "content": "# https://leetcode.com/problems/lucky-numbers-in-a-matrix\n\ndef lucky_numbers(matrix):\n    all_lucky_numbers, all_mins = [], []\n    \n    for row in matrix:\n        found_min, col_index = float('Inf'), -1\n        \n        for index, column in enumerate(row):\n            if column < found_min:\n                found_min = column\n                col_index = index\n        \n        all_mins.append([found_min, col_index])\n        \n    for a_min in all_mins:\n        [min_value, min_column] = a_min\n        maximum = float('-Inf')\n        \n        for index in range(len(matrix)):\n            num = matrix[index][min_column]\n            maximum = max(num, maximum)\n            \n        if maximum == min_value:\n            all_lucky_numbers.append(min_value)\n            \n    return all_lucky_numbers\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/majority-element/majority-element.js",
    "content": "function majorityElement(nums) {\n  let hashmap = {};\n  let result;\n\n  for (let num of nums) {\n    if (hashmap[num]) {\n      hashmap[num]++;\n    } else {\n      hashmap[num] = 1;\n    }\n  }\n\n  Object.entries(hashmap).forEach(([num, count]) => {\n    if (count > nums.length / 2) {\n      result = num;\n    }\n  });\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/make-array-zero-by-subtracting-equal-amounts/make-array-zero-by-subtracting-equal-amounts.js",
    "content": "function minimumOperationsAllInOne(nums) {\n  let count = 0;\n  let smallest = 0;\n\n  for (let num of nums) {\n    if (num > 0) {\n      smallest = smallest ? Math.min(smallest, num) : num;\n    }\n  }\n\n  while (smallest) {\n    let smallestToSubtract = smallest;\n    smallest = 0;\n\n    for (let index = 0; index < nums.length; index++) {\n      let subtractionResult = nums[index] - smallestToSubtract;\n      nums[index] = subtractionResult > 0 ? subtractionResult : 0;\n\n      if (subtractionResult > 0) {\n        smallest = smallest\n          ? Math.min(smallest, subtractionResult)\n          : subtractionResult;\n      }\n    }\n\n    count++;\n  }\n\n  return count;\n}\n\n// --------------------------------------------------\n\nfunction smallestExceptZeros(smallest, num) {\n  return smallest ? Math.min(smallest, num) : num;\n}\n\nfunction getSmallest(nums) {\n  let smallest = 0;\n\n  for (let num of nums) {\n    if (num > 0) {\n      smallest = smallestExceptZeros(smallest, num);\n    }\n  }\n\n  return smallest;\n}\n\nfunction performSubtraction(nums, smallestToSubtract, smallest) {\n  for (let index = 0; index < nums.length; index++) {\n    let subtractionResult = nums[index] - smallestToSubtract;\n    nums[index] = subtractionResult > 0 ? subtractionResult : 0;\n\n    if (subtractionResult > 0) {\n      smallest = smallestExceptZeros(smallest, subtractionResult);\n    }\n  }\n\n  return smallest;\n}\n\nfunction minimumOperations(nums) {\n  let count = 0;\n  let smallest = getSmallest(nums);\n\n  while (smallest) {\n    smallest = performSubtraction(nums, smallest, 0);\n    count++;\n  }\n\n  return count;\n}\n\n// --------------------------------------------------\n\nfunction minimumOperationsSet(nums) {\n  return new Set(nums.filter((num) => num !== 0));\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/make-the-string-great/make-the-string-great.js",
    "content": "function isUpperCase(char1, char2) {\n  return char1 !== char1.toUpperCase() && char1.toUpperCase() === char2;\n}\n\nfunction isLowerCase(char1, char2) {\n  return char2.toLowerCase() !== char2 && char2.toLowerCase() === char1;\n}\n\nfunction isBadPair(char1, char2) {\n  return (\n    isUpperCase(char1, char2) ||\n    isUpperCase(char2, char1) ||\n    isLowerCase(char1, char2) ||\n    isLowerCase(char2, char1)\n  );\n}\n\nfunction makeGood(string, pointer1 = 0, pointer2 = 1) {\n  if (string.length <= 1) return string;\n  if (pointer2 === string.length) return string;\n  console.log(\n    string[pointer1],\n    string[pointer2],\n    isBadPair(string[pointer1], string[pointer2])\n  );\n  if (isBadPair(string[pointer1], string[pointer2])) {\n    return makeGood(\n      string.slice(0, pointer1) + string.slice(pointer2 + 1),\n      0,\n      1\n    );\n  }\n\n  return makeGood(string, pointer1 + 1, pointer2 + 1);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/matrix-cells-in-distance-order/matrix-cells-in-distance-order.js",
    "content": "function sortDistances(distances) {\n  return [...distances].sort((distance1, distance2) => distance1 - distance2);\n}\n\nfunction allCellsDistOrder(rows, cols, rCenter, cCenter) {\n  const distancesMap = new Map();\n  const distances = [];\n\n  for (let row = 0; row < rows; row++) {\n    for (let col = 0; col < cols; col++) {\n      const distance = Math.abs(row - rCenter) + Math.abs(col - cCenter);\n\n      if (distancesMap.has(distance)) {\n        distancesMap.set(distance, [...distancesMap.get(distance), [row, col]]);\n      } else {\n        distances.push(distance);\n        distancesMap.set(distance, [[row, col]]);\n      }\n    }\n  }\n\n  return sortDistances(distances)\n    .map((distance) => distancesMap.get(distance))\n    .flatMap((cell) => cell);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/matrix_diagonal_sum/matrix_diagonal_sum.py",
    "content": "# https://leetcode.com/problems/matrix-diagonal-sum\n\n'''\nTime Complexity: O(N)\nSpace Complexity: O(1)\n'''\n\ndef diagonal_sum(mat):\n    diagonals_sum, mat_length = 0, len(mat)\n    \n    # left-top --> right-bottom & right-top --> left-bottom\n    for index in range(mat_length):\n        diagonals_sum += mat[index][index] + mat[index][mat_length-index-1]\n        \n    if len(mat) % 2 == 0:\n        return diagonals_sum\n    \n    center = mat_length // 2\n    return diagonals_sum - mat[center][center]]\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/matrix_negative_numbers/matrix_negative_numbers.py",
    "content": "def count_negatives(grid):\n    counter = 0\n\n    for i in range(len(grid)):\n        for j in range(len(grid[i])):\n            if grid[i][j] < 0:\n                counter += 1\n\n    return counter\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/max-consecutive-ones/max-consecutive-ones.js",
    "content": "function findMaxConsecutiveOnes(nums) {\n  let max = 0;\n  let consecutive = 0;\n\n  for (let index = 0; index < nums.length; index++) {\n    if (nums[index] === 1) consecutive++;\n    if (nums[index] === 0 || index === nums.length - 1) {\n      max = Math.max(max, consecutive);\n      consecutive = 0;\n    }\n  }\n\n  return max;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum-69-number/maximum-69-number.js",
    "content": "function maximum69Number(num) {\n  let nums = String(num).split('');\n  let firstSixIndex;\n\n  for (let index = 0; index < nums.length; index++) {\n    if (nums[index] === '6' && firstSixIndex === undefined) {\n      firstSixIndex = index;\n    }\n  }\n\n  nums[firstSixIndex] = '9';\n\n  return Number(nums.join(''));\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum-ascending-subarray-sum/maximum-ascending-subarray-sum.js",
    "content": "function maxAscendingSum(nums) {\n  let max = 0;\n  let maxSubsequence = 0;\n  let previous = -Infinity;\n\n  for (let index = 0; index < nums.length; index++) {\n    let num = nums[index];\n\n    if (num > previous) {\n      maxSubsequence += num;\n      previous = num;\n\n      if (index === nums.length - 1) max = Math.max(max, maxSubsequence);\n    } else {\n      max = Math.max(max, maxSubsequence);\n      previous = num;\n      maxSubsequence = num;\n    }\n  }\n\n  return max;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum-count-of-positive-integer-and-negative-integer/maximum-count-of-positive-integer-and-negative-integer.js",
    "content": "function maximumCount(nums) {\n  let pos = 0;\n  let neg = 0;\n\n  for (let num of nums) {\n    if (num > 0) pos++;\n    if (num < 0) neg++;\n  }\n\n  return Math.max(pos, neg);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum-depth-of-binary-tree/maximum-depth-of-binary-tree-2.js",
    "content": "function getMaximumDepth(node, depth) {\n  if (!node) {\n    return depth;\n  }\n\n  return Math.max(\n    getMaximumDepth(node.left, depth + 1),\n    getMaximumDepth(node.right, depth + 1)\n  );\n}\n\nfunction maxDepth(root) {\n  if (!root) {\n    return 0;\n  }\n\n  return Math.max(\n    getMaximumDepth(root.left, 1),\n    getMaximumDepth(root.right, 1)\n  );\n}\n\n// shorter without a helper function\nfunction maxDepth(root, depth = 0) {\n  return root\n    ? Math.max(maxDepth(root.left, depth + 1), maxDepth(root.right, depth + 1))\n    : depth;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.js",
    "content": "// https://leetcode.com/problems/maximum-depth-of-binary-tree\n\nconst maxDepth = (root) => maxDepthHelper(root, 0);\n\nconst maxDepthHelper = (node, depth) => {\n  if (!node) return depth;\n  const leftDepth = maxDepthHelper(node.left, depth + 1);\n  const rightDepth = maxDepthHelper(node.right, depth + 1);\n  return Math.max(leftDepth, rightDepth);\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum-depth-of-n-ary-tree/maximum-depth-of-n-ary-tree.js",
    "content": "function maxDepth(root, depth = 1) {\n  if (!root) return depth - 1;\n\n  let depths = [];\n\n  for (let child of root.children) {\n    const childDepth = maxDepth(child, depth + 1);\n    depths.push(childDepth);\n  }\n\n  return depths.length ? Math.max(...depths) : depth;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum-number-of-balloons/maximum-number-of-balloons.js",
    "content": "function buildHashmap(text) {\n  const hashmap = new Map();\n\n  for (let char of text) {\n    if (hashmap.has(char)) hashmap.set(char, hashmap.get(char) + 1);\n    else hashmap.set(char, 1);\n  }\n\n  return hashmap;\n}\n\nfunction maxNumberOfBalloons(text) {\n  let hashmap = buildHashmap(text);\n  let minCharCount = Infinity;\n  let balloon = 'balon';\n\n  for (let char of balloon) {\n    if (!hashmap.has(char)) return 0;\n    if (['l', 'o'].includes(char))\n      minCharCount = Math.min(minCharCount, Math.floor(hashmap.get(char) / 2));\n    else minCharCount = Math.min(minCharCount, hashmap.get(char));\n  }\n\n  return minCharCount;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum-number-of-pairs-in-array/maximum-number-of-pairs-in-array.js",
    "content": "function numberOfPairs(nums) {\n  let countNums = new Map();\n\n  for (let num of nums) {\n    if (countNums.has(num)) {\n      countNums.set(num, countNums.get(num) + 1);\n    } else {\n      countNums.set(num, 1);\n    }\n  }\n\n  let pairs = 0;\n  let rest = 0;\n\n  countNums.forEach((num) => {\n    pairs += Math.floor(num / 2);\n    rest += Math.floor(num % 2);\n  });\n\n  return [pairs, rest];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum-odd-binary-number/maximum-odd-binary-number.js",
    "content": "// https://leetcode.com/problems/maximum-odd-binary-number\n\nfunction countOnesAndZeros(s) {\n  let countOnes = 0;\n  let countZeros = 0;\n\n  for (let char of s) {\n    if (char === '1') {\n      countOnes++;\n    } else {\n      countZeros++;\n    }\n  }\n\n  return { countOnes, countZeros };\n}\n\nfunction maximumOddBinaryNumber(s) {\n  const { countOnes, countZeros } = countOnesAndZeros(s);\n  let result = '';\n\n  for (let one = 1; one <= countOnes - 1; one++) {\n    result += '1';\n  }\n\n  for (let zero = 1; zero <= countZeros; zero++) {\n    result += '0';\n  }\n\n  return result + '1';\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum-subarray/maximum-subarray.js",
    "content": "function maxSubArray(nums) {\n  let maxSum = nums[0];\n  let localSum = nums[0];\n\n  for (let index = 1; index < nums.length; index++) {\n    localSum = Math.max(nums[index], localSum + nums[index]);\n    maxSum = Math.max(maxSum, localSum);\n  }\n\n  return maxSum;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum-sum-with-exactly-k-elements/maximum-sum-with-exactly-k-elements.js",
    "content": "function getBiggest(nums) {\n  let biggest = -Infinity;\n\n  for (let num of nums) {\n    biggest = Math.max(biggest, num);\n  }\n\n  return biggest;\n}\n\nfunction maximizeSum(nums, k) {\n  let biggest = getBiggest(nums);\n  let sum = 0;\n\n  while (k--) {\n    sum += biggest;\n    biggest++;\n  }\n\n  return sum;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum-units-on-a-truck/maximum-units-on-a-truck.py",
    "content": "# https://leetcode.com/problems/maximum-units-on-a-truck\n\ndef maximum_units(box_types, truck_size):\n    sorted_by_units_per_box = sorted(box_types, key=lambda box_type: box_type[1], reverse=True)\n    \n    units = 0\n    \n    for [num_of_boxes, num_of_units] in sorted_by_units_per_box:\n        num_of_boxes_to_put_on_the_truck = min(truck_size, num_of_boxes)\n        truck_size -= num_of_boxes_to_put_on_the_truck\n        units += num_of_boxes_to_put_on_the_truck * num_of_units\n        if truck_size <= 0: break\n            \n    return units\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum-value-of-a-string-in-an-array/maximum-value-of-a-string-in-an-array.js",
    "content": "function maximumValue(strs) {\n  return strs.reduce(\n    (max, string) =>\n      Math.max(\n        max,\n        Number.isNaN(Number(string)) ? string.length : Number(string)\n      ),\n    0\n  );\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum_nesting_depth_of_the_parentheses/maximum_nesting_depth_of_the_parentheses.py",
    "content": "# https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses\n\ndef max_depth(s):\n    depth = open_paren = 0\n    \n    for char in s:\n        if char == '(':\n            open_paren += 1\n            depth = max(depth, open_paren)\n\n        if char == ')':\n            open_paren -= 1\n            \n    return depth\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum_number_of_balls_in_a_box/maximum_number_of_balls_in_a_box.py",
    "content": "# https://leetcode.com/problems/maximum-number-of-balls-in-a-box\n\ndef get_box(ball):\n    count = 0\n    \n    while ball > 0:\n        count += ball % 10\n        ball //= 10\n        \n    return count\n\ndef count_balls(low_limit, high_limit):\n    hash_counter = {}\n    \n    for ball in range(low_limit, high_limit + 1):\n        box = get_box(ball)\n        \n        if box in hash_counter:\n            hash_counter[box] += 1\n        else:\n            hash_counter[box] = 1\n            \n    max_balls = float('-Inf')\n    \n    for key, value in hash_counter.items():\n        max_balls = max(max_balls, value)\n        \n    return max_balls\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum_number_of_words_you_can_type/maximum_number_of_words_you_can_type.js",
    "content": "// https://leetcode.com/problems/maximum-number-of-words-you-can-type\n\nconst canBeTypedWords = function (text, brokenLetters) {\n  const words = text.split(' ');\n  const broken = buildBrokenMapper(brokenLetters);\n  const okWords = words.filter((word) => {\n    let foundBroken = false;\n    for (let char of word) {\n      if (broken[char]) {\n        foundBroken = true;\n      }\n    }\n\n    return !foundBroken;\n  });\n\n  return okWords.length;\n};\n\nconst buildBrokenMapper = (brokenLetters) => {\n  const mapper = {};\n\n  for (let letter of brokenLetters) {\n    mapper[letter] = true;\n  }\n\n  return mapper;\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum_population/maximum_population.py",
    "content": "# https://leetcode.com/problems/maximum-population-year\n\ndef maximum_population(logs):\n    population_by_year = {}\n    \n    for [birth, death] in logs:\n        for year in range(birth, death):\n            if year in population_by_year:\n                population_by_year[year] += 1\n            else:\n                population_by_year[year] = 1\n                \n    earliest_year = 0\n    max_population = 0\n    \n    for year, population in population_by_year.items():\n        if population == max_population:\n            earliest_year = min(earliest_year, year)\n        \n        if population > max_population:\n            earliest_year = year\n            max_population = population\n            \n    return earliest_year\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum_product/maximum_product.py",
    "content": "# https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array\n\n\ndef max_product(nums):\n    sorted_list = sorted(nums)\n    return (sorted_list[-1] - 1) * (sorted_list[-2] - 1)\n\n\ndef max_product(nums):\n    max, second_max = 0, 0\n\n    for num in nums:\n        if num >= max:\n            second_max = max\n            max = num\n        elif num >= second_max:\n            second_max = num\n\n    return (max - 1) * (second_max - 1)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/maximum_product_difference_between_two_pairs/maximum_product_difference_between_two_pairs.js",
    "content": "// https://leetcode.com/problems/maximum-product-difference-between-two-pairs\n\nconst maxProductDifference = function (nums) {\n  nums.sort((a, b) => a - b);\n  const greatest = nums[nums.length - 1];\n  const secondGreatest = nums[nums.length - 2];\n  const smallest = nums[0];\n  const secondSmallest = nums[1];\n\n  return greatest * secondGreatest - smallest * secondSmallest;\n};\n\nconst max = maxProductDifference([1, 6, 7, 5, 2, 4, 10, 6, 4]);\nconsole.log(max);\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/mean-of-array-after-removing-some-elements/mean-of-array-after-removing-some-elements.js",
    "content": "function removeFivePercent(numbers) {\n  let totalNumbers = numbers.length;\n  let fivePercent = numbers.length * 0.05;\n  return numbers.slice(fivePercent, totalNumbers - fivePercent);\n}\n\nfunction sum(numbers) {\n  return numbers.reduce((sumOfNums, num) => sumOfNums + num, 0);\n}\n\nfunction trimMean(numbers) {\n  numbers.sort((a, b) => a - b);\n  const withoutFivePercent = removeFivePercent(numbers);\n  const sumOfNums = sum(withoutFivePercent);\n  return sumOfNums / withoutFivePercent.length;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/merge-nodes-in-between-zeros/merge-nodes-in-between-zeros.js",
    "content": "export class ListNode {\n  constructor(val, next) {\n    this.val = val === undefined ? 0 : val;\n    this.next = next === undefined ? null : next;\n  }\n}\n\nexport function mergeNodes(head) {\n  let nonZeroHead;\n  let node;\n  let nextNode;\n  let currentNode = head.next;\n  let valueSum = 0;\n  let gotFirstNode = false;\n\n  while (currentNode) {\n    valueSum += currentNode.val;\n\n    if (currentNode.val === 0) {\n      nextNode = new ListNode(valueSum);\n      valueSum = 0;\n\n      if (gotFirstNode) {\n        node.next = nextNode;\n        node = node.next;\n      } else {\n        node = nextNode;\n        nonZeroHead = nextNode;\n        gotFirstNode = true;\n      }\n    }\n\n    currentNode = currentNode.next;\n  }\n\n  return nonZeroHead;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/merge-nodes-in-between-zeros/tests/merge-nodes-in-between-zeros.test.js",
    "content": "import { describe, it, expect } from 'vitest';\nimport { ListNode, mergeNodes } from '../merge-nodes-in-between-zeros';\n\nfunction buildList(nums, initValue = 0) {\n  let head = new ListNode(initValue);\n  let node = head;\n  let nextNode;\n\n  for (let i = 1; i < nums.length; i++) {\n    nextNode = new ListNode(nums[i]);\n    node.next = nextNode;\n    node = node.next;\n  }\n\n  return head;\n}\n\ndescribe('mergeNodes', () => {\n  it('removes zeros and merges nodes', () => {\n    const head = buildList([0, 3, 1, 0, 4, 5, 2, 0]);\n    const result = buildList([4, 11], 4);\n    expect(mergeNodes(head)).toEqual(result);\n  });\n\n  it('removes zeros and merges nodes', () => {\n    const head = buildList([0, 1, 0, 3, 0, 2, 2, 0]);\n    const result = buildList([1, 3, 4], 1);\n    expect(mergeNodes(head)).toEqual(result);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/merge-similar-items/merge-similar-items.js",
    "content": "function fillHashmapAndList(items, hashmap, list) {\n  for (let [value, weight] of items) {\n    if (hashmap.has(value)) {\n      hashmap.set(value, hashmap.get(value) + weight);\n    } else {\n      hashmap.set(value, weight);\n      list.push(value);\n    }\n  }\n}\n\nfunction mergeSimilarItems(items1, items2) {\n  let hashmap = new Map();\n  let list = [];\n\n  fillHashmapAndList(items1, hashmap, list);\n  fillHashmapAndList(items2, hashmap, list);\n\n  return list.sort((a, b) => a - b).map((value) => [value, hashmap.get(value)]);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/merge-sorted-array/merge-sorted-array.js",
    "content": "/*\nnums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3\n[1,2,2,3,5,6]\n\nnums1 = [0,0,0], m = 0, nums2 = [1,2,3], n = 3\n[1,2,3]\n\ntime: O(n + m)\nspace: O(n + m)\n*/\n\nfunction merge(nums1, m, nums2, n) {\n  let pointer1 = 0;\n  let pointer2 = 0;\n  let numbers = [];\n  let mIndex = m - 1;\n  let nIndex = n - 1;\n\n  while (pointer1 <= mIndex || pointer2 <= nIndex) {\n    if (pointer1 <= mIndex && pointer2 <= nIndex) {\n      let num1 = nums1[pointer1];\n      let num2 = nums2[pointer2];\n\n      if (num1 <= num2) {\n        numbers.push(num1);\n        pointer1++;\n      } else {\n        numbers.push(num2);\n        pointer2++;\n      }\n    }\n\n    if (pointer1 <= mIndex && pointer2 > nIndex) {\n      numbers.push(nums1[pointer1]);\n      pointer1++;\n    }\n\n    if (pointer2 <= nIndex && pointer1 > mIndex) {\n      numbers.push(nums2[pointer2]);\n      pointer2++;\n    }\n  }\n\n  for (let [index, num] of numbers.entries()) {\n    nums1[index] = num;\n  }\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/merge-two-2d-arrays-by-summing-values/merge-two-2d-arrays-by-summing-values.js",
    "content": "function mergeArrays(nums1, nums2) {\n  let nums = [];\n  let index1 = 0;\n  let index2 = 0;\n\n  while (index1 < nums1.length && index2 < nums2.length) {\n    let [id1, val1] = nums1[index1];\n    let [id2, val2] = nums2[index2];\n\n    if (id1 < id2) {\n      nums.push([id1, val1]);\n      index1++;\n    } else if (id2 < id1) {\n      nums.push([id2, val2]);\n      index2++;\n    } else {\n      nums.push([id1, val1 + val2]);\n      index1++;\n      index2++;\n    }\n  }\n\n  while (index1 < nums1.length) {\n    nums.push(nums1[index1]);\n    index1++;\n  }\n\n  while (index2 < nums2.length) {\n    nums.push(nums2[index2]);\n    index2++;\n  }\n\n  return nums;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/merge-two-binary-trees/merge-two-binary-trees.js",
    "content": "function mergeTrees(root1, root2) {\n  let root = new TreeNode();\n\n  if (root1 && root2) {\n    root.val = root1.val + root2.val;\n    root.left = mergeTrees(root1.left, root2.left);\n    root.right = mergeTrees(root1.right, root2.right);\n  } else if (root1) {\n    root = root1;\n  } else if (root2) {\n    root = root2;\n  } else {\n    return null;\n  }\n\n  return root;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/merge-two-sorted-lists/merge-two-sorted-lists.js",
    "content": "export class ListNode {\n  constructor(val, next) {\n    this.val = val === undefined ? 0 : val;\n    this.next = next === undefined ? null : next;\n  }\n}\n\nexport function mergeTwoLists(list1, list2) {\n  if (!list1 && !list2) {\n    return null;\n  }\n\n  if (!list1) {\n    return list2;\n  }\n\n  if (!list2) {\n    return list1;\n  }\n\n  let newList;\n\n  if (list1.val <= list2.val) {\n    newList = new ListNode(list1.val);\n    list1 = list1.next;\n  } else {\n    newList = new ListNode(list2.val);\n    list2 = list2.next;\n  }\n\n  let node = newList;\n\n  while (list1 && list2) {\n    if (list1.val <= list2.val) {\n      node.next = new ListNode(list1.val);\n      list1 = list1.next;\n    } else {\n      node.next = new ListNode(list2.val);\n      list2 = list2.next;\n    }\n\n    node = node.next;\n  }\n\n  while (list1) {\n    node.next = new ListNode(list1.val);\n    node = node.next;\n    list1 = list1.next;\n  }\n\n  while (list2) {\n    node.next = new ListNode(list2.val);\n    node = node.next;\n    list2 = list2.next;\n  }\n\n  return newList;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/merge-two-sorted-lists/tests/merge-two-sorted-lists.test.js",
    "content": "import { describe, it, expect } from 'vitest';\nimport { mergeTwoLists, ListNode } from '../merge-two-sorted-lists';\n\nfunction buildList(nums) {\n  if (nums.length === 0) {\n    return null;\n  }\n\n  let head = new ListNode(nums[0]);\n  let node = head;\n  let nextNode;\n\n  for (let i = 1; i < nums.length; i++) {\n    nextNode = new ListNode(nums[i]);\n    node.next = nextNode;\n    node = node.next;\n  }\n\n  return head;\n}\n\ndescribe('mergeTwoLists', () => {\n  it('', () => {\n    const list1 = buildList([1, 2, 4]);\n    const list2 = buildList([1, 3, 4]);\n    const result = buildList([1, 1, 2, 3, 4, 4]);\n\n    expect(mergeTwoLists(list1, list2)).toEqual(result);\n  });\n\n  it('', () => {\n    const list1 = buildList([]);\n    const list2 = buildList([]);\n    const result = buildList([]);\n\n    expect(mergeTwoLists(list1, list2)).toEqual(result);\n  });\n\n  it('', () => {\n    const list1 = buildList([]);\n    const list2 = buildList([0]);\n    const result = buildList([0]);\n\n    expect(mergeTwoLists(list1, list2)).toEqual(result);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/merge_strings_alternately/merge_strings_alternately.py",
    "content": "# https://leetcode.com/problems/merge-strings-alternately/\n\ndef mergeAlternately(word1, word2):\n    smallest_length = min(len(word1), len(word2))\n    letters = []\n\n    for index in range(smallest_length):\n        letters.append(word1[index])\n        letters.append(word2[index])\n\n    if len(word1) > len(word2):\n        biggest_word = word1\n    else:\n        biggest_word = word2\n        \n    return ''.join(letters) + biggest_word[smallest_length:]\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/merge_trees.py",
    "content": "'''\nhttps://leetcode.com/problems/merge-two-binary-trees/description/\n\nInput:\n\tTree 1                     Tree 2\n          1                         2\n         / \\                       / \\\n        3   2                     1   3\n       /                           \\   \\\n      5                             4   7\n\nOutput:\nMerged tree\n\t     3\n\t    / \\\n\t   4   5\n\t  / \\   \\\n\t 5   4   7\n'''\n\nclass TreeNode(object):\n    def __init__(self, val):\n        self.val = val\n        self.left = None\n        self.right = None\n\ndef merge_trees(t1, t2):\n    if not t1 and not t2: return None\n\n    new_node = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0))\n    new_node.left = merge_trees(t1 and t1.left, t2 and t2.left)\n    new_node.right = merge_trees(t1 and t1.right, t2 and t2.right)\n\n    return new_node\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/merge_two_lists.py",
    "content": "# https://leetcode.com/problems/merge-two-sorted-lists/description/\n\nclass ListNode(object):\n    def __init__(self, x):\n        self.val = x\n        self.next = None\n\ndef merge_two_lists(l1, l2):\n    if l1 == None and l2 == None:\n        return l1\n    elif l1 == None:\n        return l2\n    elif l2 == None:\n        return l1\n    else:\n        n = root = ListNode(0)\n\n        while l1 and l2:\n            if l1.val <= l2.val:\n                n.next = l1\n                l1 = l1.next\n            else:\n                n.next = l2\n                l2 = l2.next\n\n            n = n.next\n\n        if l1:\n            n.next = l1\n\n        if l2:\n            n.next = l2\n\n        return root.next\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/middle-of-the-linked-list/middle-of-the-linked-list-fast-slow.js",
    "content": "function middleNode(head) {\n  let slow = head;\n  let fast = head;\n\n  while (fast && fast.next) {\n    slow = slow.next;\n    fast = fast.next.next;\n  }\n\n  return slow;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/middle-of-the-linked-list/middle-of-the-linked-list.js",
    "content": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.next = (next===undefined ? null : next)\n * }\n */\n/**\nhead = [1,2,3,4,5] => n = 5 => 5 / 2 => 2.5 => 2\n[3,4,5]\n\nhead = [1] => n = 1 => 1 / 2 => 0.5 => 0\n[1]\n\nhead = [1,2,3,4,5,6] => n = 6 => 6 / 2 => 3\n[4,5,6]\n*/\n\nfunction getNodeCount(node, count) {\n  return node ? getNodeCount(node.next, count + 1) : count;\n}\n\nfunction getNode(node, index) {\n  return index ? getNode(node.next, index - 1) : node;\n}\n\nfunction middleNode(head) {\n  let count = getNodeCount(head, 0);\n  let middleIndex = Math.floor(count / 2);\n  return getNode(head, middleIndex);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/min-max-game/min-max-game.js",
    "content": "function minMaxGame(nums) {\n  while (nums.length > 1) {\n    let newNums = [];\n    let middleIndex = nums.length / 2;\n\n    for (let i = 0; i < middleIndex; i++) {\n      if (i % 2 === 0) newNums.push(Math.min(nums[2 * i], nums[2 * i + 1]));\n      else newNums.push(Math.max(nums[2 * i], nums[2 * i + 1]));\n    }\n\n    nums = newNums;\n  }\n\n  return nums;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimize-string-length/minimize-string-length.js",
    "content": "// https://leetcode.com/problems/minimize-string-length\n\nfunction minimizedStringLength(s) {\n  let set = new Set();\n\n  for (let char of s) {\n    set.add(char);\n  }\n\n  return set.size;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum-absolute-difference/minimum-absolute-difference.js",
    "content": "// https://leetcode.com/problems/minimum-absolute-difference\n\nconst minimumAbsDifference = (arr) => {\n  // runtime: O(NlogN)\n  // space: O(N)\n\n  let minDifference = Infinity;\n  const differenceToPairs = {};\n\n  arr.sort((a, b) => a - b);\n\n  for (let i = 0; i < arr.length - 1; i++) {\n    const num1 = arr[i];\n    const num2 = arr[i + 1];\n    const currentDifference = num2 - num1;\n\n    if (differenceToPairs[currentDifference]) {\n      differenceToPairs[currentDifference].push([num1, num2]);\n    } else {\n      differenceToPairs[currentDifference] = [[num1, num2]];\n    }\n\n    minDifference = Math.min(minDifference, currentDifference);\n  }\n\n  return differenceToPairs[minDifference];\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum-absolute-difference-in-bst/minimum-absolute-difference-in-bst.js",
    "content": "function getMinimumDifference(root, rootVal = Infinity) {\n  if (!root) return Infinity;\n  return Math.min(\n    Math.abs(root.val - rootVal),\n    getMinimumDifference(root.left, root.val),\n    getMinimumDifference(root.right, root.val)\n  );\n}\n\n// ===============================================================\n\nfunction traverse(node, list) {\n  if (!node) return null;\n  traverse(node.left, list);\n  list.push(node.val);\n  traverse(node.right, list);\n}\n\nfunction diff(list) {\n  let minDiff = Infinity;\n  let previous = list[0];\n\n  for (let index = 1; index < list.length; index++) {\n    minDiff = Math.min(list[index] - previous, minDiff);\n    previous = list[index];\n  }\n\n  return minDiff;\n}\n\nfunction getMinimumDifference(root) {\n  let list = [];\n  traverse(root, list);\n  return diff(list);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum-bit-flips-to-convert-number/minimum-bit-flips-to-convert-number.js",
    "content": "function toBinary(number) {\n  const binary = [];\n\n  while (number) {\n    binary.push((number % 2).toString());\n    number = Math.floor(number / 2);\n  }\n\n  return binary;\n}\n\nexport function minBitFlips(start, goal) {\n  const startBinary = toBinary(start);\n  const goalBinary = toBinary(goal);\n  const greatestLength =\n    startBinary.length > goalBinary.length\n      ? startBinary.length\n      : goalBinary.length;\n\n  let flips = 0;\n\n  for (let i = 0; i < greatestLength; i++) {\n    const startBit = startBinary[i] || '0';\n    const goalBit = goalBinary[i] || '0';\n\n    if (startBit !== goalBit) {\n      flips++;\n    }\n  }\n\n  return flips;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum-bit-flips-to-convert-number/tests/minimum-bit-flips-to-convert-number.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { minBitFlips } from '../minimum-bit-flips-to-convert-number';\n\ndescribe('minBitFlips', () => {\n  it('', () => {\n    expect(minBitFlips(10, 7)).toEqual(3);\n  });\n\n  it('', () => {\n    expect(minBitFlips(1, 16)).toEqual(2);\n  });\n\n  it('', () => {\n    expect(minBitFlips(3, 4)).toEqual(3);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum-cost-to-move-chips-to-the-same-position/minimum-cost-to-move-chips-to-the-same-position.js",
    "content": "function minCostToMoveChips(positions) {\n  let evenCount = 0;\n  let oddCount = 0;\n\n  for (let position of positions) {\n    if (position % 2 === 0) evenCount++;\n    else oddCount++;\n  }\n\n  return Math.min(evenCount, oddCount);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.js",
    "content": "// https://leetcode.com/problems/minimum-depth-of-binary-tree\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\nfunction minDepth(node, depth = 1) {\n  if (!node) return 0;\n  if (!node.left && !node.right) return depth;\n  if (!node.left) return minDepth(node.right, depth + 1);\n  if (!node.right) return minDepth(node.left, depth + 1);\n  return Math.min(\n    minDepth(node.left, depth + 1),\n    minDepth(node.right, depth + 1)\n  );\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum-distance-between-bst-nodes/minimum-distance-between-bst-nodes.js",
    "content": "function traverse(node, list) {\n  if (!node) return;\n  traverse(node.left, list);\n  list.push(node.val);\n  traverse(node.right, list);\n}\n\nfunction getMinDiff(list) {\n  let minDiff = Infinity;\n  let previous = list[0];\n\n  for (let index = 1; index < list.length; index++) {\n    if (list[index] - previous < minDiff) minDiff = list[index] - previous;\n    previous = list[index];\n  }\n\n  return minDiff;\n}\n\nfunction minDiffInBST(root) {\n  let list = [];\n  traverse(root, list);\n  return getMinDiff(list);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum-number-game/minimum-number-game.js",
    "content": "// https://leetcode.com/problems/minimum-number-game\n\nfunction numberGame(nums) {\n  let arr = [];\n\n  nums.sort((a, b) => a - b);\n\n  for (let index = 0; index < nums.length; index += 2) {\n    let alice = nums[index];\n    let bob = nums[index + 1];\n    arr.push(bob);\n    arr.push(alice);\n  }\n\n  return arr;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum-number-of-moves-to-seat-everyone/minimum-number-of-moves-to-seat-everyone.js",
    "content": "function sort(nums) {\n  return [...nums].sort((a, b) => a - b);\n}\n\nexport function minMovesToSeat(seats, students) {\n  const sortedSeats = sort(seats);\n  const sortedStudents = sort(students);\n  const N = seats.length;\n\n  let moves = 0;\n\n  for (let i = 0; i < N; i++) {\n    moves += Math.abs(sortedSeats[i] - sortedStudents[i]);\n  }\n\n  return moves;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum-number-of-moves-to-seat-everyone/tests/minimum-number-of-moves-to-seat-everyone.test.js",
    "content": "import { describe, it, expect } from 'vitest';\nimport { minMovesToSeat } from '../minimum-number-of-moves-to-seat-everyone';\n\ndescribe('minMovesToSeat', () => {\n  it('', () => {\n    expect(minMovesToSeat([3, 1, 5], [2, 7, 4])).toEqual(4);\n  });\n\n  it('', () => {\n    expect(minMovesToSeat([4, 1, 5, 9], [1, 3, 2, 6])).toEqual(7);\n  });\n\n  it('', () => {\n    expect(minMovesToSeat([2, 2, 6, 6], [1, 3, 2, 6])).toEqual(4);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum-number-of-operations-to-convert-time/minimum-number-of-operations-to-convert-time.js",
    "content": "function toMinutes(stringTime) {\n  const [hour, minutes] = stringTime.split(':');\n  return Number(hour) * 60 + Number(minutes);\n}\n\nfunction convertTime(current, correct) {\n  let count = 0;\n  let minutes = toMinutes(correct) - toMinutes(current);\n\n  while (minutes) {\n    if (minutes >= 60) minutes -= 60;\n    else if (minutes >= 15) minutes -= 15;\n    else if (minutes >= 5) minutes -= 5;\n    else minutes -= 1;\n    count++;\n  }\n\n  return count;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum-string-length-after-removing-substrings/minimum-string-length-after-removing-substrings.js",
    "content": "// https://leetcode.com/problems/minimum-string-length-after-removing-substrings\n\nfunction minLength(s) {\n  while (true) {\n    let found = false;\n    for (let index = 0; index < s.length - 1; index++) {\n      let slice = s.slice(index, index + 2);\n      if (['AB', 'CD'].includes(slice)) {\n        s = s.slice(0, index) + s.slice(index + 2);\n        found = true;\n        break;\n      }\n    }\n\n    if (!found) break;\n  }\n\n  return s.length;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum-subsequence-in-non-increasing-order/minimum-subsequence-in-non-increasing-order.js",
    "content": "function sum(nums) {\n  return nums.reduce((sumOfNums, num) => sumOfNums + num, 0);\n}\n\nfunction minSubsequence(nums) {\n  const result = [];\n  const sortedNums = [...nums].sort((a, b) => a - b);\n  let index = nums.length - 1;\n  let sumOfNums = sum(sortedNums);\n  let otherHalfSum = 0;\n\n  while (index >= 0 && otherHalfSum <= sumOfNums) {\n    const num = sortedNums[index];\n    result.push(num);\n    sumOfNums -= num;\n    otherHalfSum += num;\n    index--;\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum-sum/minimum-sum.js",
    "content": "/*\nYou are given a positive integer num consisting of exactly four digits.\nSplit num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2,\nand all the digits found in num must be used.\n\nFor example, given num = 2932, you have the following digits:\ntwo 2's, one 9 and one 3. Some of the possible pairs [new1, new2] are [22, 93], [23, 92], [223, 9] and [2, 329].\nReturn the minimum possible sum of new1 and new2.\n\n# Example 1:\nInput: num = 2932\nOutput: 52\nExplanation: Some possible pairs [new1, new2] are [29, 23], [223, 9], etc.\nThe minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52.\n\n# Example 2:\nInput: num = 4009\nOutput: 13\nExplanation: Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. \nThe minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13.\n*/\n\n// 2932 => 2, 9, 3, 2 => 2, 2 => 29, 23\n\nfunction getAllDigits(number) {\n  const stringNumber = number.toString();\n  const digits = [];\n\n  for (let i = 0; i < stringNumber.length; i++) {\n    digits.push(Number(stringNumber[i]));\n  }\n\n  return digits;\n}\n\nfunction sort(digits) {\n  return digits.sort((digit1, digit2) => digit1 - digit2);\n}\n\nfunction minimumSum(number) {\n  const digits = getAllDigits(number);\n  const sortedDigits = sort(digits);\n  const [digit1, digit2, digit3, digit4] = sortedDigits;\n\n  return digit1 * 10 + digit3 + (digit2 * 10 + digit4);\n}\n\nconsole.log(minimumSum(2932), 52);\nconsole.log(minimumSum(4009), 13);\n\nfunction altMinimunSum(number) {\n  const digits = number.toString().split('').sort();\n  return Number(digits[0] + digits[2]) + Number(digits[1] + digits[3]);\n}\n\nconsole.log(altMinimunSum(2932), 52);\nconsole.log(altMinimunSum(4009), 13);\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum-sum-of-mountain-triplets-i/minimum-sum-of-mountain-triplets-i.js",
    "content": "// https://leetcode.com/problems/minimum-sum-of-mountain-triplets-i\n\nfunction minimumSum(nums) {\n  let min = Infinity;\n\n  for (let i = 0; i < nums.length - 2; i++) {\n    for (let j = i + 1; j < nums.length - 1; j++) {\n      for (let k = j + 1; k < nums.length; k++) {\n        if (nums[i] < nums[j] && nums[k] < nums[j]) {\n          min = Math.min(min, nums[i] + nums[j] + nums[k]);\n        }\n      }\n    }\n  }\n\n  return min == Infinity ? -1 : min;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum-time-to-type-word-using-special-typewriter/minimum-time-to-type-word-using-special-typewriter.js",
    "content": "// https://leetcode.com/problems/minimum-time-to-type-word-using-special-typewriter\n\nconst minTimeToType = (word) => {\n  const wordLength = word.length;\n\n  let currentIndex = 0;\n  let moves = wordLength;\n\n  for (let i = 0; i < wordLength; i++) {\n    const letter = word[i];\n    const charCode = letter.charCodeAt() - 97;\n    const firstDistance = Math.abs(charCode - currentIndex);\n    const secondDistance =\n      charCode > currentIndex\n        ? currentIndex + 26 - charCode\n        : charCode + 26 - currentIndex;\n\n    const minimumDistance = Math.min(firstDistance, secondDistance);\n\n    moves += minimumDistance;\n    currentIndex = charCode;\n  }\n\n  return moves;\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum-value-to-get-positive-step-by-step-sum/minimum-value-to-get-positive-step-by-step-sum.js",
    "content": "function getMinValue(nums) {\n  let min = Infinity;\n  let sum = 0;\n\n  for (let num of nums) {\n    sum += num;\n    min = Math.min(min, sum);\n  }\n\n  return min;\n}\n\nfunction minStartValue(nums) {\n  const minValue = getMinValue(nums);\n  const result = 1 - minValue;\n  return result >= 1 ? result : 1;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/minimum_operations_to_make_the_array_increasing/minimum_operations_to_make_the_array_increasing.py",
    "content": "# https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing\n\ndef min_operations(nums):\n    previous_num = nums[0]\n    operations = 0\n\n    for index, num in enumerate(nums[1:]):\n        if num <= previous_num:\n            new_num = previous_num - num + 1\n            operations += new_num\n            nums[index + 1] += new_num\n\n        previous_num = nums[index + 1]\n        \n    return operations\n\ndef min_operations(nums):\n    prev, ops = 0, 0\n\n    for num in nums:\n        if num <= prev:\n            prev += 1\n            ops += prev - num\n        else:\n            prev = num\n    \n    return ops\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/missing-number/missing-number.js",
    "content": "function buildHashmap(nums) {\n  const hashmap = new Map();\n\n  for (let num of nums) {\n    hashmap.set(num, true);\n  }\n\n  return hashmap;\n}\n\nfunction getMissingNumber(numsLength, hashmap) {\n  for (let i = 0; i <= numsLength; i++) {\n    if (!hashmap.has(i)) return i;\n  }\n}\n\nfunction missingNumber(nums) {\n  const hashmap = buildHashmap(nums);\n  return getMissingNumber(nums.length, hashmap);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/monotonic-array/monotonic-array.js",
    "content": "function isMonotonic(nums) {\n  if (nums.length === 1) return true;\n  let isIncreasing;\n  let previous = nums[0];\n\n  for (let index = 1; index < nums.length; index++) {\n    if (nums[index] === previous) {\n      previous = nums[index];\n      continue;\n    }\n\n    if (isIncreasing === undefined) {\n      isIncreasing = previous <= nums[index];\n    }\n\n    if (isIncreasing && nums[index] < previous) return false;\n    if (!isIncreasing && nums[index] > previous) return false;\n    previous = nums[index];\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/most-words-found/most-words-found.js",
    "content": "/*\nA sentence is a list of words that are separated by a single space with no leading or trailing spaces.\nYou are given an array of strings sentences, where each sentences[i] represents a single sentence.\nReturn the maximum number of words that appear in a single sentence.\n\n# Example 1:\nInput: sentences = [\"alice and bob love leetcode\", \"i think so too\", \"this is great thanks very much\"]\nOutput: 6\nExplanation: \n- The first sentence, \"alice and bob love leetcode\", has 5 words in total.\n- The second sentence, \"i think so too\", has 4 words in total.\n- The third sentence, \"this is great thanks very much\", has 6 words in total.\nThus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words.\n\n# Example 2:\nInput: sentences = [\"please wait\", \"continue to fight\", \"continue to win\"]\nOutput: 3\nExplanation: It is possible that multiple sentences contain the same number of words. \nIn this example, the second and third sentences (underlined) have the same number of words.\n*/\n\nfunction mostWordsFound(sentences = []) {\n  return Math.max(...sentences.map((sentence) => sentence.split(' ').length));\n}\n\nconsole.log(\n  mostWordsFound([\n    'alice and bob love leetcode',\n    'i think so too',\n    'this is great thanks very much',\n  ]),\n  6\n);\n\nconsole.log(\n  mostWordsFound(['please wait', 'continue to fight', 'continue to win']),\n  3\n);\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/move-zeroes/move-zeroes-in-place.js",
    "content": "function moveZeroes(nums) {\n  let zeroesCount = 0;\n  let inPlaceIndex = 0;\n\n  for (let num of nums) {\n    if (num) {\n      nums[inPlaceIndex] = num;\n      inPlaceIndex++;\n    } else {\n      zeroesCount++;\n    }\n  }\n\n  while (zeroesCount) {\n    nums[nums.length - zeroesCount] = 0;\n    zeroesCount--;\n  }\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/move-zeroes/move-zeroes.js",
    "content": "function moveZeroes(nums) {\n  let numsWithZerosAtTheEnd = [];\n  let zeroCount = 0;\n\n  for (let num of nums) {\n    if (num) {\n      numsWithZerosAtTheEnd.push(num);\n    } else {\n      zeroCount++;\n    }\n  }\n\n  while (zeroCount) {\n    numsWithZerosAtTheEnd.push(0);\n    zeroCount--;\n  }\n\n  return numsWithZerosAtTheEnd;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/n_ary_tree_postorder_traversal/n_ary_tree_postorder_traversal.py",
    "content": "# https://leetcode.com/problems/n-ary-tree-postorder-traversal\n\nresult = []\n\ndef postorder(root):\n    if root is None: return []\n    \n    for node in root.children:\n        postorder(node)\n        \n    result.append(root.val)\n    return result\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/n_ary_tree_preorder_traversal/n_ary_tree_preorder_traversal.py",
    "content": "# https://leetcode.com/problems/n-ary-tree-postorder-traversal\n\nresult = []\n\ndef preorder(root):\n    if root is None: return []\n    \n    result.append(root.val)\n\n    for node in root.children:\n        preorder(node)\n        \n    return result\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/n_repeated_element_in_size_2n_array/n_repeated_element_in_size_2n_array.py",
    "content": "# https://leetcode.com/problems/n-repeated-element-in-size-2n-array/\n\n'''\nIn a array A of size 2N, there are N+1 unique elements,\nand exactly one of these elements is repeated N times.\n\nReturn the element repeated N times.\n\nExample 1:\nInput: [1,2,3,3]\nOutput: 3\n\nExample 2:\nInput: [2,1,2,5,3,2]\nOutput: 2\n\nExample 3:\nInput: [5,1,5,2,5,3,5,4]\nOutput: 5\n'''\n\n\ndef n_repeated_element_in_size_2n_array(A):\n    map_counter = {}\n\n    for number in A:\n        if number in map_counter:\n            map_counter[number] += 1\n            return number\n        else:\n            map_counter[number] = 1\n\n\ndata_tests = [\n    ([1, 2, 3, 3], 3),\n    ([2, 1, 2, 5, 3, 2], 2),\n    ([5, 1, 5, 2, 5, 3, 5, 4], 5)\n]\n\nfor numbers, expected in data_tests:\n    result = n_repeated_element_in_size_2n_array(numbers)\n    print(result, expected == result)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/neither-minimum-nor-maximum/neither-minimum-nor-maximum-on.js",
    "content": "// https://leetcode.com/problems/neither-minimum-nor-maximum\n\nfunction findNonMinOrMax(nums) {\n  let min = Infinity,\n    max = -Infinity;\n\n  for (num of nums) {\n    min = Math.min(min, num);\n    max = Math.max(max, num);\n  }\n\n  for (let num of nums) {\n    if (num !== min && num !== max) {\n      return num;\n    }\n  }\n\n  return -1;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/neither-minimum-nor-maximum/neither-minimum-nor-maximum.js",
    "content": "// https://leetcode.com/problems/neither-minimum-nor-maximum\n\nfunction findNonMinOrMax(nums) {\n  return nums.length > 2 ? nums.sort((a, b) => a - b)[1] : -1;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/next-greater-element-i/next-greater-element-i-optimized.js",
    "content": "function peek(stack) {\n  return stack[stack.length - 1];\n}\n\nfunction isEmpty(stack) {\n  return stack.length === 0;\n}\n\nexport function nextGreaterElement(nums1, nums2) {\n  const stack = [];\n  const hashmap = new Map();\n\n  for (let num of nums2) {\n    while (!isEmpty(stack) && num > peek(stack)) {\n      hashmap.set(stack.pop(), num);\n    }\n\n    stack.push(num);\n  }\n\n  while (!isEmpty(stack)) {\n    hashmap.set(stack.pop(), -1);\n  }\n\n  const result = [];\n\n  for (let num of nums1) {\n    if (hashmap.has(num)) {\n      result.push(hashmap.get(num));\n    } else {\n      result.push(-1);\n    }\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/next-greater-element-i/next-greater-element-i.js",
    "content": "export function nextGreaterElement(nums1, nums2) {\n  const result = [];\n\n  for (let num1 of nums1) {\n    let foundNumber = false;\n    let foundNextGreaterElement = false;\n\n    for (let num2 of nums2) {\n      if (num1 === num2) {\n        foundNumber = true;\n      }\n\n      if (foundNumber && num2 > num1) {\n        result.push(num2);\n        foundNextGreaterElement = true;\n        break;\n      }\n    }\n\n    if (!foundNextGreaterElement) {\n      result.push(-1);\n    }\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/next-greater-element-i/tests/next-greater-element-i-optimized.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { nextGreaterElement } from '../next-greater-element-i-optimized';\n\ndescribe('nextGreaterElement', () => {\n  it('', () => {\n    expect(nextGreaterElement([4, 1, 2], [1, 3, 4, 2])).toEqual([-1, 3, -1]);\n  });\n\n  it('', () => {\n    expect(nextGreaterElement([2, 4], [1, 2, 3, 4])).toEqual([3, -1]);\n  });\n\n  it('', () => {\n    expect(nextGreaterElement([4, 1, 2], [1, 3, 4, 2, 5])).toEqual([5, 3, 5]);\n  });\n\n  it('', () => {\n    expect(nextGreaterElement([4, 1, 2], [3, 4, 5, 2, 1])).toEqual([5, -1, -1]);\n  });\n\n  it('', () => {\n    expect(nextGreaterElement([4, 1, 2], [3, 4, 5, 2, 1, 6])).toEqual([\n      5, 6, 6,\n    ]);\n  });\n\n  it('', () => {\n    expect(\n      nextGreaterElement([9, 8, 7, 3, 2, 1, 6], [9, 8, 7, 3, 2, 1, 6])\n    ).toEqual([-1, -1, -1, 6, 6, 6, -1]);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/next-greater-element-i/tests/next-greater-element-i.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { nextGreaterElement } from '../next-greater-element-i';\n\ndescribe('nextGreaterElement', () => {\n  it('', () => {\n    expect(nextGreaterElement([4, 1, 2], [1, 3, 4, 2])).toEqual([-1, 3, -1]);\n  });\n\n  it('', () => {\n    expect(nextGreaterElement([2, 4], [1, 2, 3, 4])).toEqual([3, -1]);\n  });\n\n  it('', () => {\n    expect(nextGreaterElement([4, 1, 2], [1, 3, 4, 2, 5])).toEqual([5, 3, 5]);\n  });\n\n  it('', () => {\n    expect(nextGreaterElement([4, 1, 2], [3, 4, 5, 2, 1])).toEqual([5, -1, -1]);\n  });\n\n  it('', () => {\n    expect(nextGreaterElement([4, 1, 2], [3, 4, 5, 2, 1, 6])).toEqual([\n      5, 6, 6,\n    ]);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/num_unique_emails/num_unique_emails.py",
    "content": "def num_unique_emails(emails):\n    unique_emails = set()\n    \n    for email in emails:\n        [local, domain] = email.split('@')\n        splitted_local = local.split('+')\n        new_local = ''.join(splitted_local[0].split('.'))\n        unique_emails.add(new_local + '@' + domain)\n        \n    return len(unique_emails)"
  },
  {
    "path": "coding_interviews/leetcode/easy/number-of-1-bits/number-of-1-bits.js",
    "content": "function hammingWeight(n) {\n  let sum = 0;\n\n  while (n != 0) {\n    sum += n & 1;\n    n = n >>> 1;\n  }\n\n  return sum;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/number-of-arithmetic-triplets/number-of-arithmetic-triplets.js",
    "content": "function buildMap(nums) {\n  const hashmap = new Map();\n\n  for (let num of nums) {\n    hashmap.set(num, num);\n  }\n\n  return hashmap;\n}\n\nfunction arithmeticTriplets(nums, diff) {\n  let hashmap = buildMap(nums);\n  let counter = 0;\n\n  for (let index = 0; index < nums.length - 2; index++) {\n    const number = nums[index] + diff;\n    const anotherNumber = number + diff;\n\n    if (hashmap.has(number) && hashmap.has(anotherNumber)) {\n      counter++;\n    }\n  }\n\n  return counter;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/number-of-common-factors/number-of-common-factors.js",
    "content": "function commonFactors(a, b) {\n  let minValue = Math.min(a, b);\n  let counter = 0;\n\n  for (let num = 1; num <= minValue; num++) {\n    if (a % num === 0 && b % num === 0) counter++;\n  }\n\n  return counter;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/number-of-employees-who-met-the-target/number-of-employees-who-met-the-target.js",
    "content": "function numberOfEmployeesWhoMetTarget(hours, target) {\n  let count = 0;\n\n  for (let hour of hours) {\n    if (hour >= target) count++;\n  }\n\n  return count;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/number-of-even-and-odd-bits/number-of-even-and-odd-bits.js",
    "content": "function toBinary(n) {\n  const binary = [];\n\n  while (n > 0) {\n    binary.push(n % 2);\n    n = Math.floor(n / 2);\n  }\n\n  return binary;\n}\n\nfunction isEven(n) {\n  return n % 2 === 0;\n}\n\nfunction isOdd(n) {\n  return n % 2 !== 0;\n}\n\nfunction evenOddBit(n) {\n  let binary = toBinary(n);\n  let even = 0;\n  let odd = 0;\n\n  for (let index = 0; index < binary.length; index++) {\n    if (isEven(index) && binary[index]) even++;\n    if (isOdd(index) && binary[index]) odd++;\n  }\n\n  return [even, odd];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/number-of-lines-to-write-string/number-of-lines-to-write-string.js",
    "content": "// https://leetcode.com/problems/number-of-lines-to-write-string\n\nfunction toWidthsIndex(char) {\n  return char.charCodeAt() - 97;\n}\n\nfunction numberOfLines(widths, s) {\n  let output = [1, 0];\n\n  for (let char of s) {\n    let width = widths[toWidthsIndex(char)];\n\n    if (output[1] + width <= 100) {\n      output[1] = output[1] + width;\n    } else {\n      output[0]++;\n      output[1] = width;\n    }\n  }\n\n  return output;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/number-of-senior-citizens/number-of-senior-citizens.js",
    "content": "function countSeniors(details) {\n  let count = 0;\n\n  for (let detail of details) {\n    if (Number(detail.slice(11, 13)) > 60) {\n      count++;\n    }\n  }\n\n  return count;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/number-of-senior-citizens/one-liner-number-of-senior-citizens.js",
    "content": "function countSeniors(details) {\n  return details\n    .filter((detail) => Number(detail.slice(11, 13)) > 60)\n    .length;\n};"
  },
  {
    "path": "coding_interviews/leetcode/easy/number-of-strings-that-appear-as-substrings-in-word/number-of-strings-that-appear-as-substrings-in-word.js",
    "content": "const isPatternInWord = (pattern, word) => {\n  const patternLength = pattern.length;\n  let hasPattern = false;\n\n  for (let i = 0; i + patternLength <= word.length; i++) {\n    console.log(word.substring(i, i + patternLength));\n    if (word.substring(i, i + patternLength) === pattern) {\n      hasPattern = true;\n    }\n  }\n\n  return hasPattern;\n};\n\nconst numOfStrings = (patterns, word) => {\n  let count = 0;\n\n  patterns.forEach((pattern) => {\n    if (isPatternInWord(pattern, word)) {\n      count++;\n    }\n  });\n\n  return count;\n};\n\nconst result = numOfStrings(['a', 'abc', 'bc', 'd'], 'abc');\nconsole.log('result', result);\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/number-of-unequal-triplets-in-array/number-of-unequal-triplets-in-array.js",
    "content": "function unequalTriplets(nums) {\n  let counter = 0;\n\n  for (let i = 0; i < nums.length - 2; i++) {\n    for (let j = i + 1; j < nums.length - 1; j++) {\n      for (let k = j + 1; k < nums.length; k++) {\n        let iNum = nums[i];\n        let jNum = nums[j];\n        let kNum = nums[k];\n\n        if (iNum !== jNum && iNum !== kNum && jNum !== kNum) counter++;\n      }\n    }\n  }\n\n  return counter;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/number_complement.py",
    "content": "'''\nhttps://leetcode.com/problems/number-complement/description/\n\nInput: 5\nOutput: 2\n\nInput: 1\nOutput: 0\n'''\n\ndef to_binary(num):\n    binary_num = ''\n    copy_num = num\n\n    while copy_num > 0:\n        binary_num += str(copy_num % 2)\n        copy_num /= 2\n\n    return binary_num\n\ndef to_binary_complement(binary_num):\n    return ''.join(['1' if binary == '0' else '0' for binary in binary_num])\n\ndef to_complement(complement_binary_num):\n    return sum([pow(2, index) for index, binary in enumerate(complement_binary_num) if binary == '1'])\n\ndef find_complement(num):\n    binary_num = to_binary(num)\n    complement_binary_num = to_binary_complement(binary_num)\n    return to_complement(complement_binary_num)\n\nprint(find_complement(5) == 2)\nprint(find_complement(1) == 0)\nprint(find_complement(8) == 7)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/number_of_good_pairs/number_of_good_pairs.py",
    "content": "def factorial(n):\n    if n <= 1: return 1\n    return factorial(n - 1) * n\n\ndef permutation(n, r):\n    return factorial(n) // (factorial(n - r) * factorial(r))\n\ndef number_of_good_pairs(nums):\n    nums_counter = {}\n    \n    for num in nums:\n        if num in nums_counter:\n            nums_counter[num] += 1\n        else:\n            nums_counter[num] = 1\n    \n    counter = 0\n    \n    for num, num_counter in nums_counter.items():\n        if num_counter > 1:\n            counter += permutation(num_counter, 2)\n            \n    return counter\n\n# ------------------------------------------------------------\n\nfrom math import factorial\n\ndef permutation(n, r):\n    return factorial(n) // (factorial(n - r) * factorial(r))\n\ndef number_of_good_pairs(nums):\n    nums_counter = {}\n    \n    for num in nums:\n        if num in nums_counter:\n            nums_counter[num] += 1\n        else:\n            nums_counter[num] = 1\n    \n    counter = 0\n    \n    for num, num_counter in nums_counter.items():\n        if num_counter > 1:\n            counter += permutation(num_counter, 2)\n            \n    return counter\n\n# ------------------------------------------------------------\n\ndef number_of_good_pairs(nums):\n    nums_counter = {}\n    counter = 0\n    \n    for num in nums:\n        if num in nums_counter:\n            counter += nums_counter[num]\n            nums_counter[num] += 1\n        else:\n            nums_counter[num] = 1\n            \n    return counter\n\n# ------------------------------------------------------------\n\nfrom collections import Counter\n\ndef number_of_good_pairs(nums):\n    nums_counter = Counter()\n    counter = 0\n    \n    for num in nums:\n        counter += nums_counter[num]\n        nums_counter[num] += 1\n            \n    return counter\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/number_of_recent_calls/number_of_recent_calls.py",
    "content": "# https://leetcode.com/problems/number-of-recent-calls\n\nclass RecentCounter:\n    def __init__(self):\n        self.requests = []\n\n    def ping(self, t: int) -> int:\n        self.requests.append(t)\n        initial_time = t - 3000\n        \n        counter = 0\n        \n        for request in self.requests:\n            if request >= initial_time and request <= t:\n                counter += 1\n        \n        return counter\n\nclass RecentCounter:\n    def __init__(self):\n        self.requests = deque()\n\n    def ping(self, t: int) -> int:\n        self.requests.append(t)\n        \n        while self.requests[0] < t - 3000:\n            self.requests.popleft()\n            \n        return len(self.requests)"
  },
  {
    "path": "coding_interviews/leetcode/easy/number_of_students/number_of_students.py",
    "content": "def busy_student(start_time, end_time, query_time):\n    number_of_students = 0\n\n    for index in range(len(start_time)):\n        start, end = start_time[index], end_time[index]\n\n        if query_time >= start and query_time <= end:\n            number_of_students += 1\n\n    return number_of_students\n\n\ndef busy_student(start_time, end_time, query_time):\n    number_of_students = 0\n\n    for start, end in zip(start_time, end_time):\n        if query_time >= start and query_time <= end:\n            number_of_students += 1\n\n    return number_of_students\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/odd-string-difference/odd-string-difference.js",
    "content": "function toCode(char) {\n  return char.charCodeAt() - 97;\n}\n\nfunction buildDiffIntegerArray(word) {\n  let diffIntegerArray = [];\n  let previous = word[0];\n\n  for (let index = 1; index < word.length; index++) {\n    let current = word[index];\n    diffIntegerArray.push(toCode(current) - toCode(previous));\n    previous = current;\n  }\n\n  return diffIntegerArray;\n}\n\nfunction joinIntegersString(diff) {\n  return diff.map((diffNum) => diffNum.toString()).join('*');\n}\n\nfunction oddString(words) {\n  let hashmap = new Map();\n\n  for (let word of words) {\n    let key = joinIntegersString(buildDiffIntegerArray(word));\n\n    if (hashmap.has(key)) {\n      hashmap.set(key, [hashmap.get(key)[0] + 1, word]);\n    } else {\n      hashmap.set(key, [1, word]);\n    }\n  }\n\n  for (let [_, [count, word]] of hashmap.entries()) {\n    if (count === 1) {\n      return word;\n    }\n  }\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/odd_in_matrix/odd_in_matrix.py",
    "content": "def init_matrix(rows, columns):\n    return [[0 for _ in range(columns)] for _ in range(rows)]\n\n\ndef odd_cells(n, m, indices):\n    matrix = init_matrix(n, m)\n\n    for [ri, ci] in indices:\n        for column in range(m):\n            matrix[ri][column] += 1\n\n        for row in range(n):\n            matrix[row][ci] += 1\n\n    odds = 0\n\n    for row in range(n):\n        for column in range(m):\n            if matrix[row][column] % 2 != 0:\n                odds += 1\n\n    return odds\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/partition_labels.py",
    "content": "'''\nhttps://leetcode.com/problems/partition-labels/description/\n\nInput: S = \"ababcbacadefegdehijhklij\"\nOutput: [9, 7, 8]\n\nInput: S = \"abc\"\nOutput: [1, 1, 1]\n\nInput: S = \"abbaa\"\nOutput: [5]\n'''\n\ndef partition_labels(S):\n    partitions = []\n    start_index = 0\n    last_index = S.rfind(S[0])\n\n    for i, c in enumerate(S, 1):\n        if i == len(S):\n            partitions.append(S[start_index:])\n        elif last_index == i - 1:\n            partitions.append(S[start_index:i])\n            start_index = i\n            last_index = S.rfind(S[i])\n        elif S.rfind(S[i]) > last_index:\n            last_index = S.rfind(S[i])\n\n    return [len(partition) for partition in partitions]\n\nprint(partition_labels(\"ababcbacadefegdehijhklij\") == [9, 7, 8])\nprint(partition_labels(\"abc\") == [1, 1, 1])\nprint(partition_labels(\"abbaa\") == [5])\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/pascals-triangle/pascals-triangle.js",
    "content": "function generate(numRows) {\n  let triangle = [[1]];\n\n  for (let row = 1; row < numRows; row++) {\n    let triangleRow = [];\n\n    for (let index = 0; index <= row; index++) {\n      const num1 = index - 1 >= 0 ? triangle[row - 1][index - 1] : 0;\n      const num2 =\n        index < triangle[row - 1].length ? triangle[row - 1][index] : 0;\n      triangleRow.push(num1 + num2);\n    }\n\n    triangle.push(triangleRow);\n  }\n\n  return triangle;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/path-sum/path-sum.js",
    "content": "function hasPathSum(root, targetSum, sum = 0) {\n  if (!root) {\n    return false;\n  }\n\n  if (!root.left && !root.right) {\n    return sum + root.val === targetSum;\n  }\n\n  return (\n    hasPathSum(root.left, targetSum, sum + root.val) ||\n    hasPathSum(root.right, targetSum, sum + root.val)\n  );\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/peak_index_mountain.py",
    "content": "'''\nhttps://leetcode.com/problems/peak-index-in-a-mountain-array/description/\n\nInput: [0, 1, 0]\nOutput: 1\n\nInput: [0, 2, 1, 0]\nOutput: 1\n'''\n\ndef peak_index_in_mountain_array(A):\n    peak = A[0]\n    peak_index = 0\n\n    for index, mountain_height in enumerate(A):\n        if mountain_height > peak:\n          peak_index = index\n          peak = mountain_height\n\n    return peak_index\n\nprint(peak_index_in_mountain_array([0, 1, 0]) == 1)\nprint(peak_index_in_mountain_array([0, 2, 1, 0]) == 1)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/percentage-of-letter-in-string/percentage-of-letter-in-string.js",
    "content": "function percentageLetter(s, letter) {\n  let counter = new Map();\n\n  for (let char of s) {\n    if (counter.has(char)) {\n      counter.set(char, counter.get(char) + 1);\n    } else {\n      counter.set(char, 1);\n    }\n  }\n\n  let letterCount = counter.has(letter) ? counter.get(letter) : 0;\n\n  return Math.floor((letterCount / s.length) * 100);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/plus_one/plus_one.js",
    "content": "// https://leetcode.com/problems/plus-one/\n\nfunction add_one(digits) {\n  return plus_one(digits, 1);\n}\n\nfunction plus_one(digits, inc) {\n  if (digits.length == 0 && inc > 0) {\n    return [1];\n  }\n\n  if (digits.length == 0 && inc == 0) {\n    return [];\n  }\n\n  let new_inc;\n  let last_digit;\n\n  last_digit = digits[digits.length - 1];\n  last_digit = last_digit + inc;\n\n  if (last_digit == 10) {\n    new_inc = 1;\n  } else {\n    new_inc = 0;\n  }\n\n  return plus_one(\n    digits.slice(0, digits.length - 1),\n    new_inc\n  ).concat([last_digit % 10]);\n}\n\nconsole.log(add_one([1, 2, 3])) // [1, 2, 4]\nconsole.log(add_one([4, 3, 2, 1])) // [4, 3, 2, 2]\nconsole.log(add_one([1, 2, 9])) // [1, 3, 0]\nconsole.log(add_one([1, 9, 9])) // [2, 0, 0]\nconsole.log(add_one([9, 9, 9])) // [1, 0, 0, 0]\nconsole.log(add_one([1, 0, 0, 0, 0])) // [1, 0, 0, 0, 1]\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/plus_one/plus_one.py",
    "content": "# https://leetcode.com/problems/plus-one/\n\n\ndef add_one(digits):\n    return plus_one(digits, 1)\n\n\ndef plus_one(digits, inc):\n    if digits == [] and inc > 0:\n        return [1]\n\n    if digits == [] and inc == 0:\n        return []\n\n    last_digit = digits[-1]\n    last_digit = last_digit + inc\n\n    if last_digit == 10:\n        new_inc = 1\n    else:\n        new_inc = 0\n\n    return plus_one(digits[0:-1], new_inc) + [last_digit % 10]\n\n\nprint(add_one([1, 2, 3]))  # [1, 2, 4]\nprint(add_one([4, 3, 2, 1]))  # [4, 3, 2, 2]\nprint(add_one([1, 2, 9]))  # [1, 3, 0]\nprint(add_one([1, 9, 9]))  # [2, 0, 0]\nprint(add_one([9, 9, 9]))  # [1, 0, 0, 0]\nprint(add_one([1, 0, 0, 0, 0]))  # [1, 0, 0, 0, 1]\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/points-that-intersect-with-cars/points-that-intersect-with-cars.js",
    "content": "// https://leetcode.com/problems/points-that-intersect-with-cars\n\nfunction numberOfPoints(nums) {\n  let map = new Map();\n  let points = 0;\n\n  for ([start, end] of nums) {\n    for (let num = start; num <= end; num++) {\n      if (!map.has(num)) {\n        points++;\n        map.set(num, true);\n      }\n    }\n  }\n\n  return points;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/power-of-two/power-of-two.js",
    "content": "function isPowerOfTwo(n) {\n  if (n <= 0) {\n    return false;\n  }\n\n  while (n > 1) {\n    if (n % 2 !== 0) {\n      return false;\n    }\n\n    n /= 2;\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/prime-number-of-set-bits-in-binary-representation/prime-number-of-set-bits-in-binary-representation.js",
    "content": "// https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation\n\nfunction toBinary(n) {\n  let binary = [];\n\n  while (n) {\n    binary.push((n % 2).toString());\n    n = Math.floor(n / 2);\n  }\n\n  return binary.join('');\n}\n\nfunction getNumberOfSetBits(binary) {\n  let count = 0;\n\n  for (let digit of binary) {\n    if (digit === '1') count++;\n  }\n\n  return count;\n}\n\nfunction isPrime(num) {\n  for (let i = 2, s = Math.sqrt(num); i <= s; i++) {\n    if (num % i === 0) return false;\n  }\n  return num > 1;\n}\n\nfunction countPrimeSetBits(left, right) {\n  let count = 0;\n\n  for (let num = left; num <= right; num++) {\n    let binary = toBinary(num);\n    let setBits = getNumberOfSetBits(binary);\n\n    if (isPrime(setBits)) {\n      count++;\n    }\n  }\n\n  return count;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/projection-area-of-3d-shapes/projection-area-of-3d-shapes.js",
    "content": "// https://leetcode.com/problems/projection-area-of-3d-shapes\n\nfunction projectionArea(grid) {\n  let xy = 0;\n  let xz = 0;\n  let yz = 0;\n\n  for (let x = 0; x < grid.length; x++) {\n    for (let y = 0; y < grid[x].length; y++) {\n      if (grid[x][y] > 0) xy++;\n    }\n  }\n\n  for (let x = 0; x < grid.length; x++) {\n    let max = -Infinity;\n\n    for (let z = 0; z < grid[x].length; z++) {\n      max = Math.max(max, grid[x][z]);\n    }\n\n    xz += max;\n  }\n\n  let allAreas = [];\n\n  for (let y = 0; y < grid.length; y++) {\n    for (let z = 0; z < grid[y].length; z++) {\n      allAreas[z] = Math.max(allAreas[z] || 0, grid[y][z]);\n    }\n  }\n\n  yz = allAreas.reduce((sum, area) => sum + area, 0);\n\n  return xy + xz + yz;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/range_sum_of_bst/range_sum_of_bst.py",
    "content": "# https://leetcode.com/problems/range-sum-of-bst/submissions/\n\n'''\nGiven the root node of a binary search tree,\nreturn the sum of values of all nodes with value between L and R (inclusive).\n\nThe binary search tree is guaranteed to have unique values.\n\nExample 1:\nInput: root = [10,5,15,3,7,null,18], L = 7, R = 15\nOutput: 32\n\nExample 2:\nInput: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10\nOutput: 23\n'''\n\n\ndef rangeSumBST(root, L, R):\n    left_sum = 0\n    right_sum = 0\n    root_sum = 0\n\n    if root.left is not None and root.val > L:\n        left_sum = rangeSumBST(root.left, L, R)\n\n    if root.right is not None and root.val < R:\n        right_sum = rangeSumBST(root.right, L, R)\n\n    if root.val >= L and root.val <= R:\n        root_sum = root.val\n\n    return root_sum + left_sum + right_sum\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/rank-transform-of-an-array/rank-transform-of-an-array-less-memory.js",
    "content": "// https://leetcode.com/problems/rank-transform-of-an-array\n\n/**\n * [40,10,20,30]\n * [10,20,30,40] => O(NlogN)\n * {10: 1, 20: 2, 30: 3, 40: 4} => O(N), N = array size\n * [4,1,2,3] => O(N)\n * runtime: O(NlogN)\n * space: O(N)\n */\nfunction buildMap(set) {\n  let map = new Map();\n  let index = 1;\n\n  for (let num of set.values()) {\n    map.set(num, index);\n    index++;\n  }\n\n  return map;\n}\n\nfunction buildRank(arr, map) {\n  for (let index = 0; index < arr.length; index++) {\n    arr[index] = map.get(arr[index]);\n  }\n\n  return arr;\n}\n\nfunction arrayRankTransform(arr) {\n  const sortedSet = new Set([...arr].sort((a, b) => a - b));\n  const map = buildMap(sortedSet);\n  return buildRank(arr, map);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/rank-transform-of-an-array/rank-transform-of-an-array.js",
    "content": "// https://leetcode.com/problems/rank-transform-of-an-array\n\n/**\n * [40,10,20,30]\n * [10,20,30,40] => O(NlogN)\n * {10: 1, 20: 2, 30: 3, 40: 4} => O(N), N = array size\n * [4,1,2,3] => O(N)\n * runtime: O(NlogN)\n * space: O(N)\n */\nfunction buildMap(set) {\n  let map = new Map();\n  let index = 1;\n\n  for (let num of set.values()) {\n    map.set(num, index);\n    index++;\n  }\n\n  return map;\n}\n\nfunction buildRank(arr, map) {\n  let rank = [];\n\n  for (let num of arr) {\n    rank.push(map.get(num));\n  }\n\n  return rank;\n}\n\nfunction arrayRankTransform(arr) {\n  const sortedSet = new Set([...arr].sort((a, b) => a - b));\n  const map = buildMap(sortedSet);\n  return buildRank(arr, map);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/ransom-note/ransom-note.js",
    "content": "function canConstruct(ransomNote, magazine) {\n  let map = {};\n\n  for (let char of magazine) {\n    if (map[char]) {\n      map[char] += 1;\n    } else {\n      map[char] = 1;\n    }\n  }\n\n  for (let char of ransomNote) {\n    if (map[char]) {\n      map[char]--;\n    } else {\n      return false;\n    }\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/ransom_note/ransom_note.py",
    "content": "def can_construct(ransom_note, magazine):\n    if ransom_note == '':\n        return True\n\n    if magazine == '':\n        return False\n\n    letters_counter = {}\n\n    for letter in magazine:\n        if letter in letters_counter:\n            letters_counter[letter] += 1\n        else:\n            letters_counter[letter] = 1\n\n    for char in ransom_note:\n        if char not in letters_counter or letters_counter[char] == 0:\n            return False\n\n        letters_counter[char] -= 1\n\n    return True\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/reduce_zero/reduce_zero.py",
    "content": "# https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/\n\n\ndef reduce_number(num):\n    if num % 2 == 0:\n        return num / 2\n    else:\n        return num - 1\n\n\ndef number_of_steps(num):\n    counter = 0\n\n    while num:\n        counter += 1\n        num = reduce_number(num)\n\n    return counter\n\n\ndata_tests = [\n    (14, 6),\n    (8, 4)\n]\n\nfor number, expected in data_tests:\n    result = number_of_steps(number)\n    print(result, expected == result)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/reformat-date/reformat-date.js",
    "content": "// https://leetcode.com/problems/reformat-date\n\nfunction getDateInfo(date) {\n  let dateInfo = [];\n  let info = '';\n\n  for (let index = 0; index < date.length; index++) {\n    let char = date[index];\n    if (char === ' ') {\n      dateInfo.push(info);\n      info = '';\n    } else if (index === date.length - 1) {\n      dateInfo.push(info + char);\n    } else {\n      info += char;\n    }\n  }\n\n  return dateInfo;\n}\n\nconst monthStringToNumber = {\n  Jan: '01',\n  Feb: '02',\n  Mar: '03',\n  Apr: '04',\n  May: '05',\n  Jun: '06',\n  Jul: '07',\n  Aug: '08',\n  Sep: '09',\n  Oct: '10',\n  Nov: '11',\n  Dec: '12',\n};\n\nfunction formatDay(day) {\n  return day.length === 1 ? `0${day}` : day;\n}\n\nfunction reformatDate(date) {\n  let [day, month, year] = getDateInfo(date);\n  let dateDay = '';\n  let dateMonth = monthStringToNumber[month];\n\n  for (let char of day) {\n    if (!Number.isNaN(Number(char))) {\n      dateDay += char;\n    }\n  }\n\n  return `${year}-${dateMonth}-${formatDay(dateDay)}`;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/reformat-phone-number/reformat-phone-number.js",
    "content": "function removeSpacesAndDashes(number) {\n  return number.replaceAll('-', '').replaceAll(' ', '');\n}\n\nfunction reformatNumber(number) {\n  let num = removeSpacesAndDashes(number);\n  let blocks = [];\n  let block = [];\n  let blockLimit = 2;\n  let numLength = num.length;\n\n  for (let index = 0; index < numLength; index++) {\n    if (block.length === 0) {\n      if (numLength - index === 2) {\n        blocks.push(num.slice(index));\n        break;\n      }\n\n      if (numLength - index === 4) {\n        blocks.push(num.slice(index, index + 2));\n        blocks.push(num.slice(index + 2));\n        break;\n      }\n    }\n\n    if (index === blockLimit) {\n      blockLimit = index + 3;\n      block.push(num[index]);\n      blocks.push(block.join(''));\n      block = [];\n    } else {\n      block.push(num[index]);\n    }\n  }\n\n  return blocks.join('-');\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/relative-ranks/relative-ranks.js",
    "content": "function sortDesc(list) {\n  return list.sort((a, b) => b - a);\n}\n\nconst mapper = {\n  0: 'Gold Medal',\n  1: 'Silver Medal',\n  2: 'Bronze Medal',\n};\n\nfunction buildHashmap(list) {\n  let hashmap = new Map();\n\n  for (let [index, item] of list.entries()) {\n    hashmap.set(item, mapper[index] || (index + 1).toString());\n  }\n\n  return hashmap;\n}\n\nfunction getRelativeRanks(score, hashmap) {\n  let rank = [];\n\n  for (let value of score) {\n    rank.push(hashmap.get(value));\n  }\n\n  return rank;\n}\n\nfunction findRelativeRanks(score) {\n  const sortedScore = sortDesc([...score]);\n  const hashmap = buildHashmap(sortedScore);\n  return getRelativeRanks(score, hashmap);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/relative-sort-array/relative-sort-array.js",
    "content": "// https://leetcode.com/problems/relative-sort-array\n\nconst relativeSortArray = (arr1, arr2) => {\n  const mapper1 = {};\n  const mapper2 = {};\n\n  arr2.forEach((num) => (mapper2[num] = true));\n\n  arr1.forEach((num) => {\n    if (mapper1[num]) mapper1[num].push(num);\n    else if (mapper2[num]) mapper1[num] = [num];\n    else if (mapper1['other']) mapper1['other'].push(num);\n    else mapper1['other'] = [num];\n  });\n\n  const sortedArr = [];\n\n  arr2.forEach((num) => {\n    sortedArr.push(...mapper1[num]);\n  });\n\n  if (mapper1['other'])\n    sortedArr.push(...mapper1['other'].sort((a, b) => a - b));\n\n  return sortedArr;\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/remove-duplicates-from-sorted-list/remove-duplicates-from-sorted-list.js",
    "content": "function deleteDuplicates(head) {\n  if (!head || !head.next) {\n    return head;\n  }\n\n  let current = head;\n  let next = current.next;\n\n  while (next) {\n    if (current.val === next.val) {\n      next = next.next;\n      current.next = next;\n    } else {\n      current = next;\n      next = next.next;\n    }\n  }\n\n  return head;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/remove-linked-list-elements/remove-linked-list-elements.js",
    "content": "function removeElements(head, val) {\n  if (!head) return head;\n\n  while (head && head.val === val) {\n    head = head.next;\n  }\n\n  if (!head) return head;\n\n  let previous = head;\n  let current = head.next;\n\n  while (current) {\n    if (current.val === val) {\n      previous.next = current.next;\n      current = previous.next;\n    } else {\n      previous = previous.next;\n      current = current.next;\n    }\n  }\n\n  return head;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/remove-outermost-parentheses/remove-outermost-parentheses.js",
    "content": "export function removeOuterParentheses(string) {\n  const stack = [];\n  const result = [];\n\n  for (let i = 0; i < string.length; i++) {\n    const char = string[i];\n\n    if (char === '(') {\n      if (stack.length) {\n        result.push(char);\n      }\n\n      stack.push(char);\n    } else {\n      if (stack.length > 1) {\n        result.push(char);\n      }\n\n      stack.pop();\n    }\n  }\n\n  return result.join('');\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/remove-outermost-parentheses/tests/remove-outermost-parentheses.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { removeOuterParentheses } from '../remove-outermost-parentheses';\n\ndescribe('removeOuterParentheses', () => {\n  it('', () => {\n    expect(removeOuterParentheses('(()())(())')).toEqual('()()()');\n  });\n\n  it('', () => {\n    expect(removeOuterParentheses('(()())(())(()(()))')).toEqual(\n      '()()()()(())'\n    );\n  });\n\n  it('', () => {\n    expect(removeOuterParentheses('()()')).toEqual('');\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/remove-palindromic-subsequences/remove-palindromic-subsequences.js",
    "content": "function isPalindrome(s) {\n  return s === s.split('').reverse().join('');\n}\n\nfunction removePalindromeSub(s) {\n  return isPalindrome(s) ? 1 : 2;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/remove-trailing-zeros-from-a-string/remove-trailing-zeros-from-a-string.js",
    "content": "function removeTrailingZeros(num) {\n  let result = '';\n  let trailing = true;\n\n  for (let index = num.length - 1; index >= 0; index--) {\n    if (num[index] === '0' && trailing) {\n      continue;\n    } else {\n      trailing = false;\n      result = num[index] + result;\n    }\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/remove_duplicates/remove_duplicates.py",
    "content": "# https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string\n\ndef remove_duplicates(S):\n    if len(S) <= 1: return S\n\n    start, end = 0, 1\n\n    while end < len(S):\n        if S[start] != S[end]:\n            start = end\n            end = start + 1\n\n        elif S[start] == S[end] and end + 1 == len(S):\n            S = S[0:start]\n\n        elif S[start] == S[end]:\n            S = S[0:start] + S[end+1:]\n            start, end = 0, 1\n\n    return S\n\ndef remove_duplicates(S):\n    stack = []\n\n    for char in S:\n        if len(stack) and stack[-1] == char:\n            stack.pop()\n        else:\n            stack.append(char)\n\n    return ''.join(stack)"
  },
  {
    "path": "coding_interviews/leetcode/easy/remove_duplicates.py",
    "content": "# https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/\n\n'''\n- Examples:\n[1, 1, 2] # => 2\n[] # => 0\n[1, 1, 1] # => 1\n[1, 2, 3, 3, 4, 5] # => 5\n'''\n\ndef remove_duplicates(nums):\n    if not nums:\n        return 0\n\n    total_result = 1\n    num = nums[0]\n\n    for index in range(1, len(nums)):\n        if nums[index] != num:\n            nums[total_result] = nums[index]\n            total_result += 1\n            num = nums[index]\n\n    return total_result\n\nlist1 = [1, 1, 2]\nlist2 = []\nlist3 = [1, 1, 1]\nlist4 = [1, 2, 3, 3, 4, 5]\n\nprint remove_duplicates(list1)\nprint remove_duplicates(list2)\nprint remove_duplicates(list3)\nprint remove_duplicates(list4)\n\nprint list1\nprint list2\nprint list3\nprint list4\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/remove_duplicates_from_list.py",
    "content": "# https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/\n\nclass ListNode(object):\n    def __init__(self, value):\n        self.val = value\n        self.next = None\n\ndef remove_duplicates(head):\n    if head is None:\n        return\n\n    current_node = head\n\n    while current_node and current_node.next:\n        if current_node.val == current_node.next.val:\n            current_node.next = current_node.next.next\n        else:\n            current_node = current_node.next\n\n    return head\n\n# 1 -> 1 -> 2\nprint('1 -> 1 -> 2')\nhead = ListNode(1)\nhead.next = ListNode(1)\nhead.next.next = ListNode(2)\ncurrent_node = remove_duplicates(head)\n\nwhile current_node:\n    print(current_node.val)\n    current_node = current_node.next\n\n# 1 -> 1 -> 2 -> 3 -> 3\nprint('\\n1 -> 1 -> 2 -> 3 -> 3')\nhead = ListNode(1)\nhead.next = ListNode(1)\nhead.next.next = ListNode(2)\nhead.next.next.next = ListNode(3)\nhead.next.next.next.next = ListNode(3)\ncurrent_node = remove_duplicates(head)\n\nwhile current_node:\n    print(current_node.val)\n    current_node = current_node.next\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/remove_element.py",
    "content": "# https://leetcode.com/problems/remove-element/description/\n\n'''\nnums = [3, 2, 2, 3], val = 3 # => 2\nnums = [3, 2, 2, 3], val = 2 # => 2\nnums = [1, 2, 2, 4], val = 3 # => 4\nnums = [], val = 3 # => 0\n'''\n\ndef remove_element(nums, val):\n    while val in nums:\n        nums.remove(val)\n\n    return len(nums)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/replace_digits/replace_digits.py",
    "content": "# https://leetcode.com/problems/replace-all-digits-with-characters\n\ndef replace_digits(s):\n    replaced_string = []\n    \n    for index in range(len(s)):\n        if index % 2 == 0:\n            replaced_string.append(s[index])\n        else:\n            replaced_string.append(shift(s[index-1], s[index]))\n            \n    return ''.join(replaced_string)\n            \ndef shift(char, digit):\n    return chr(ord(char) + int(digit))\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/replace_elements/replace_elements.py",
    "content": "# https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side\n\ndef replace_elements(arr):\n    index, max_num = len(arr) - 1, -1\n\n    for number in reversed(arr):\n        arr[index] = max_num\n        max_num = max(number, max_num)\n        index -= 1\n            \n    return arr"
  },
  {
    "path": "coding_interviews/leetcode/easy/reshape-the-matrix/reshape-the-matrix.js",
    "content": "function matrixReshape(mat, r, c) {\n  if (mat.length * mat[0].length !== r * c) {\n    return mat;\n  }\n\n  let reshapedMatrix = [];\n  let reshapedMatrixRow = [];\n  let index = 0;\n\n  for (let row = 0; row < mat.length; row++) {\n    for (let col = 0; col < mat[row].length; col++) {\n      const num = mat[row][col];\n\n      if (index < c) {\n        reshapedMatrixRow.push(num);\n      } else {\n        reshapedMatrix.push(reshapedMatrixRow);\n        reshapedMatrixRow = [num];\n        index = 0;\n      }\n\n      index++;\n    }\n  }\n\n  reshapedMatrix.push(reshapedMatrixRow);\n\n  return reshapedMatrix;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/reverse-linked-list/reverse-linked-list.js",
    "content": "function reverseList(head) {\n  if (!head) {\n    return head;\n  }\n\n  let firstNode = head;\n  let secondNode = head.next;\n  let auxiliaryNode = null;\n  let previousNode = null;\n\n  while (secondNode) {\n    auxiliaryNode = secondNode.next;\n    secondNode.next = firstNode;\n    firstNode.next = previousNode;\n    previousNode = firstNode;\n    firstNode = secondNode;\n    secondNode = auxiliaryNode;\n  }\n\n  return firstNode;\n}\n\nfunction reverseListSimpler(head) {\n  let previous = null;\n  let current = head;\n  let next;\n\n  while (current) {\n    next = current.next;\n    current.next = previous;\n    previous = current;\n    current = next;\n  }\n\n  return previous;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/reverse-only-letters/reverse-only-letters.js",
    "content": "function isEnglishLetter(char) {\n  return (\n    (char.charCodeAt() >= 65 && char.charCodeAt() <= 90) ||\n    (char.charCodeAt() >= 97 && char.charCodeAt() <= 122)\n  );\n}\n\nfunction reverseOnlyLetters(s) {\n  const englishLetter = [];\n\n  for (let char of s) {\n    if (isEnglishLetter(char)) englishLetter.push(char);\n  }\n\n  let index = englishLetter.length - 1;\n  let output = s.split('');\n\n  for (let i = 0; i < s.length; i++) {\n    if (isEnglishLetter(s[i])) {\n      output[i] = englishLetter[index];\n      index--;\n    }\n  }\n\n  return output.join('');\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/reverse-prefix-of-word/reverse-prefix-of-word.js",
    "content": "function reverse(charsList) {\n  const reversedCharsList = [];\n\n  for (let i = charsList.length - 1; i >= 0; i--) {\n    reversedCharsList.push(charsList[i]);\n  }\n\n  return reversedCharsList;\n}\n\nexport function reversePrefix(word, char) {\n  let charsList = [];\n  let foundFirstOccurrence = false;\n\n  for (let i = 0; i < word.length; i++) {\n    const wordChar = word[i];\n    charsList.push(wordChar);\n\n    if (wordChar === char && !foundFirstOccurrence) {\n      foundFirstOccurrence = true;\n      charsList = reverse(charsList);\n    }\n  }\n\n  return charsList.join('');\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/reverse-prefix-of-word/tests/reverse-prefix-of-word.test.js",
    "content": "import { describe, it, expect } from 'vitest';\nimport { reversePrefix } from '../reverse-prefix-of-word';\n\ndescribe('reversePrefix', () => {\n  it('reverses the prefix', () => {\n    expect(reversePrefix('abcdefd', 'd')).toEqual('dcbaefd');\n  });\n\n  it('reverses the prefix', () => {\n    expect(reversePrefix('xyxzxe', 'z')).toEqual('zxyxxe');\n  });\n\n  it('reverses the prefix', () => {\n    expect(reversePrefix('abcd', 'z')).toEqual('abcd');\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/reverse-string/reverse-string-in-place.js",
    "content": "function reverseString(s) {\n  let pointer1 = 0;\n  let pointer2 = s.length - 1;\n  let auxiliaryChar;\n\n  while (pointer1 < pointer2) {\n    auxiliaryChar = s[pointer1];\n    s[pointer1] = s[pointer2];\n    s[pointer2] = auxiliaryChar;\n    pointer1++;\n    pointer2--;\n  }\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/reverse-string/reverse-string.js",
    "content": "function reverseString(s) {\n  let reversedString = [];\n\n  for (let index = s.length - 1; index >= 0; index--) {\n    reversedString.push(s[index]);\n  }\n\n  return reversedString;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/reverse-vowels-of-a-string/reverse-vowels-of-a-string.js",
    "content": "function reverseVowels(s) {\n  const allVowels = [];\n  const vowels = 'aeiouAEIOU';\n\n  for (let char of s) {\n    if (vowels.includes(char)) allVowels.push(char);\n  }\n\n  const reversedVowels = [];\n\n  for (\n    let index = 0, vowelIndex = allVowels.length - 1;\n    index < s.length;\n    index++\n  ) {\n    if (vowels.includes(s[index])) {\n      reversedVowels.push(allVowels[vowelIndex]);\n      vowelIndex--;\n    } else {\n      reversedVowels.push(s[index]);\n    }\n  }\n\n  return reversedVowels.join('');\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/reverse-words-in-a-string-iii/reverse-words-in-a-string-iii.js",
    "content": "function reverseWords(s) {\n  let reversedString = [];\n  let splittedString = s.split(' ');\n\n  for (let word of splittedString) {\n    let reversedWord = [];\n\n    for (let index = word.length - 1; index >= 0; index--) {\n      reversedWord.push(word[index]);\n    }\n\n    reversedString.push(reversedWord.join(''));\n  }\n\n  return reversedString.join(' ');\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/reverse_integer.py",
    "content": "# https://leetcode.com/problems/reverse-integer/\n\ndef reverse(x):\n    number_list = []\n\n    if x < 0:\n        negative = True\n        x *= -1\n    else:\n        negative = False\n\n    while x > 0:\n        number_list.append(x % 10)\n        x /= 10\n\n    result_number = 0\n\n    for index, n in enumerate(number_list):\n        result_number += n * pow(10, len(number_list) - 1 - index)\n\n    if negative:\n        result_number *= -1\n\n    if (result_number < 2147483648*-1 or result_number > 2147483647):\n        return 0\n\n    return result_number\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/reverse_string.py",
    "content": "'''\nhttps://leetcode.com/problems/reverse-string/description/\n\ninput: \"hello\"\noutput: \"olleh\"\n'''\n\ndef reverse_string(s):\n    return s[::-1]\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/reverse_vowels.py",
    "content": "'''\nhttps://leetcode.com/problems/reverse-vowels-of-a-string/description/\n\ninput: \"hello\"\noutput: \"holle\"\n\ninput: \"leetcode\"\noutput: \"leotcede\"\n'''\n\ndef vowel(char):\n    return char in ['a', 'e', 'i', 'o', 'u']\n\ndef reverse_vowels(s):\n    vowels = [char for char in s if vowel(char)]\n    index = len(vowels) - 1\n    result = ''\n\n    for char in s:\n        if vowel(char):\n            result += vowels[index]\n            index -= 1\n        else:\n            result += char\n\n    return result\n\n\n\nprint(reverse_vowels('hello') == 'holle')\nprint(reverse_vowels('leetcode') == 'leotcede')\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/reverse_words_string.py",
    "content": "'''\nhttps://leetcode.com/problems/reverse-words-in-a-string-iii/description/\n\ninput: \"Let's take LeetCode contest\"\noutput: \"s'teL ekat edoCteeL tsetnoc\"\n'''\n\ndef reverse_words(s):\n    return ' '.join([word[::-1] for word in s.split(' ')])\n\nprint(reverse_words(\"Let's take LeetCode contest\") == \"s'teL ekat edoCteeL tsetnoc\")\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/rings-and-rods/rings-and-rods.js",
    "content": "/*\nThere are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9.\n\nYou are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where:\n\nThe first character of the ith pair denotes the ith ring's color ('R', 'G', 'B').\nThe second character of the ith pair denotes the rod that the ith ring is placed on ('0' to '9').\nFor example, \"R3G2B1\" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1.\n\nReturn the number of rods that have all three colors of rings on them.\n\nInput: rings = \"B0B6G0R6R0R6G9\"\nOutput: 1\n\nInput: rings = \"B0R0G0R9R0B0G0\"\nOutput: 1\n*/\n\nexport function countPoints(rings = '') {\n  const rods = {\n    0: new Set(),\n    1: new Set(),\n    2: new Set(),\n    3: new Set(),\n    4: new Set(),\n    5: new Set(),\n    6: new Set(),\n    7: new Set(),\n    8: new Set(),\n    9: new Set(),\n  };\n\n  for (let i = 0; i < rings.length - 1; i += 2) {\n    const color = rings[i];\n    const position = rings[i + 1];\n    rods[position].add(color);\n  }\n\n  return Object.values(rods).reduce(\n    (count, colors) => (colors.size === 3 ? count + 1 : count),\n    0\n  );\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/rings-and-rods/tests/rings-and-rods.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { countPoints } from '../rings-and-rods';\n\ndescribe('countPoints', () => {\n  it('', () => {\n    expect(countPoints('B0B6G0R6R0R6G9')).toEqual(1);\n  });\n\n  it('', () => {\n    expect(countPoints('B0R0G0R9R0B0G0')).toEqual(1);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/root-equals-sum-of-children/index.js",
    "content": "function checkTree(root) {\n  return root.val === root.left.val + root.right.val;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/row-with-maximum-ones/row-with-maximum-ones.js",
    "content": "// https://leetcode.com/problems/row-with-maximum-ones\n\nfunction rowAndMaximumOnes(mat) {\n  let rowIndex;\n  let maxCountOfOnes = -Infinity;\n\n  for (let row = 0; row < mat.length; row++) {\n    let countOfOnes = 0;\n\n    for (let num of mat[row]) {\n      if (num === 1) {\n        countOfOnes++;\n      }\n    }\n\n    if (countOfOnes > maxCountOfOnes) {\n      maxCountOfOnes = countOfOnes;\n      rowIndex = row;\n    }\n  }\n\n  return [rowIndex, maxCountOfOnes];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/running_array_sum/running_array_sum.py",
    "content": "def running_sum(nums):\n    sum = 0\n    result = []\n\n    for num in nums:\n        sum += num\n        result.append(sum)\n\n    return result\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/same-tree/same-tree.js",
    "content": "function isSameTree(p, q) {\n  if (!p && !q) return true;\n  if ((!p && q) || (!q && p)) return false;\n\n  return (\n    p.val === q.val &&\n    isSameTree(p.left, q.left) &&\n    isSameTree(p.right, q.right)\n  );\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/same_tree.py",
    "content": "# https://leetcode.com/problems/same-tree/description/\n\ndef is_same_tree(p, q):\n    if (p and not q) or (not p and q):\n        return False\n\n    if not p and not q:\n        return True\n\n    return p.val == q.val and is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)\n\ndef is_same_tree(p, q):\n    if p and q:\n        return p.val == q.val and is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)\n\n    return p is q\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/search-in-a-binary-search-tree/search-in-a-binary-search-tree.js",
    "content": "function searchBST(root, val) {\n  if (!root) {\n    return null;\n  }\n\n  if (root.val === val) {\n    return root;\n  }\n\n  return searchBST(root.left, val) || searchBST(root.right, val);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/search-insert-position/search-insert-position-new.js",
    "content": "function getMiddle(start, end) {\n  return Math.floor((start + end) / 2);\n}\n\nfunction searchInsert(nums, target) {\n  let start = 0;\n  let end = nums.length - 1;\n  let middle = getMiddle(start, end);\n\n  while (start <= end) {\n    if (target < nums[middle]) {\n      end = middle - 1;\n      middle = getMiddle(start, end);\n    } else if (target > nums[middle]) {\n      start = middle + 1;\n      middle = getMiddle(start, end);\n    } else {\n      return middle;\n    }\n  }\n\n  return middle + 1;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/search-insert-position/search-insert-position.js",
    "content": "// https://leetcode.com/problems/search-insert-position\n\nconst searchInsert = (nums, target) => {\n  let start = 0;\n  let end = nums.length - 1;\n\n  while (start <= end) {\n    middle = Math.floor((start + end) / 2);\n    if (nums[middle] === target) return middle;\n    if (target > nums[middle]) start = middle + 1;\n    if (target < nums[middle]) end = middle - 1;\n  }\n\n  return start;\n};\n\nconst print = (nums, target) => console.log(searchInsert(nums, target));\n\nprint([1, 3, 5, 6], 5);\nprint([1, 3, 5, 6], 2);\nprint([1, 3, 5, 6], 7);\nprint([1, 3, 5, 6], 0);\nprint([1], 0);\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/search_in_a_binary_search_tree/search_in_a_binary_search_tree.py",
    "content": "# https://leetcode.com/problems/search-in-a-binary-search-tree\n\ndef searchBST(root, val):\n    if root and val < root.val:\n        return searchBST(root.left, val)\n        \n    if root and val > root.val:\n        return searchBST(root.right, val)\n        \n    return root\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/second-largest-digit-in-a-string/second-largest-digit-in-a-string.js",
    "content": "// https://leetcode.com/problems/second-largest-digit-in-a-string\n\nfunction secondHighest(s) {\n  let highest = -1;\n  let secHighest = -1;\n\n  for (let char of s) {\n    let numChar = Number(char);\n    let isInt = Number.isInteger(numChar);\n\n    if (isInt && numChar > highest) {\n      secHighest = highest;\n      highest = numChar;\n    } else if (isInt && numChar !== highest && numChar > secHighest) {\n      secHighest = numChar;\n    }\n  }\n\n  return highest === secHighest ? -1 : secHighest;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/self_dividing_numbers.py",
    "content": "'''\nhttps://leetcode.com/problems/self-dividing-numbers/description/\n\nInput: left = 1, right = 22\nOutput: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]\n'''\n\ndef self_dividing_numbers(left, right):\n    output = [number for number in range(left, right + 1) if dividing(number, number)]\n    return output\n\ndef dividing(number, original):\n    if number == 0: return True\n    if number % 10 == 0: return False\n    return dividing(number / 10, original) and original % (number % 10) == 0\n\nprint(self_dividing_numbers(1, 22) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22])\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/semi-ordered-permutation/semi-ordered-permutation.js",
    "content": "// https://leetcode.com/problems/semi-ordered-permutation\n\nfunction semiOrderedPermutation(nums) {\n  let N = nums.length;\n  let indexFirst;\n  let indexLast;\n\n  for (let index = 0; index < N; index++) {\n    if (nums[index] === 1) indexFirst = index;\n    if (nums[index] === N) indexLast = index;\n  }\n\n  let swaps = indexFirst;\n\n  if (indexFirst > indexLast) swaps += N - indexLast - 2;\n  else swaps += N - indexLast - 1;\n\n  return swaps;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/separate-the-digits-in-an-array/separate-the-digits-in-an-array.js",
    "content": "function separateDigits(nums) {\n  const answer = [];\n\n  for (let num of nums) {\n    const numString = num.toString();\n\n    for (let charNum of numString) {\n      answer.push(Number(charNum));\n    }\n  }\n\n  return answer;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/shortest_to_char/shortest_to_char.py",
    "content": "# https://leetcode.com/problems/shortest-distance-to-a-character\n\ndef shortest_to_char(s, c):\n    all_c_indexes = []\n    \n    for index, char in enumerate(s):\n        if char == c:\n            all_c_indexes.append(index)\n            \n    answer = []\n    \n    for index, char in enumerate(s):\n        if char == c:\n            answer.append(0)\n        else:\n            answer_index = float('Inf')\n            \n            for c_index in all_c_indexes:\n                answer_index = min(answer_index, abs(c_index - index))\n            \n            answer.append(answer_index)\n            \n    return answer\n\ndef shortest_to_char(s, c):\n    previous = float('-Inf')\n    answer = []\n    \n    for index, char in enumerate(s):\n        if char == c:\n            previous = index\n            \n        answer.append(index - previous)\n        \n    previous = float('Inf')\n    \n    for index in range(len(s) - 1, -1, -1):\n        if s[index] == c:\n            previous = index\n            \n        answer[index] = min(answer[index], previous - index)\n            \n    return answer"
  },
  {
    "path": "coding_interviews/leetcode/easy/shuffle_string/shuffle_string.py",
    "content": "# shuffle string\n# https://leetcode.com/problems/shuffle-string\n\n\ndef restore_string(s, indices):\n    index_to_char_mapper = {}\n\n    for index in range(len(s)):\n        index_to_char_mapper[indices[index]] = s[index]\n\n    return ''.join([index_to_char_mapper[index] for index in range(len(s))])\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/shuffle_the_array/shuffle_the_array.py",
    "content": "def shuffle(nums, n):\n    first_half = nums[:n]\n    last_half = nums[n:]\n    final_list = []\n\n    for index in range(len(first_half)):\n        final_list.append(first_half[index])\n        final_list.append(last_half[index])\n\n    return final_list\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sign_of_the_product_of_an_array/sign_of_the_product_of_an_array.py",
    "content": "# https://leetcode.com/problems/sign-of-the-product-of-an-array\n\ndef array_sign(nums):\n    product = 1\n    \n    for num in nums:\n        if num == 0: return 0\n        product *= num\n        \n    if product > 0:\n        return 1\n\n    if product < 0:\n        return -1"
  },
  {
    "path": "coding_interviews/leetcode/easy/single-number/single-number.js",
    "content": "function singleNumber(nums) {\n  let hashmap = {};\n\n  for (let num of nums) {\n    if (hashmap[num]) {\n      hashmap[num]++;\n    } else {\n      hashmap[num] = 1;\n    }\n  }\n\n  for (let num of nums) {\n    if (hashmap[num] === 1) {\n      return num;\n    }\n  }\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/single_number/single_number.py",
    "content": "# https://leetcode.com/problems/single-number\n\ndef single_number(nums):\n    counter = {}\n    \n    for num in nums:\n        if num in counter:\n            counter[num] += 1\n        else:\n            counter[num] = 1\n            \n    for num in nums:\n        if counter[num] == 1: return num\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/slowest-key/slowest-key.js",
    "content": "function isLexicographicallyLarger(keysPressed, keyPressedIndex, index) {\n  return keysPressed[index] > keysPressed[keyPressedIndex];\n}\n\nfunction slowestKey(releaseTimes, keysPressed) {\n  let longestDuration = releaseTimes[0];\n  let previousRelease = releaseTimes[0];\n  let keyPressedIndex = 0;\n\n  for (let index = 1; index < releaseTimes.length; index++) {\n    let currentRelease = releaseTimes[index];\n    let currentDuration = currentRelease - previousRelease;\n\n    if (currentDuration > longestDuration) {\n      longestDuration = currentDuration;\n      keyPressedIndex = index;\n    }\n\n    if (\n      currentDuration === longestDuration &&\n      isLexicographicallyLarger(keysPressed, keyPressedIndex, index)\n    ) {\n      longestDuration = currentDuration;\n      keyPressedIndex = index;\n    }\n\n    previousRelease = currentRelease;\n  }\n\n  return keysPressed[keyPressedIndex];\n}\n\nfunction slowestKey(releaseTimes, keysPressed) {\n  let longestDuration = releaseTimes[0];\n  let previousRelease = releaseTimes[0];\n  let keyPressedIndex = 0;\n\n  for (let index = 1; index < releaseTimes.length; index++) {\n    let currentRelease = releaseTimes[index];\n    let currentDuration = currentRelease - previousRelease;\n\n    if (\n      currentDuration > longestDuration ||\n      (currentDuration === longestDuration &&\n        isLexicographicallyLarger(keysPressed, keyPressedIndex, index))\n    ) {\n      longestDuration = currentDuration;\n      keyPressedIndex = index;\n    }\n\n    previousRelease = currentRelease;\n  }\n\n  return keysPressed[keyPressedIndex];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/smallest-even-multiple/smallest-even-multiple.js",
    "content": "function smallestEvenMultiple(n) {\n  return n % 2 === 0 ? n : n * 2;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/smallest-index-with-equal-value/smallest-index-with-equal-value.js",
    "content": "function smallestEqual(nums) {\n  for (let [index, num] of nums.entries()) {\n    if (index % 10 === num) {\n      return index;\n    }\n  }\n\n  return -1;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/smallest-range-i/optimized-smallest-range-i.js",
    "content": "// https://leetcode.com/problems/smallest-range-i\n\nfunction minMax(nums) {\n  let min = Infinity;\n  let max = -Infinity;\n\n  for (let num of nums) {\n    min = Math.min(min, num);\n    max = Math.max(max, num);\n  }\n\n  return [min, max];\n}\n\nfunction smallestRangeI(nums, k) {\n  let [min, max] = minMax(nums);\n  return Math.max(0, max - k - (min + k));\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/smallest-range-i/smallest-range-i.js",
    "content": "// https://leetcode.com/problems/smallest-range-i\n\nfunction smallestRangeI(nums, k) {\n  let smaller = Infinity;\n  let bigger = -Infinity;\n\n  for (let num of nums) {\n    smaller = Math.min(smaller, num);\n    bigger = Math.max(bigger, num);\n  }\n\n  let middle = Math.floor((bigger + smaller) / 2);\n  let min = Infinity;\n  let max = -Infinity;\n\n  if (k > bigger - middle) {\n    max = middle;\n  } else {\n    max = bigger - k;\n  }\n\n  if (k > middle - smaller) {\n    min = middle;\n  } else {\n    min = smaller + k;\n  }\n\n  return max - min;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/smallest-range-i/smallest-range-iI.js",
    "content": "// https://leetcode.com/problems/smallest-range-i\n\nfunction smallestRangeI(nums, k) {\n  let min = Math.min(...nums);\n  let max = Math.max(...nums);\n  return Math.max(0, max - k - (min + k));\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/smallest_numbers/smallest_numbers.py",
    "content": "# https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number\n\n'''\nnums = [8,1,2,2,3]\n[4,0,1,1,3]\n\nnums = [6,5,4,8]\n[2,1,0,3]\n'''\n\n\n'''\nO(Nˆ2): Runtime / O(N): Space\n'''\n\n\ndef smaller_numbers_than_current(nums):\n    smaller_numbers_counters = []\n\n    for num in nums:\n        counter = 0\n\n        for compared_num in nums:\n            if compared_num < num:\n                counter += 1\n\n        smaller_numbers_counters.append(counter)\n\n    return smaller_numbers_counters\n\n\n'''\nO(NlogN): Runtime / O(N): Space\n'''\n\n\ndef smaller_numbers_than_current_2(nums):\n    smaller_numbers_counters = {}\n\n    for index, num in enumerate(sorted(nums)):\n        if num not in smaller_numbers_counters:\n            smaller_numbers_counters[num] = index\n\n    return [smaller_numbers_counters[num] for num in nums]\n\n\ndata_tests = [\n    ([8, 1, 2, 2, 3], [4, 0, 1, 1, 3]),\n    ([6, 5, 4, 8], [2, 1, 0, 3])\n]\n\nfor numbers, expected in data_tests:\n    result = smaller_numbers_than_current(numbers)\n    print(result, result == expected)\n\n    result = smaller_numbers_than_current_2(numbers)\n    print(result, result == expected)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sort-array-by-increasing-frequency/sort-array-by-increasing-frequency.js",
    "content": "function buildCounter(nums) {\n  let counter = new Map();\n\n  for (let num of nums) {\n    if (counter.has(num)) counter.set(num, counter.get(num) + 1);\n    else counter.set(num, 1);\n  }\n\n  return counter;\n}\n\nfunction toPairs(counter) {\n  const pairs = [];\n\n  for (let [key, value] of counter.entries()) {\n    pairs.push([key, value]);\n  }\n\n  return pairs;\n}\n\nfunction byCount(pair1, pair2) {\n  if (pair1[1] < pair2[1]) return -1;\n  if (pair1[1] === pair2[1] && pair1[0] >= pair2[0]) return -1;\n  if (pair1[1] === pair2[1] && pair1[0] < pair2[0]) return 1;\n  if (pair1[1] > pair2[1]) return 1;\n  return 0;\n}\n\nfunction buildResult(pairs) {\n  const result = [];\n\n  for (let [num, count] of pairs) {\n    for (let counter = 1; counter <= count; counter++) {\n      result.push(num);\n    }\n  }\n\n  return result;\n}\n\nfunction frequencySort(nums) {\n  const counter = buildCounter(nums);\n  const pairs = toPairs(counter);\n  pairs.sort(byCount);\n  return buildResult(pairs);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sort-array-by-parity/sort-array-by-parity-two-loops.js",
    "content": "// https://leetcode.com/problems/sort-array-by-parity\n\nfunction sortArrayByParity(nums) {\n  let output = [];\n\n  for (let num of nums) {\n    if (num % 2 === 0) output.push(num);\n  }\n\n  for (let num of nums) {\n    if (num % 2 !== 0) output.push(num);\n  }\n\n  return output;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sort-array-by-parity/sort-array-by-parity.js",
    "content": "// https://leetcode.com/problems/sort-array-by-parity\n\nfunction sortArrayByParity(nums) {\n  let odd = [];\n  let even = [];\n\n  for (let num of nums) {\n    if (num % 2 === 0) even.push(num);\n    else odd.push(num);\n  }\n\n  return [...even, ...odd];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sort-array-by-parity-ii/sort-array-by-parity-ii.js",
    "content": "function isEven(num) {\n  return num % 2 === 0;\n}\n\nfunction separateIntoEvensAndOdds(nums) {\n  let evens = [];\n  let odds = [];\n\n  for (let num of nums) {\n    if (isEven(num)) evens.push(num);\n    else odds.push(num);\n  }\n\n  return [evens, odds];\n}\n\nexport function sortArrayByParityII(nums) {\n  let [evens, odds] = separateIntoEvensAndOdds(nums);\n  let result = [];\n\n  for (let index = 0; index < evens.length; index++) {\n    result.push(evens[index]);\n    result.push(odds[index]);\n  }\n\n  return result;\n}\n\nexport function sortArrayByParityIIInPlace(nums) {\n  for (let index = 0; index < nums.length - 1; index++) {\n    if (isEven(index) !== isEven(nums[index])) {\n      for (let index2 = index + 1; index2 < nums.length; index2++) {\n        if (isEven(index) === isEven(nums[index2])) {\n          let num = nums[index];\n          nums[index] = nums[index2];\n          nums[index2] = num;\n          break;\n        }\n      }\n    }\n  }\n\n  return nums;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sort-array-by-parity-ii/tests/sort-array-by-parity-ii.test.js",
    "content": "import { describe, it, expect } from 'vitest';\nimport {\n  sortArrayByParityII,\n  sortArrayByParityIIInPlace,\n} from '../sort-array-by-parity-ii';\n\ndescribe('sortArrayByParityII', () => {\n  it('', () => {\n    expect(sortArrayByParityII([4, 2, 5, 7])).toEqual([4, 5, 2, 7]);\n  });\n\n  it('', () => {\n    expect(sortArrayByParityII([2, 3])).toEqual([2, 3]);\n  });\n\n  it('', () => {\n    expect(sortArrayByParityII([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])).toEqual([\n      2, 1, 4, 3, 6, 5, 8, 7, 10, 9,\n    ]);\n  });\n\n  it('', () => {\n    expect(sortArrayByParityII([2, 3, 1, 1, 4, 0, 0, 4, 3, 3])).toEqual([\n      2, 3, 4, 1, 0, 1, 0, 3, 4, 3,\n    ]);\n  });\n});\n\ndescribe('sortArrayByParityIIInPlace', () => {\n  it('', () => {\n    expect(sortArrayByParityIIInPlace([4, 2, 5, 7])).toEqual([4, 5, 2, 7]);\n  });\n\n  it('', () => {\n    expect(sortArrayByParityIIInPlace([2, 3])).toEqual([2, 3]);\n  });\n\n  it('', () => {\n    expect(sortArrayByParityIIInPlace([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])).toEqual(\n      [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]\n    );\n  });\n\n  it('', () => {\n    expect(sortArrayByParityIIInPlace([2, 3, 1, 1, 4, 0, 0, 4, 3, 3])).toEqual([\n      2, 3, 4, 1, 0, 1, 0, 3, 4, 3,\n    ]);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sort-even-and-odd-indices-independently/sort-even-and-odd-indices-independently.js",
    "content": "function decreasing(a, b) {\n  return b - a;\n}\n\nfunction increasing(a, b) {\n  return a - b;\n}\n\nfunction sortEvenOdd(nums) {\n  let evens = [];\n  let odds = [];\n\n  for (let index = 0; index < nums.length; index++) {\n    if (index % 2 === 0) evens.push(nums[index]);\n    else odds.push(nums[index]);\n  }\n\n  evens.sort(increasing);\n  odds.sort(decreasing);\n\n  let result = [];\n  let biggerLength = evens.length > odds.length ? evens.length : odds.length;\n\n  for (let index = 0; index < biggerLength; index++) {\n    if (index < evens.length) result.push(evens[index]);\n    if (index < odds.length) result.push(odds[index]);\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sort-integers-by-the-number-of-1-bits/sort-integers-by-the-number-of-1-bits.js",
    "content": "function toBinary(num) {\n  if (num === 0) return { binary: '0', numberOfOneBits: 0 };\n\n  let binary = [];\n  let numberOfOneBits = 0;\n  let numCopy = num;\n\n  while (numCopy > 0) {\n    const binaryDigit = numCopy % 2;\n    if (binaryDigit) numberOfOneBits++;\n    binary.unshift(String(binaryDigit));\n    numCopy = Math.floor(numCopy / 2);\n  }\n\n  return { num, binary: binary.join(''), numberOfOneBits };\n}\n\nfunction byNumberOfOneBits(binary1, binary2) {\n  if (binary1.numberOfOneBits < binary2.numberOfOneBits) return -1;\n  if (binary1.numberOfOneBits > binary2.numberOfOneBits) return 1;\n  if (\n    binary1.numberOfOneBits === binary2.numberOfOneBits &&\n    binary1.num < binary2.num\n  )\n    return -1;\n  return 0;\n}\n\nfunction sortByBits(nums) {\n  const hashmap = new Map();\n  const binaries = [];\n  const result = [];\n\n  for (let num of nums) {\n    const binary = toBinary(num);\n    hashmap.set(binary.binary, num);\n    binaries.push(binary);\n  }\n\n  binaries.sort(byNumberOfOneBits);\n\n  for (let { binary } of binaries) {\n    result.push(hashmap.get(binary));\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sort-the-people/sort-the-people.js",
    "content": "function sortPeople(names, heights) {\n  const heightToName = new Map();\n\n  for (let index = 0; index < names.length; index++) {\n    const name = names[index];\n    const height = heights[index];\n    heightToName.set(height, name);\n  }\n\n  return heights\n    .sort((height1, height2) => height2 - height1)\n    .map((height) => heightToName.get(height));\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sort_array_by_parity/sort_array_by_parity.py",
    "content": "# https://leetcode.com/problems/sort-array-by-parity/submissions/\n\n'''\nGiven an array A of non-negative integers,\nreturn an array consisting of all the even elements of A,\nfollowed by all the odd elements of A.\n\nYou may return any answer array that satisfies this condition.\n\nExample:\nInput: [3,1,2,4]\nOutput: [2,4,3,1]\n'''\n\n\ndef sort_array_by_parity(A):\n    even_numbers = []\n    odd_numbers = []\n\n    for number in A:\n        if number % 2 == 0:\n            even_numbers.append(number)\n        else:\n            odd_numbers.append(number)\n\n    return even_numbers + odd_numbers\n\n\ndata_tests = [\n    ([1, 2, 3, 4], [2, 4, 1, 3]),\n    ([3, 1, 2, 4], [2, 4, 3, 1]),\n]\n\nfor numbers, expected in data_tests:\n    result = sort_array_by_parity(numbers)\n    print(result, result == expected)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sort_sentence/sort_sentence.py",
    "content": "# https://leetcode.com/problems/sorting-the-sentence\n\ndef sort_sentence(s):\n    words = s.split()\n    index_to_word = {}\n\n    for word in words:\n        index = int(word[-1])\n        actual_word = word[:len(word) - 1]\n        index_to_word[index] = actual_word\n        \n    sentence = []\n    \n    for index in range(1, len(words) + 1):\n        sentence.append(index_to_word[index])\n        \n    return ' '.join(sentence)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/special-positions-in-a-binary-matrix/special-positions-in-a-binary-matrix-cache.js",
    "content": "function countOnesInRow(matrix, row) {\n  let ones = 0;\n\n  for (let col = 0; col < matrix[row].length; col++) {\n    if (matrix[row][col] === 1) ones++;\n  }\n\n  return ones;\n}\n\nfunction countOnesInCol(matrix, col) {\n  let ones = 0;\n\n  for (let row = 0; row < matrix.length; row++) {\n    if (matrix[row][col] === 1) ones++;\n  }\n\n  return ones;\n}\n\nfunction numSpecial(matrix) {\n  let specialPositions = 0;\n  let hashmapRow = new Map();\n  let hashmapCol = new Map();\n\n  for (let row = 0; row < matrix.length; row++) {\n    for (let col = 0; col < matrix[row].length; col++) {\n      let rowOnes = hashmapRow.has(row)\n        ? hashmapRow.get(row)\n        : countOnesInRow(matrix, row);\n\n      hashmapRow.set(row, rowOnes);\n\n      let colOnes = hashmapCol.has(col)\n        ? hashmapCol.get(col)\n        : countOnesInCol(matrix, col);\n\n      hashmapCol.set(col, colOnes);\n\n      if (matrix[row][col] === 1 && rowOnes === 1 && colOnes === 1) {\n        specialPositions++;\n      }\n    }\n  }\n\n  return specialPositions;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/special-positions-in-a-binary-matrix/special-positions-in-a-binary-matrix.js",
    "content": "function countOnesInRow(matrix, row) {\n  let ones = 0;\n\n  for (let col = 0; col < matrix[row].length; col++) {\n    if (matrix[row][col] === 1) ones++;\n  }\n\n  return ones;\n}\n\nfunction countOnesInCol(matrix, col) {\n  let ones = 0;\n\n  for (let row = 0; row < matrix.length; row++) {\n    if (matrix[row][col] === 1) ones++;\n  }\n\n  return ones;\n}\n\nfunction numSpecial(matrix) {\n  let specialPositions = 0;\n\n  for (let row = 0; row < matrix.length; row++) {\n    for (let col = 0; col < matrix[row].length; col++) {\n      if (\n        matrix[row][col] === 1 &&\n        countOnesInRow(matrix, row) === 1 &&\n        countOnesInCol(matrix, col) === 1\n      ) {\n        specialPositions++;\n      }\n    }\n  }\n\n  return specialPositions;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/split-strings-by-separator/split-strings-by-separator.js",
    "content": "// https://leetcode.com/problems/split-strings-by-separator\n\nfunction splitWordsBySeparator(words, separator) {\n  let output = [];\n\n  for (let word of words) {\n    let start = 0;\n\n    for (let index = 0; index < word.length; index++) {\n      if (word[index] === separator) {\n        const str = word.slice(start, index);\n        if (str.length) output.push(str);\n        start = index + 1;\n      } else if (index === word.length - 1) {\n        output.push(word.slice(start, index + 1));\n        start = index + 1;\n      }\n    }\n  }\n\n  return output;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/split-with-minimum-sum/split-with-minimum-sum.js",
    "content": "function splitNum(num) {\n  let numsString = num\n    .toString()\n    .split('')\n    .sort((a, b) => a - b);\n\n  let firstHalf = [];\n  let lastHalf = [];\n  let isFirstHalf = true;\n\n  for (let charNum of numsString) {\n    if (isFirstHalf) firstHalf.push(charNum);\n    else lastHalf.push(charNum);\n    isFirstHalf = !isFirstHalf;\n  }\n\n  return Number(firstHalf.join('')) + Number(lastHalf.join(''));\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/split_string_in_balanced_strings/split_string_in_balanced_strings.py",
    "content": "# https://leetcode.com/problems/split-a-string-in-balanced-strings/\n\n\ndef balanced_string_split(s):\n    els = 0\n    ares = 0\n    max = 0\n\n    for char in s:\n        if char == 'L':\n            els += 1\n        else:\n            ares += 1\n\n        if els == ares:\n            max += 1\n            els = 0\n            ares = 0\n\n    return max\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/squares-of-a-sorted-array/squares-of-a-sorted-array-on.js",
    "content": "function buildArray(n) {\n  const list = [];\n\n  for (let i = 1; i <= n; i++) {\n    list.push(0);\n  }\n\n  return list;\n}\n\nfunction sortedSquares(nums) {\n  let sortedSquaresNumbers = buildArray(0);\n  let leftIndex = 0;\n  let rightIndex = nums.length - 1;\n  let pointer = nums.length - 1;\n\n  while (leftIndex <= rightIndex) {\n    let left = nums[leftIndex];\n    let right = nums[rightIndex];\n\n    if (Math.abs(left) > Math.abs(right)) {\n      sortedSquaresNumbers[pointer] = Math.pow(left, 2);\n      leftIndex++;\n    } else {\n      sortedSquaresNumbers[pointer] = Math.pow(right, 2);\n      rightIndex--;\n    }\n\n    pointer--;\n  }\n\n  return sortedSquaresNumbers;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/squares-of-a-sorted-array/squares-of-a-sorted-array.js",
    "content": "function square(num) {\n  return num * num;\n}\n\nfunction byIncreasingOrder(num1, num2) {\n  return num1 - num2;\n}\n\nfunction sortedSquares(nums) {\n  return nums.map(square).sort(byIncreasingOrder);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/squares_of_a_sorted_array/squares_of_a_sorted_array.py",
    "content": "# https://leetcode.com/problems/squares-of-a-sorted-array\n\n'''\nGiven an array of integers A sorted in non-decreasing order,\nreturn an array of the squares of each number, also in sorted non-decreasing order.\n\nExample 1:\nInput: [-4,-1,0,3,10]\nOutput: [0,1,9,16,100]\n\nExample 2:\nInput: [-7,-3,2,3,11]\nOutput: [4,9,9,49,121]\n'''\n\n\ndef squares_of_a_sorted_array(A):\n    new_array = []\n\n    for number in A:\n        new_array.append(number * number)\n\n    return sorted(new_array)\n\n\ndef squares_of_a_sorted_array_in_place(A):\n    for index in range(len(A)):\n        A[index] = A[index] * A[index]\n\n    return sorted(A)\n\n\ndata_tests = [\n    ([-4, -1, 0, 3, 10], [0, 1, 9, 16, 100]),\n    ([-7, -3, 2, 3, 11], [4, 9, 9, 49, 121])\n]\n\nfor numbers, expected in data_tests:\n    result = squares_of_a_sorted_array(numbers)\n    print(result, result == expected)\n\n    result = squares_of_a_sorted_array_in_place(numbers)\n    print(result, result == expected)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/str_str/str_str.py",
    "content": "'''\nhttps://leetcode.com/problems/implement-strstr\nImplement strStr().\n\nReturn the index of the first occurrence of needle in haystack,\nor -1 if needle is not part of haystack.\n\n- Example 1:\n\nInput: haystack = \"hello\", needle = \"ll\"\nOutput: 2\n\n- Example 2:\n\nInput: haystack = \"aaaaa\", needle = \"bba\"\nOutput: -1\n'''\n\n\ndef strStr(haystack, needle):\n    if needle == '':\n        return 0\n\n    neddle_length = len(needle)\n\n    for index in range(len(haystack) - neddle_length + 1):\n        if haystack[index:index+neddle_length] == needle:\n            return index\n\n    return -1\n\n\ntest_data = [\n    (\"hello\", \"ll\", 2),\n    (\"aaaaa\", \"bba\", -1),\n    (\"other\", \"\", 0),\n]\n\nfor haystack, needle, expected in test_data:\n    result = strStr(haystack, needle)\n    print('result as expected?', result == expected)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/string-matching-in-an-array/string-matching-in-an-array.js",
    "content": "function isSubstring(subword, word) {\n  for (let index = 0; index <= word.length - subword.length; index++) {\n    if (subword === word.slice(index, index + subword.length)) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nfunction addSubstring(word1, word2, answer) {\n  if (word1.length <= word2.length) {\n    isSubstring(word1, word2) && answer.add(word1);\n  } else {\n    isSubstring(word2, word1) && answer.add(word2);\n  }\n}\n\nfunction stringMatching(words) {\n  let answer = new Set([]);\n\n  for (let i = 0; i < words.length - 1; i++) {\n    for (let j = i + 1; j < words.length; j++) {\n      let word1 = words[i];\n      let word2 = words[j];\n      addSubstring(word1, word2, answer);\n    }\n  }\n\n  return [...answer];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/subarrays-distinct-element-sum-of-squares-i/subarrays-distinct-element-sum-of-squares-i.js",
    "content": "// https://leetcode.com/problems/subarrays-distinct-element-sum-of-squares-i\n\nfunction sumCounts(nums) {\n  let sum = 0;\n\n  for (let i = 0; i < nums.length; i++) {\n    let set = new Set();\n\n    for (let j = i; j < nums.length; j++) {\n      set.add(nums[j]);\n      sum += set.size ** 2;\n    }\n  }\n\n  return sum;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/subdomain_visit_count.py",
    "content": "'''\nhttps://leetcode.com/problems/subdomain-visit-count/description/\n\nExample 1:\nInput: [\"9001 discuss.leetcode.com\"]\nOutput: [\"9001 discuss.leetcode.com\", \"9001 leetcode.com\", \"9001 com\"]\n\nExample 2:\nInput: [\"900 google.mail.com\", \"50 yahoo.com\", \"1 intel.mail.com\", \"5 wiki.org\"]\nOutput: [\"901 mail.com\", \"50 yahoo.com\", \"900 google.mail.com\", \"5 wiki.org\",\"5 org\", \"1 intel.mail.com\", \"951 com\"]\n'''\n\ndef update_subdomain_counter(sc, s, c):\n    if s in sc:\n        sc[s] += int(c)\n    else:\n        sc[s] = int(c)\n\ndef subdomain_visits(cpdomains):\n    subdomain_counter = {}\n\n    for cpdomain in cpdomains:\n        code, subdomain = cpdomain.split(' ')\n        update_subdomain_counter(subdomain_counter, subdomain, code)\n\n        while subdomain.find(\".\") != -1:\n            subdomain = subdomain.split('.', 1)[1]\n            update_subdomain_counter(subdomain_counter, subdomain, code)\n\n    return [str(counter) + \" \" + subdomain for subdomain, counter in subdomain_counter.items()]\n\nprint(subdomain_visits([\"9001 discuss.leetcode.com\"]))\nprint(subdomain_visits([\"900 google.mail.com\", \"50 yahoo.com\", \"1 intel.mail.com\", \"5 wiki.org\"]))\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/substrings-of-size-three-with-distinct-characters/substrings-of-size-three-with-distinct-characters.js",
    "content": "function isGoodString(string) {\n  let [char1, char2, char3] = string;\n  return char1 !== char2 && char1 !== char3 && char2 !== char3;\n}\n\nfunction countGoodSubstrings(string) {\n  let goodSubstringsCounter = 0;\n\n  for (let index = 0; index < string.length - 2; index++) {\n    const substring = string.slice(index, index + 3);\n\n    if (isGoodString(substring)) {\n      goodSubstringsCounter++;\n    }\n  }\n\n  return goodSubstringsCounter;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/subtract_product_and_sum/subtract_product_and_sum.py",
    "content": "# https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer\n\n'''\nGiven an integer number n, return the difference between the product of its\ndigits and the sum of its digits.\n\nInput: n = 234\nOutput: 15\n\nInput: n = 4421\nOutput: 21\n'''\n\n\ndef subtract_product_and_sum(num):\n    multiplications = 1\n    additions = 0\n\n    for digit in str(num):\n        multiplications *= int(digit)\n        additions += int(digit)\n\n    return multiplications - additions\n\n\ndata_tests = [\n    (234, 15),\n    (4421, 21)\n]\n\n\nfor num, expected in data_tests:\n    result = subtract_product_and_sum(num)\n    print(result, result == expected)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/subtree-of-another-tree/subtree-of-another-tree.js",
    "content": "function isSame(root, subRoot) {\n  if (!root && !subRoot) return true;\n  if (!root || !subRoot || root.val !== subRoot.val) return false;\n  return isSame(root.left, subRoot.left) && isSame(root.right, subRoot.right);\n}\n\nfunction isSubtree(root, subRoot) {\n  return root\n    ? isSame(root, subRoot) ||\n        isSubtree(root.left, subRoot) ||\n        isSubtree(root.right, subRoot)\n    : false;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sum-multiples/sum-multiples.js",
    "content": "function sumOfMultiples(n) {\n  let sum = 0;\n\n  for (let num = 1; num <= n; num++) {\n    if (num % 7 === 0 || num % 5 === 0 || num % 3 === 0) {\n      sum += num;\n    }\n  }\n\n  return sum;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sum-of-all-subset-xor-totals/sum-of-all-subset-xor-totals.js",
    "content": "function getAllSubsets(subset, nums, output, index) {\n  if (index == nums.length) {\n    subset.push(output);\n    return;\n  }\n\n  getAllSubsets(subset, nums, [...output], index + 1);\n  output.push(nums[index]);\n  getAllSubsets(subset, nums, [...output], index + 1);\n}\n\nfunction calculateTotalXOR(nums) {\n  let totalXOR = nums[0];\n\n  for (let i = 1; i < nums.length; i++) {\n    totalXOR = totalXOR ^ nums[i];\n  }\n\n  return totalXOR;\n}\n\nfunction subsetXORSum(nums) {\n  let total = 0;\n  let subset = [];\n\n  getAllSubsets(subset, nums, [], 0);\n\n  for (let list of subset) {\n    if (list.length) total += calculateTotalXOR(list);\n  }\n\n  return total;\n}\n\nconsole.log(subsetXORSum([1, 2, 3]));\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sum-of-digits-in-base-k/sum-of-digits-in-base-k.js",
    "content": "function fromDecimalToK(n, k) {\n  const baseKN = [];\n\n  while (n) {\n    baseKN.push(n % k);\n    n = Math.floor(n / k);\n  }\n\n  return baseKN;\n}\n\nfunction sumBase(n, k) {\n  return fromDecimalToK(n, k).reduce((num, sum) => sum + num, 0);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sum-of-digits-of-string-after-convert/sum-of-digits-of-string-after-convert.js",
    "content": "function toNum(char) {\n  return char.charCodeAt() - 96;\n}\n\nfunction getNumbers(s) {\n  let numbers = [];\n\n  for (let char of s) {\n    numbers.push(toNum(char));\n  }\n\n  return numbers;\n}\n\nfunction sum(charNums) {\n  return charNums.reduce(\n    (sumOfNums, charNum) => sumOfNums + Number(charNum),\n    0\n  );\n}\n\nfunction getLucky(s, k) {\n  let numbers = getNumbers(s);\n  let digits = numbers.join('').split('');\n\n  for (let index = 1; index <= k; index++) {\n    digits = sum(digits).toString().split('');\n  }\n\n  return Number(digits.join(''));\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sum-of-left-leaves/sum-of-left-leaves.js",
    "content": "function sumOfLeftLeaves(root, isLeft = false) {\n  if (!root) return 0;\n  if (!root.left && !root.right && isLeft) return root.val;\n  return sumOfLeftLeaves(root.left, true) + sumOfLeftLeaves(root.right, false);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sum-of-squares-of-special-elements/sum-of-squares-of-special-elements.js",
    "content": "// https://leetcode.com/problems/sum-of-squares-of-special-elements\n\nfunction sumOfSquares(nums) {\n  let sum = 0;\n\n  for (let i = 1; i <= nums.length; i++) {\n    if (nums.length % i === 0) {\n      sum += nums[i - 1] * nums[i - 1];\n    }\n  }\n\n  return sum;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sum-of-values-at-indices-with-k-set-bits/sum-of-values-at-indices-with-k-set-bits.js",
    "content": "function toBinary(num) {\n  if (num === 0) return '0';\n\n  let binary = [];\n\n  while (num > 0) {\n    binary.unshift(num % 2);\n    num = Math.floor(num / 2);\n  }\n\n  return binary.join('');\n}\n\nfunction checkSetBits(binary, k) {\n  let countSetBits = 0;\n\n  for (let digit of binary) {\n    if (digit === '1') countSetBits++;\n  }\n\n  return countSetBits === k;\n}\n\nfunction sumIndicesWithKSetBits(nums, k) {\n  let sum = 0;\n\n  for (let index = 0; index < nums.length; index++) {\n    let binary = toBinary(index);\n    console.log(index, binary);\n    let matchesKSetBits = checkSetBits(binary, k);\n    if (matchesKSetBits) {\n      sum += nums[index];\n    }\n  }\n\n  return sum;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sum_leaf_binary_numbers/sum_leaf_binary_numbers.py",
    "content": "# https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers\n\ntotal_binary_sum = 0\n\ndef sum_root_to_leaf(root):\n    if root is None: return\n    helper(root, str(root.val))\n    return total_binary_sum\n    \ndef helper(node, path):\n    if node.left:\n        helper(node.left, path + str(node.left.val))\n        \n    if node.right:\n        helper(node.right, path + str(node.right.val))\n\n    if node.right is None and node.left is None:\n        total_binary_sum += int(path, 2)\n\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sum_of_all_odd_length_subarrays/sum_of_all_odd_length_subarrays.py",
    "content": "# https://leetcode.com/problems/sum-of-all-odd-length-subarrays\n\n'''\nTime complexity: O(O*A*S) or O(N^3) to simplify, where O = number of odd numbers, A = length of arr, and S = sum of the subarrays\nSpace complexity: O(1)\n'''\n\ndef sum_odd_length_subarrays(arr):\n    odd, sum_of_subarrays = 1, 0\n    \n    while (odd <= len(arr)):\n        for index in range(0, len(arr) - odd + 1):\n            sum_of_subarrays += sum(arr[index:index+odd])\n            \n        odd += 2\n            \n    return sum_of_subarrays\n\n'''\nTime complexity: O(N)\nSpace complexity: O(1)\n'''\n\ndef sum_odd_length_subarrays_optimized(A):\n    sum_of_subarrays, length_of_A = 0, len(A)\n\n    for index, num in enumerate(A):\n        sum_of_subarrays += ((index + 1) * (length_of_A - index) + 1) // 2 * num\n\n    return sum_odd_length_subarrays\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/sum_of_unique_elements/sum_of_unique_elements.py",
    "content": "# https://leetcode.com/problems/sum-of-unique-elements\n\n\ndef sum_of_unique(nums):\n    mapper = {}\n    \n    for num in nums:\n        if num in mapper:\n            mapper[num] += 1\n        else:\n            mapper[num] = 1\n            \n    sum_of_unique_nums = 0\n            \n    for key in mapper:\n        if mapper[key] == 1:\n            sum_of_unique_nums += key\n            \n    return sum_of_unique_nums"
  },
  {
    "path": "coding_interviews/leetcode/easy/sum_zero/sum_zero.py",
    "content": "def sum_zero(n):\n    zero_sum_array = []\n    counter = 1\n\n    if n % 2 != 0:\n        zero_sum_array.append(0)\n        n -= 1\n\n    while n:\n        zero_sum_array.append(counter)\n        zero_sum_array.append(-counter)\n        counter += 1\n        n -= 2\n\n    return zero_sum_array\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/symmetric-tree/symmetric-tree.js",
    "content": "function symmetricNodes(node1, node2) {\n  if ((!node1 && node2) || (node1 && !node2)) {\n    return false;\n  }\n\n  if (!node1 && !node2) {\n    return true;\n  }\n\n  return (\n    node1.val === node2.val &&\n    symmetricNodes(node1.left, node2.right) &&\n    symmetricNodes(node1.right, node2.left)\n  );\n}\n\nfunction isSymmetric(root) {\n  if (!root) {\n    return true;\n  }\n\n  return symmetricNodes(root.left, root.right);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/take-gifts-from-the-richest-pile/take-gifts-from-the-richest-pile.js",
    "content": "function pickGifts(gifts, k) {\n  while (k--) {\n    let maxIndex = -Infinity;\n    let max = -Infinity;\n\n    for (let index = 0; index < gifts.length; index++) {\n      if (gifts[index] > max) {\n        maxIndex = index;\n        max = gifts[index];\n      }\n    }\n\n    gifts[maxIndex] = Math.floor(Math.sqrt(gifts[maxIndex]));\n  }\n\n  return gifts.reduce((sum, gift) => sum + gift, 0);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/three-consecutive-odds/three-consecutive-odds.js",
    "content": "function threeConsecutiveOdds(nums) {\n  let counter = 0;\n\n  for (let num of nums) {\n    if (num % 2 === 0) counter = 0;\n    else counter++;\n    if (counter >= 3) return true;\n  }\n\n  return false;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/time-needed-to-buy-tickets/time-needed-to-buy-tickets.js",
    "content": "function timeRequiredToBuy(tickets, k) {\n  let count = 0;\n  let pointer = 0;\n\n  while (tickets[k]) {\n    if (tickets[pointer]) {\n      tickets[pointer]--;\n      count++;\n    }\n\n    pointer = (pointer + 1) % tickets.length;\n  }\n\n  return count;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/to_lower_case/to_lower_case.py",
    "content": "# https://leetcode.com/problems/to-lower-case/\n\n'''\nImplement function ToLowerCase() that has a string parameter str,\nand returns the same string in lowercase.\n\nExample 1:\nInput: \"Hello\"\nOutput: \"hello\"\n\nExample 2:\nInput: \"here\"\nOutput: \"here\"\n\nExample 3:\nInput: \"LOVELY\"\nOutput: \"lovely\"\n'''\n\n\ndef lower_case_char(char):\n    if ord(char) >= 65 and ord(char) <= 90:\n        return chr(ord(char) + 32)\n\n    return char\n\n\ndef lower_case(str):\n    list_of_chars = []\n\n    for char in str:\n        list_of_chars.append(lower_case_char(char))\n\n    return ''.join(list_of_chars)\n\n\ndata_tests = [\n    ('Hello', 'hello'),\n    ('here', 'here'),\n    ('LOVELY', 'lovely'),\n    ('al&phaBET', 'al&phabet')\n]\n\nfor string, expected in data_tests:\n    result = lower_case(string)\n    print(result, expected == result)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/toeplitz-matrix/toeplitz-matrix.js",
    "content": "function isDiagonalToeplitz(matrix, value, row, col) {\n  if (row >= matrix.length || col >= matrix[row].length) return true;\n  if (value !== matrix[row][col]) return false;\n  return isDiagonalToeplitz(matrix, matrix[row][col], row + 1, col + 1);\n}\n\nfunction isToeplitzMatrix(matrix) {\n  for (let row = 0; row < matrix.length - 1; row++) {\n    for (let col = 0; col < matrix[row].length - 1; col++) {\n      if (!isDiagonalToeplitz(matrix, matrix[row][col], row + 1, col + 1))\n        return false;\n    }\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/transpose-matrix/transpose-matrix.js",
    "content": "function transpose(matrix) {\n  let newMatrix = [];\n\n  for (let col = 0; col < matrix[0].length; col++) {\n    let newRow = [];\n\n    for (let row = 0; row < matrix.length; row++) {\n      newRow.push(matrix[row][col]);\n    }\n\n    newMatrix.push(newRow);\n  }\n\n  return newMatrix;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/truncate_sentence/truncate_sentence.py",
    "content": "# https://leetcode.com/problems/truncate-sentence\n\ndef truncate_sentence(s, k):\n    start_index, end_index, words = 0, 0, []\n\n    for index, char in enumerate(s):\n        end_index = index\n\n        if char == ' ':\n            words.append(s[start_index:end_index])\n            start_index = index + 1\n            \n    words.append(s[start_index:])\n    \n    truncated_words = []\n    \n    for word in words[:k]:\n        truncated_words.append(word)\n\n    return ' '.join(truncated_words)\n\ndef truncate_sentence(s, k):\n    start_index, end_index, words = 0, 0, []\n        \n    for index, char in enumerate(s):\n        end_index = index\n\n        if char == ' ':\n            words.append(s[start_index:end_index])\n            start_index = index + 1\n            \n    words.append(s[start_index:])\n    \n    return ' '.join(words[:k])\n\ndef truncate_sentence(s, k):\n    return ' '.join(s.split(' ')[0:k])\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/two-furthest-houses-with-different-colors/two-furthest-houses-with-different-colors.js",
    "content": "function maxDistance(colors) {\n  let startPointer = 0;\n  let endPointer = colors.length - 1;\n  let maximumDistance = -Infinity;\n\n  while (endPointer > startPointer) {\n    if (colors[startPointer] !== colors[endPointer]) {\n      maximumDistance = endPointer - startPointer;\n      break;\n    }\n\n    endPointer--;\n  }\n\n  endPointer = colors.length - 1;\n\n  while (startPointer < endPointer) {\n    if (\n      colors[startPointer] !== colors[endPointer] &&\n      endPointer - startPointer > maximumDistance\n    ) {\n      maximumDistance = endPointer - startPointer;\n      break;\n    }\n\n    startPointer++;\n  }\n\n  return maximumDistance;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/two-out-of-three/two-out-of-three.js",
    "content": "function buildHashmap(nums) {\n  let hashmap = new Map();\n\n  for (let num of nums) {\n    hashmap.set(num, true);\n  }\n\n  return hashmap;\n}\n\nfunction checkAndAddNumbers(result, hashmap1, hashmap2, hashmap3) {\n  hashmap1.forEach((_, num) => {\n    if (hashmap2.has(num) || hashmap3.has(num)) {\n      result.add(num);\n    }\n  });\n}\n\nfunction twoOutOfThree(nums1, nums2, nums3) {\n  let hashmap1 = buildHashmap(nums1);\n  let hashmap2 = buildHashmap(nums2);\n  let hashmap3 = buildHashmap(nums3);\n  let result = new Set();\n\n  checkAndAddNumbers(result, hashmap1, hashmap2, hashmap3);\n  checkAndAddNumbers(result, hashmap2, hashmap1, hashmap3);\n  checkAndAddNumbers(result, hashmap3, hashmap2, hashmap1);\n\n  return [...result];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/two-sum/two-sum.js",
    "content": "function twoSum(nums, target) {\n  let numbersMap = {};\n\n  for (let [index, num] of nums.entries()) {\n    numbersMap[num] = index;\n  }\n\n  for (let [index, num] of nums.entries()) {\n    let remainder = target - num;\n    let remainderIndex = numbersMap[remainder];\n\n    if (remainderIndex && index !== remainderIndex) {\n      return [index, remainderIndex];\n    }\n  }\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/two-sum-iv-input-is-a-bst/two-sum-iv-input-is-a-bst.js",
    "content": "function dfs(node, hashmap, values) {\n  if (!node) {\n    return node;\n  }\n\n  hashmap[node.val] = true;\n  values.push(node.val);\n\n  dfs(node.left, hashmap, values);\n  dfs(node.right, hashmap, values);\n}\n\nfunction findTarget(root, k) {\n  let hashmap = {};\n  let values = [];\n\n  dfs(root, hashmap, values);\n\n  for (let value of values) {\n    if (hashmap[k - value] && k - value !== value) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\n// second try with better memory usage\n\nfunction dfs2(node, target, hashmap) {\n  if (!node) {\n    return false;\n  }\n\n  if (hashmap[target - node.val]) {\n    return true;\n  }\n\n  hashmap[node.val] = true;\n\n  return dfs2(node.left, target, hashmap) || dfs2(node.right, target, hashmap);\n}\n\nfunction findTarget2(root, k) {\n  return dfs2(root, k, {});\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/two_sum.py",
    "content": "# https://leetcode.com/problems/two-sum/description/\n\ndef two_sum(nums, target):\n    for i in range(len(nums)):\n        for j in range(i+1, len(nums)):\n            if nums[i] + nums[j] == target:\n                return [i, j]\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/uncommon-words-from-two-sentences/uncommon-words-from-two-sentences.js",
    "content": "function buildCounter(sentence) {\n  let counter = new Map();\n\n  for (let word of sentence) {\n    if (counter.has(word)) counter.set(word, counter.get(word) + 1);\n    else counter.set(word, 1);\n  }\n\n  return counter;\n}\n\nfunction getOnceWords(counter) {\n  const onceWords = [];\n\n  for (let [word, count] of counter) {\n    if (count === 1) onceWords.push(word);\n  }\n\n  return onceWords;\n}\n\nfunction getUncommonWords(onceWords, map) {\n  return onceWords.filter((onceWord) => !map.has(onceWord));\n}\n\nfunction uncommonFromSentences(s1, s2) {\n  const list1 = s1.split(' ');\n  const list2 = s2.split(' ');\n  const counter1 = buildCounter(list1);\n  const counter2 = buildCounter(list2);\n  const onceWords1 = getOnceWords(counter1);\n  const onceWords2 = getOnceWords(counter2);\n\n  return [\n    ...getUncommonWords(onceWords1, counter2),\n    ...getUncommonWords(onceWords2, counter1),\n  ];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/unique-number-of-occurrences/unique-number-of-occurrences.js",
    "content": "function uniqueOccurrences(arr) {\n  const hashmap = new Map();\n\n  for (let num of arr) {\n    if (hashmap.has(num)) {\n      hashmap.set(num, hashmap.get(num) + 1);\n    } else {\n      hashmap.set(num, 1);\n    }\n  }\n\n  const counts = [];\n\n  hashmap.forEach((count, num) => {\n    counts.push(count);\n  });\n\n  return counts.length === new Set(counts).size;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/unique_morse_code_words.py",
    "content": "# https://leetcode.com/problems/unique-morse-code-words/description/\n\n# \"gin\" -> \"--...-.\"\n# \"zen\" -> \"--...-.\"\n# \"gig\" -> \"--...--.\"\n# \"msg\" -> \"--...--.\"\n\ndef unique_morse_representations(words):\n    morse = [\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"]\n    alphabet = 'abcdefghijklmnopqrstuvwxyz'\n\n    morse_code_mapper = {}\n\n    for index, letter in enumerate(alphabet):\n        morse_code_mapper[letter] = morse[index]\n\n    unique_codes = set()\n\n    for word in words:\n        code = ''\n\n        for letter in word:\n            code += morse_code_mapper[letter]\n\n        unique_codes.add(code)\n\n    return len(unique_codes)\n\nprint(unique_morse_representations([\"gin\", \"zen\", \"gig\", \"msg\"]) == 2)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/unique_number_of_occurrences/unique_number_of_occurrences.py",
    "content": "# https://leetcode.com/problems/unique-number-of-occurrences\n\ndef unique_occurrences(arr):\n    num_to_occurrences = {}\n    \n    for num in arr:\n        if num in num_to_occurrences:\n            num_to_occurrences[num] += 1\n        else:\n            num_to_occurrences[num] = 1\n\n    return len(num_to_occurrences) == len(set(num_to_occurrences.values()))\n\nfrom collections import Counter\n\ndef unique_occurrences_2(arr):\n    num_to_occurrences = Counter(arr)\n    return len(num_to_occurrences) == len(set(num_to_occurrences.values()))\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/univalued-binary-tree/univalued-binary-tree.js",
    "content": "function isUnivalTree(root) {\n  if (!root) return true;\n\n  const leftResult = isUnivalTree(root.left);\n  const rightResult = isUnivalTree(root.right);\n\n  let result = true;\n\n  result = root.left ? root.val === root.left.val : result;\n  result = root.right ? result && root.val === root.right.val : result;\n\n  return result && leftResult && rightResult;\n}\n\nfunction isUnivalTree(root, value = root.val) {\n  if (!root) return true;\n  return (\n    root.val === value &&\n    isUnivalTree(root.left, value) &&\n    isUnivalTree(root.right, value)\n  );\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/valid-anagram/valid-anagram.js",
    "content": "function isAnagram(s, t) {\n  if (s.length !== t.length) {\n    return false;\n  }\n\n  let charCount = {};\n\n  for (let index = 0; index < s.length; index++) {\n    let char = s[index];\n\n    if (charCount[char]) {\n      charCount[char]++;\n    } else {\n      charCount[char] = 1;\n    }\n  }\n\n  for (let char of t) {\n    if (charCount[char]) {\n      charCount[char]--;\n    } else {\n      return false;\n    }\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/valid-palindrome/valid-palindrome-2.js",
    "content": "function isPalindrome(s) {\n  let string = s.toLowerCase().replace(/[^a-z0-9]/gi, '');\n  let start = 0;\n  let end = string.length - 1;\n\n  while (start <= end) {\n    if (string[start] !== string[end]) {\n      return false;\n    }\n\n    start++;\n    end--;\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/valid-palindrome/valid-palindrome.js",
    "content": "const alphanumeric = 'abcdefghijklmnopqrstuvwxyz0123456789';\n\nfunction downcase(string) {\n  return string.toLowerCase();\n}\n\nfunction keepAlphanumeric(string) {\n  let alphanumericOnlyString = [];\n\n  for (let char of string) {\n    if (alphanumeric.includes(char)) {\n      alphanumericOnlyString.push(char);\n    }\n  }\n\n  return alphanumericOnlyString.join('');\n}\n\nfunction isValidPalindrome(string) {\n  let start = 0;\n  let end = string.length - 1;\n\n  while (start <= end) {\n    if (string[start] !== string[end]) {\n      return false;\n    }\n\n    start++;\n    end--;\n  }\n\n  return true;\n}\n\nfunction isPalindrome(string) {\n  return isValidPalindrome(keepAlphanumeric(downcase(string)));\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/valid-palindrome/valid_palindrome.py",
    "content": "'''\nGiven a string, determine whether its palindrome if you are allowed to delete at most one character\n\nExample\n\"aba\" - True\n\"abca\" - True\n\"abccadsfa\" - False\n\"\" - True\n\n\"abca\" 0 => \"bca\"\n\"abca\" 1 => \"aca\"\n'''\n\n# Brute force\n\n\ndef is_palindrome(string):\n    return string == string[::-1]\n\n\ndef build_new_string_variation(string, index):\n    return string[:index] + string[index+1:]\n\n\ndef valid_palindrome(string):\n    if string == '':\n        return True\n\n    if is_palindrome(string):\n        return True\n\n    for index in range(len(string)):\n        new_string = build_new_string_variation(string, index)\n        if is_palindrome(new_string):\n            return True\n\n    return False\n\n\ndata = [\n    (\"aba\", True),\n    (\"abca\", True),\n    (\"abccadsfa\", False),\n    (\"\", True)\n]\n\nfor string, expected in data:\n    result = valid_palindrome(string)\n    print(result == expected)\n\n\n# Greedy Solution: find if it is not palindrome\ndef valid_palindrome_2(string):\n    if string == '':\n        return True\n\n    if is_palindrome(string):\n        return True\n\n    for i in range(len(string) // 2):\n        last_current_index = len(string) - 1 - i\n\n        if string[i] != string[last_current_index]:\n            string_shifted_to_left = string[i:last_current_index]\n            string_shifted_to_right = string[i + 1:last_current_index + 1]\n            return is_palindrome(string_shifted_to_left) or is_palindrome(string_shifted_to_right)\n\n    return True\n\n\ndata = [\n    (\"aba\", True),\n    (\"abc\", False),\n    (\"abca\", True),\n    (\"abccadsfa\", False),\n    (\"\", True)\n]\n\nfor string, expected in data:\n    result = valid_palindrome_2(string)\n    print(result == expected)\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/valid-parentheses/valid-parentheses.js",
    "content": "function matches(openBracket, closingBracket) {\n  return (\n    {\n      '}': '{',\n      ']': '[',\n      ')': '(',\n    }[closingBracket] === openBracket\n  );\n}\n\nfunction isValid(s) {\n  if (s.length === 1) {\n    return false;\n  }\n\n  const stack = [];\n\n  for (let char of s) {\n    if (['(', '{', '['].includes(char)) {\n      stack.push(char);\n    } else {\n      let top = stack.pop();\n\n      if (!matches(top, char)) {\n        return false;\n      }\n    }\n  }\n\n  return stack.length === 0;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/water-bottles/water-bottles.js",
    "content": "function numWaterBottles(numBottles, numExchange) {\n  let drinkNum = numBottles;\n\n  while (numBottles >= numExchange) {\n    let remainingBottles = numBottles % numExchange;\n    let newBottles = Math.floor(numBottles / numExchange);\n    drinkNum += newBottles;\n    numBottles = remainingBottles + newBottles;\n  }\n\n  return drinkNum;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/easy/weakest_rows/weakest_rows.py",
    "content": "# https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix\n\ndef k_weakest_rows(mat, k):\n    sum_index_list = [[sum(row), index] for index, row in enumerate(mat)]\n    return [sum_index[1] for sum_index in sorted(sum_index_list)][:k]"
  },
  {
    "path": "coding_interviews/leetcode/easy/xor-operation-in-an-array/xor-operation-in-an-array.js",
    "content": "function xorOperation(n, start) {\n  let result = start;\n  let number = start;\n\n  for (let num = 1; num < n; num++) {\n    number += 2;\n    result ^= number;\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/3sum/3sum-tle.js",
    "content": "function sortTriplet(num1, num2, num3) {\n  return [num1, num2, num3].sort((n1, n2) => n1 - n2);\n}\n\nfunction getSortedTripletString(num1, num2, num3) {\n  let triplet = sortTriplet(num1, num2, num3);\n  return `${triplet[0]}*${triplet[1]}*${triplet[2]}`;\n}\n\nfunction threeSum(nums) {\n  if (nums.length < 3) {\n    return [];\n  }\n\n  let triplets = [];\n  let numberCount = {};\n  let usedTriplets = {};\n  let usedPairs = {};\n\n  for (let num of nums) {\n    if (numberCount[num]) {\n      numberCount[num]++;\n    } else {\n      numberCount[num] = 1;\n    }\n  }\n\n  for (let i = 0; i < nums.length - 1; i++) {\n    for (let j = i + 1; j < nums.length; j++) {\n      let num1 = nums[i];\n      let num2 = nums[j];\n      let pairSum = num1 + num2;\n      let missingTriplet = pairSum * -1;\n      let sortedPairString = `${Math.min(num1, num2)}*${Math.max(num1, num2)}`;\n\n      if (usedPairs[sortedPairString]) {\n        continue;\n      }\n\n      let sortedTripletString = getSortedTripletString(\n        num1,\n        num2,\n        missingTriplet\n      );\n\n      if (usedTriplets[sortedTripletString]) {\n        continue;\n      }\n\n      if (\n        (missingTriplet === num1 &&\n          missingTriplet === num2 &&\n          numberCount[missingTriplet] &&\n          numberCount[missingTriplet] >= 3) ||\n        (((missingTriplet === num1 && missingTriplet !== num2) ||\n          (missingTriplet !== num1 && missingTriplet === num2)) &&\n          numberCount[missingTriplet] &&\n          numberCount[missingTriplet] >= 2) ||\n        (missingTriplet !== num1 &&\n          missingTriplet !== num2 &&\n          numberCount[missingTriplet])\n      ) {\n        triplets.push([num1, num2, missingTriplet]);\n        usedTriplets[sortedTripletString] = true;\n        usedPairs[sortedPairString] = true;\n        continue;\n      }\n    }\n  }\n\n  return triplets;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/add_two_numbers/add_two_numbers.py",
    "content": "# https://leetcode.com/problems/add-two-numbers/description/\n\n'''\n(1, 2, 3) + (2, 3, 4) = (3, 5, 7)\n(1, 2, 3) + (2, 9, 4) = (3, 1, 8)\n'''\n\nclass ListNode(object):\n    def __init__(self, x):\n        self.val = x\n        self.next = None\n\ndef add_two_numbers(l1, l2):\n    carry = False\n    result_list = r_list = ListNode(0)\n\n    while l1 or l2 or carry:\n        if l1 and l2:\n            value = l1.val + l2.val\n            l1 = l1.next\n            l2 = l2.next\n        elif l1:\n            value = l1.val\n            l1 = l1.next\n        elif l2:\n            value = l2.val\n            l2 = l2.next\n        else:\n            value = 0\n\n        if carry:\n            value += 1\n            carry = False\n\n        if value >= 10:\n            value -= 10\n            carry = True\n\n        r_list.next = ListNode(value)\n        r_list = r_list.next\n\n    return result_list.next\n\n# Test 1:\n\nl1 = ListNode(1)\nl1.next = ListNode(2)\nl = l1.next\nl.next = ListNode(3)\n\nl2 = ListNode(2)\nl2.next = ListNode(9)\nl = l2.next\nl.next = ListNode(4)\n\nresult_list = add_two_numbers(l1, l2)\n\nwhile result_list:\n    print result_list.val\n    result_list = result_list.next\n\nprint \"--------------------\"\n\n# Test 2:\n\nl1 = ListNode(5)\nl2 = ListNode(5)\n\nresult_list = add_two_numbers(l1, l2)\n\nwhile result_list:\n    print result_list.val\n    result_list = result_list.next\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/all_elements_in_two_binary_search_trees/all_elements_in_two_binary_search_trees.py",
    "content": "# https://leetcode.com/problems/all-elements-in-two-binary-search-trees\n\n\ndef get_all_elements(root1, root2):\n    values = []\n    get_sorted_list(root1, values)\n    get_sorted_list(root2, values)\n    return sorted(values)\n\n\ndef get_sorted_list(node, values):\n    if node.left:\n        get_sorted_list(node.left, values)\n\n    values.append(node.val)\n\n    if node.right:\n        get_sorted_list(node.right, values)\n\n# ---------------------------------------------------------------------\n\ndef get_sorted_elements_from(node):\n    if not node:\n        return []\n    \n    elements = []\n    \n    if node.left:\n        elements = get_sorted_elements_from(node.left)\n    \n    elements.append(node.val)\n    \n    if node.right:\n        elements += get_sorted_elements_from(node.right)\n        \n    return elements\n    \n\ndef get_all_elements(root1, root2):\n    sorted_tree_1 = get_sorted_elements_from(root1)\n    sorted_tree_2 = get_sorted_elements_from(root2)\n    \n    index_1, index_2 = 0, 0\n    result = []\n    \n    while index_1 < len(sorted_tree_1) and index_2 < len(sorted_tree_2):\n        value1 = sorted_tree_1[index_1]\n        value2 = sorted_tree_2[index_2]\n        \n        if value1 <= value2:\n            result.append(value1)\n            index_1 += 1\n        else:\n            result.append(value2)\n            index_2 += 1\n            \n    if index_1 < len(sorted_tree_1):\n        result += sorted_tree_1[index_1:]\n        \n    if index_2 < len(sorted_tree_2):\n        result += sorted_tree_2[index_2:]\n        \n    return result\n\n# ---------------------------------------------------------------------\n\ndef get_sorted_elements_from(node, elements):\n    if not node: return []\n    if node.left: get_sorted_elements_from(node.left, elements)\n    elements.append(node.val)\n    if node.right: get_sorted_elements_from(node.right, elements)    \n\ndef get_all_elements(root1, root2):\n    sorted_tree_1 = []\n    get_sorted_elements_from(root1, sorted_tree_1)\n    \n    sorted_tree_2 = []\n    get_sorted_elements_from(root2, sorted_tree_2)\n    \n    index_1, index_2 = 0, 0\n    result = []\n    \n    while index_1 < len(sorted_tree_1) and index_2 < len(sorted_tree_2):\n        value1 = sorted_tree_1[index_1]\n        value2 = sorted_tree_2[index_2]\n        \n        if value1 <= value2:\n            result.append(value1)\n            index_1 += 1\n        else:\n            result.append(value2)\n            index_2 += 1\n            \n    if index_1 < len(sorted_tree_1):\n        result += sorted_tree_1[index_1:]\n        \n    if index_2 < len(sorted_tree_2):\n        result += sorted_tree_2[index_2:]\n        \n    return result"
  },
  {
    "path": "coding_interviews/leetcode/medium/arithmetic-subarrays/arithmetic-subarrays.py",
    "content": "# https://leetcode.com/problems/arithmetic-subarrays\n\ndef check_arithmetic_subarrays(nums, l, r):\n    answer = []\n\n    for index in range(len(l)):\n        l_value = l[index]\n        r_value = r[index]\n        nums_range = sorted(nums[l_value:r_value+1])\n        is_arithmetic = True\n        diff = nums_range[1] - nums_range[0]\n        \n        for i in range(2, len(nums_range)):\n            if diff != nums_range[i] - nums_range[i-1]:\n                is_arithmetic = False\n                break\n\n        answer.append(is_arithmetic)\n        \n    return answer\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/balance-a-binary-search-tree/balance-a-binary-search-tree.js",
    "content": "function inorder(root, nodes) {\n  if (root.left) inorder(root.left, nodes);\n  nodes.push(root.val);\n  if (root.right) inorder(root.right, nodes);\n}\n\nfunction toBST(start, end, nodes) {\n  if (start > end) return null;\n\n  const middle = Math.floor((start + end) / 2);\n  const bst = new TreeNode(nodes[middle]);\n\n  bst.left = toBST(start, middle - 1, nodes);\n  bst.right = toBST(middle + 1, end, nodes);\n\n  return bst;\n}\n\nfunction balanceBST(root) {\n  const nodes = [];\n  inorder(root, nodes);\n  return toBST(0, nodes.length - 1, nodes);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/binary-tree-inorder-traversal/binary-tree-inorder-traversal.py",
    "content": "# https://leetcode.com/problems/binary-tree-inorder-traversal\n\nclass Solution:\n    def __init__(self):\n        self.inorder_list = []\n\n    def inorder_traversal(self, root):\n        if root:\n            self.inorder_traversal(root.left)\n            self.inorder_list.append(root.val)\n            self.inorder_traversal(root.right)\n\n        return self.inorder_list"
  },
  {
    "path": "coding_interviews/leetcode/medium/binary-tree-level-order-traversal/binary-tree-level-order-traversal.js",
    "content": "function levelOrder(root) {\n  if (!root) {\n    return [];\n  }\n\n  let queue = [root];\n  let levelOrderTree = [];\n\n  while (queue.length) {\n    let levelNodes = [];\n    let levels = queue.length;\n\n    for (let level = 0; level < levels; level++) {\n      let node = queue.shift();\n\n      if (node.left) {\n        queue.push(node.left);\n      }\n\n      if (node.right) {\n        queue.push(node.right);\n      }\n\n      levelNodes.push(node.val);\n    }\n\n    levelOrderTree.push(levelNodes);\n  }\n\n  return levelOrderTree;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/bst_from_pre_order_traversal/bst_from_pre_order_traversal.py",
    "content": "class TreeNode:\n    def __init__(self, val=0, left=None, right=None):\n        self.val = val\n        self.left = left\n        self.right = right\n\n\ndef bst_from_preorder(preorder):\n    root = TreeNode(preorder[0])\n\n    for value in preorder[1:]:\n        helper(root, value)\n\n    return root\n\n\ndef helper(node, value):\n    if value < node.val and node.left:\n        helper(node.left, value)\n    elif value < node.val:\n        node.left = TreeNode(value)\n\n    if value > node.val and node.right:\n        helper(node.right, value)\n    elif value > node.val:\n        node.right = TreeNode(value)\n\n    return node\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/bst_to_greatest/bst_to_greatest.py",
    "content": "def sum_and_list(node, total, values):\n    left_total = 0\n    right_total = 0\n    left_values = []\n    right_values = []\n\n    if node.left:\n        [left_total, left_values] = sum_and_list(node.left, total, values)\n\n    if node.right:\n        [right_total, right_values] = sum_and_list(node.right, total, values)\n\n    return [\n        total + left_total + node.val + right_total,\n        values + left_values + [node.val] + right_values\n    ]\n\n\ndef modify_helper(node, mapper):\n    if node.left:\n        modify_helper(node.left, mapper)\n\n    if node.right:\n        modify_helper(node.right, mapper)\n\n    node.val = mapper[node.val]\n    return node\n\n\ndef bst_to_gst(root):\n    [total, values] = sum_and_list(root, 0, [])\n\n    smaller_total = 0\n    mapper = {}\n\n    for value in values:\n        mapper[value] = total - smaller_total\n        smaller_total += value\n\n    return modify_helper(root, mapper)\n\n\nvalue = 0\n\n\ndef bst_to_gst(node):\n    if node.right:\n        bst_to_gst(node.right)\n\n    node.val = node.val + value\n    value = node.val\n\n    if node.left:\n        bst_to_gst(node.left)\n\n    return node\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/clone-graph/clone-graph.js",
    "content": "/*\nCloning a graph using a Breadth-First Search\n— build a queue of all nodes in the graph\n— build a hashmap of all cloned nodes\n— if it's on the map: it's counted as visited & add to the neighbors' list \n— else create from scratch\n*/\n\nfunction cloneGraph(node) {\n  if (!node) return;\n\n  let clonedGraph = new Node(node.val);\n  let queue = [node];\n  let createdNodes = {\n    1: clonedGraph,\n  };\n\n  while (queue.length) {\n    let currentNode = queue.shift();\n    let clonedNode = createdNodes[currentNode.val];\n\n    for (let neighbor of currentNode.neighbors) {\n      if (createdNodes[neighbor.val]) {\n        clonedNode.neighbors.push(createdNodes[neighbor.val]);\n      } else {\n        let createdNode = new Node(neighbor.val);\n        createdNodes[neighbor.val] = createdNode;\n        clonedNode.neighbors.push(createdNode);\n        queue.push(neighbor);\n      }\n    }\n  }\n\n  return clonedGraph;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/cloned_binary_tree/cloned_binary_tree.py",
    "content": "# https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/\n\n\ndef get_target_copy(original, cloned, target):\n    if cloned.val == target.val:\n        return cloned\n\n    if cloned.left:\n        result = get_target_copy(original.left, cloned.left, target)\n\n        if result:\n            return result\n\n    if cloned.right:\n        result = get_target_copy(original.right, cloned.right, target)\n\n        if result:\n            return result\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/count-nodes-equal-to-average-of-subtree/count-nodes-equal-to-average-of-subtree.js",
    "content": "function calculateAverage(totalValue, nodesCount) {\n  return Math.floor(totalValue / nodesCount);\n}\n\nfunction averageHelper(node, count) {\n  if (!node) {\n    return { totalValue: 0, nodesCount: 0, equalToAverageCount: 0 };\n  }\n\n  const left = averageHelper(node.left, 1);\n  const right = averageHelper(node.right, 1);\n\n  const totalValue = node.val + left.totalValue + right.totalValue;\n  const nodesCount = count + left.nodesCount + right.nodesCount;\n\n  const average = calculateAverage(totalValue, nodesCount);\n\n  const equalToAverageCount =\n    (average === node.val ? 1 : 0) +\n    left.equalToAverageCount +\n    right.equalToAverageCount;\n\n  return {\n    totalValue,\n    nodesCount,\n    equalToAverageCount,\n  };\n}\n\nfunction averageOfSubtree(root) {\n  let totalValue = root.val;\n  let nodesCount = 1;\n\n  const left = averageHelper(root.left, nodesCount);\n  const right = averageHelper(root.right, nodesCount);\n\n  const average = calculateAverage(\n    totalValue + left.totalValue + right.totalValue,\n    nodesCount + left.nodesCount + right.nodesCount\n  );\n\n  return (\n    (average === root.val ? 1 : 0) +\n    left.equalToAverageCount +\n    right.equalToAverageCount\n  );\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/count-number-of-distinct-integers-after-reverse-operations/count-number-of-distinct-integers-after-reverse-operations-numbers.js",
    "content": "// https://leetcode.com/problems/count-number-of-distinct-integers-after-reverse-operations\n\nfunction reverseDigits(num) {\n  let digits = 0;\n\n  while (num > 0) {\n    digits = digits * 10 + (num % 10);\n    num = Math.floor(num / 10);\n  }\n\n  return digits;\n}\n\nfunction countDistinctIntegers(nums) {\n  let set = new Set();\n  let N = nums.length;\n\n  for (let index = 0; index < N; index++) {\n    let num = nums[index];\n    set.add(num);\n    let reversedDigitsNum = reverseDigits(num);\n    set.add(reversedDigitsNum);\n  }\n\n  return set.size;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/count-number-of-distinct-integers-after-reverse-operations/count-number-of-distinct-integers-after-reverse-operations.js",
    "content": "// https://leetcode.com/problems/count-number-of-distinct-integers-after-reverse-operations\n\nfunction reverseDigits(num) {\n  let digits = [];\n\n  while (num > 0) {\n    digits.push((num % 10).toString());\n    num = Math.floor(num / 10);\n  }\n\n  return Number(digits.join(''));\n}\n\nfunction countDistinctIntegers(nums) {\n  let set = new Set();\n  let N = nums.length;\n\n  for (let index = 0; index < N; index++) {\n    let num = nums[index];\n    set.add(num);\n    let reversedDigitsNum = reverseDigits(num);\n    set.add(reversedDigitsNum);\n  }\n\n  return set.size;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/count-sorted-vowel-strings/count-sorted-vowel-strings.js",
    "content": "function countVowelStrings(n) {\n  let a = 1,\n    e = 1,\n    i = 1,\n    o = 1,\n    u = 1;\n\n  for (let counter = 1; counter < n; counter++) {\n    o += u;\n    i += o;\n    e += i;\n    a += e;\n  }\n\n  return a + e + i + o + u;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/count-sub-islands/count-sub-islands-tle.js",
    "content": "/**\n- getting all islands in grid2\n  - store the rows and columns of each island\n  - this can be stored in a list\n    - e.g. [[[3,0]], [[4,1]], [2,1]]\n- iterate through the list of islands of grid2\n  - if all rows and cols from an island of grid2 match the cells in the grid1\n    - increment the number of sub-islands\n- return number of sub islands\n*/\nfunction isInsideTheGrid(grid, row, col) {\n  return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length;\n}\n\nfunction dfs(grid, row, col) {\n  if (!isInsideTheGrid(grid, row, col)) {\n    return [];\n  }\n\n  if (grid[row][col]) {\n    grid[row][col] = 0;\n\n    return [\n      [row, col],\n      ...dfs(grid, row - 1, col),\n      ...dfs(grid, row + 1, col),\n      ...dfs(grid, row, col - 1),\n      ...dfs(grid, row, col + 1),\n    ];\n  }\n\n  return [];\n}\n\nfunction countSubIslands(grid1, grid2) {\n  let islands = [];\n\n  for (let row = 0; row < grid2.length; row++) {\n    for (let col = 0; col < grid2[row].length; col++) {\n      let cell = grid2[row][col];\n\n      if (cell) {\n        grid2[row][col] = 0;\n\n        let island = [\n          [row, col],\n          ...dfs(grid2, row - 1, col),\n          ...dfs(grid2, row + 1, col),\n          ...dfs(grid2, row, col - 1),\n          ...dfs(grid2, row, col + 1),\n        ];\n\n        islands.push(island);\n      }\n    }\n  }\n\n  let numberOfSubIslands = 0;\n\n  for (let island of islands) {\n    let isSubIsland = true;\n\n    for (let [row, col] of island) {\n      if (grid1[row][col] === 0) {\n        isSubIsland = false;\n        break;\n      }\n    }\n\n    if (isSubIsland) {\n      numberOfSubIslands++;\n    }\n  }\n\n  return numberOfSubIslands;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/count-sub-islands/count-sub-islands.js",
    "content": "function dfs(grid1, grid2, row, col) {\n  if (\n    row < 0 ||\n    row >= grid2.length ||\n    col < 0 ||\n    col >= grid2[0].length ||\n    grid2[row][col] == 0\n  ) {\n    return 1;\n  }\n\n  grid2[row][col] = 0;\n\n  let numberOfSubIslands = 1;\n\n  numberOfSubIslands &= dfs(grid1, grid2, row - 1, col);\n  numberOfSubIslands &= dfs(grid1, grid2, row + 1, col);\n  numberOfSubIslands &= dfs(grid1, grid2, row, col - 1);\n  numberOfSubIslands &= dfs(grid1, grid2, row, col + 1);\n\n  return numberOfSubIslands & grid1[row][col];\n}\n\nfunction countSubIslands(grid1, grid2) {\n  let numberOfSubIslands = 0;\n\n  for (let row = 0; row < grid2.length; row++) {\n    for (let col = 0; col < grid2[row].length; col++) {\n      if (grid2[row][col]) {\n        numberOfSubIslands += dfs(grid1, grid2, row, col);\n      }\n    }\n  }\n\n  return numberOfSubIslands;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/count_points/count_points.py",
    "content": "# https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle\n\ndef is_point_within_circuference(qx, qy, qr, px, py):\n    return qr ** 2 >= abs(qx - px) ** 2 + abs(qy - py) ** 2\n\ndef count_points(points, queries):\n    answer = []\n    \n    for [qx, qy, qr] in queries:\n        count = 0\n        \n        for [px, py] in points:\n            if is_point_within_circuference(qx, qy, qr, px, py):\n                count += 1\n\n        answer.append(count)\n        \n    return answer\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/counter_number_of_teams/counter_number_of_teams.py",
    "content": "def num_teams(rating):\n    counter = 0\n\n    for i in range(len(rating) - 2):\n        for j in range(i + 1, len(rating) - 1):\n            for k in range(j + 1, len(rating)):\n                if (rating[i] < rating[j] and rating[j] < rating[k]) or (\n                        rating[i] > rating[j] and rating[j] > rating[k]):\n                    counter += 1\n\n    return counter\n\n\ndef num_teams(rating):\n    asc = desc = 0\n\n    for index, value in enumerate(rating):\n        llc = rgc = lgc = rlc = 0\n\n        for left in rating[:index]:\n            if left > value:\n                lgc += 1\n            if left < value:\n                llc += 1\n\n        for right in rating[index + 1:]:\n            if right > value:\n                rgc += 1\n            if right < value:\n                rlc += 1\n\n        asc += llc * rgc\n        desc += lgc * rlc\n\n    return asc + desc\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/deck_revealed_increasing/deck_revealed_increasing.py",
    "content": "# https://leetcode.com/problems/reveal-cards-in-increasing-order\n\nimport queue\n\ndef deck_revealed_increasing(deck):\n    q = queue.Queue()\n    sorted_deck = sorted(deck)\n    \n    for index in range(len(deck)): q.put(index)\n        \n    result = [0] * len(deck)\n    index = 0\n\n    while not q.empty():\n        result[q.get()] = sorted_deck[index]\n        index += 1\n        if not q.empty(): q.put(q.get())\n        \n    return result\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/decode-string/decode-string.js",
    "content": "const isNum = (char) => !isNaN(Number(char));\n\nexport function decodeString(encodedString) {\n  const stack = [];\n  let index = 0;\n\n  while (index < encodedString.length) {\n    const char = encodedString[index];\n\n    if (isNum(char)) {\n      const number = [];\n\n      while (isNum(encodedString[index])) {\n        number.push(encodedString[index]);\n        index++;\n      }\n\n      stack.push(Number(number.join('')));\n      continue;\n    }\n\n    if (char === ']') {\n      let str = '';\n\n      while (stack[stack.length - 1] !== '[') {\n        str = stack.pop() + str;\n      }\n\n      stack.pop();\n      stack.push(str.repeat(stack.pop()));\n      index++;\n      continue;\n    }\n\n    stack.push(char);\n    index++;\n  }\n\n  return stack.join('');\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/decode-string/tests/decode-string.test.js",
    "content": "import { describe, it, expect } from 'vitest';\nimport { decodeString } from '../decode-string';\n\ndescribe('decodeString', () => {\n  it('', () => {\n    expect(decodeString('3[a]2[bc]')).toEqual('aaabcbc');\n  });\n\n  it('', () => {\n    expect(decodeString('2[abc]3[cd]ef')).toEqual('abcabccdcdcdef');\n  });\n\n  it('', () => {\n    expect(decodeString('3[a2[c]]')).toEqual('accaccacc');\n  });\n\n  it('', () => {\n    expect(decodeString('100[leetcode]')).toEqual(\n      'leetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcode'\n    );\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/deepest_leaves_sum/deepest_leaves_sum.py",
    "content": "# https://leetcode.com/problems/deepest-leaves-sum\n\n'''\nGiven a binary tree, return the sum of values of its deepest leaves.\n\nInput: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]\nOutput: 15\n'''\n\n\ndef sum_deepest_leaves(root):\n    mapper = helper(root, {}, 1)\n    deepest_level = 1\n\n    for level in mapper:\n        if level > deepest_level:\n            deepest_level = level\n\n    deepest_level_nodes_values = mapper[deepest_level]\n\n    nodes_values_sum = 0\n\n    for node_value in deepest_level_nodes_values:\n        nodes_values_sum += node_value\n\n    return nodes_values_sum\n\n\ndef helper(node, mapper, level):\n    if level in mapper:\n        mapper[level] = mapper[level] + [node.val]\n    else:\n        mapper[level] = [node.val]\n\n    if node.left:\n        mapper = helper(node.left, mapper, level + 1)\n\n    if node.right:\n        mapper = helper(node.right, mapper, level + 1)\n\n    return mapper\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/delete-node-in-a-linked-list/better-delete-node-in-a-linked-list.js",
    "content": "// https://leetcode.com/problems/delete-node-in-a-linked-list\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n *     this.val = val;\n *     this.next = null;\n * }\n * @param {ListNode} node\n * @return {void} Do not return anything, modify node in-place instead.\n */\nfunction deleteNode(node) {\n  node.val = node.next.val;\n  node.next = node.next.next;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/delete-node-in-a-linked-list/delete-node-in-a-linked-list.js",
    "content": "// https://leetcode.com/problems/delete-node-in-a-linked-list\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n *     this.val = val;\n *     this.next = null;\n * }\n * @param {ListNode} node\n * @return {void} Do not return anything, modify node in-place instead.\n */\nfunction deleteNode(node) {\n  if (node.next && !node.next.next) {\n    node.val = node.next.val;\n    node.next = null;\n    return;\n  }\n\n  node.val = node.next.val;\n  deleteNode(node.next);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/design-a-stack-with-increment-operation/design-a-stack-with-increment-operation.js",
    "content": "export const CustomStack = function (maxSize) {\n  this.maxSize = maxSize;\n  this.items = [];\n};\n\nCustomStack.prototype.push = function (x) {\n  if (this.items.length < this.maxSize) {\n    this.items.push(x);\n  }\n};\n\nCustomStack.prototype.pop = function () {\n  return this.items.length > 0 ? this.items.pop() : -1;\n};\n\nCustomStack.prototype.increment = function (k, val) {\n  for (let i = 0; i < k; i++) {\n    if (i <= this.items.length - 1) this.items[i] += val;\n  }\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/design-a-stack-with-increment-operation/tests/design-a-stack-with-increment-operation.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { CustomStack } from '../design-a-stack-with-increment-operation';\n\ndescribe('CustomStack', () => {\n  it('', () => {\n    const customStack = new CustomStack(3);\n\n    customStack.push(1);\n    customStack.push(2);\n\n    expect(customStack.pop()).toEqual(2);\n\n    customStack.push(2);\n    customStack.push(3);\n    customStack.push(4);\n\n    customStack.increment(5, 100);\n    customStack.increment(2, 100);\n\n    expect(customStack.pop()).toEqual(103);\n    expect(customStack.pop()).toEqual(202);\n    expect(customStack.pop()).toEqual(201);\n    expect(customStack.pop()).toEqual(-1);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/design-add-and-search-words-data-structure/design-add-and-search-words-data-structure.js",
    "content": "function isTheSame(word, wordFromDict) {\n  if (word.length !== wordFromDict.length) return false;\n\n  for (let index = 0; index < word.length; index++) {\n    let wordChar = word[index];\n    let wordFromDictChar = wordFromDict[index];\n\n    if (wordChar === '.') {\n      continue;\n    }\n\n    if (wordChar !== wordFromDictChar) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nconst WordDictionary = function () {\n  this.hashmap = {};\n};\n\nWordDictionary.prototype.addWord = function (word) {\n  if (!this.hashmap[word]) {\n    this.hashmap[word] = true;\n  }\n};\n\nWordDictionary.prototype.search = function (word) {\n  if (this.hashmap[word]) {\n    return this.hashmap[word];\n  }\n\n  let words = Object.keys(this.hashmap);\n\n  for (let wordFromDict of words) {\n    if (isTheSame(word, wordFromDict)) {\n      return true;\n    }\n  }\n\n  return false;\n};\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/difference-between-ones-and-zeros-in-row-and-column/difference-between-ones-and-zeros-in-row-and-column.js",
    "content": "function traverseGridRow(grid, row) {\n  let diff = 0;\n\n  for (let col = 0; col < grid[row].length; col++) {\n    let cell = grid[row][col];\n\n    if (cell) {\n      diff++;\n    } else {\n      diff--;\n    }\n  }\n\n  return diff;\n}\n\nfunction traverseGridCol(grid, col) {\n  let diff = 0;\n\n  for (let row = 0; row < grid.length; row++) {\n    let cell = grid[row][col];\n\n    if (cell) {\n      diff++;\n    } else {\n      diff--;\n    }\n  }\n\n  return diff;\n}\n\nfunction onesMinusZeros(grid) {\n  let rows = [];\n  let cols = [];\n  let diffGrid = [];\n\n  for (let row = 0; row < grid.length; row++) {\n    let diffRow = [];\n\n    for (let col = 0; col < grid[row].length; col++) {\n      let rowDiff;\n      let colDiff;\n\n      if (row < rows.length) {\n        rowDiff = rows[row];\n      } else {\n        rowDiff = traverseGridRow(grid, row);\n        rows.push(rowDiff);\n      }\n\n      if (col < cols.length) {\n        colDiff = cols[col];\n      } else {\n        colDiff = traverseGridCol(grid, col);\n        cols.push(colDiff);\n      }\n\n      diffRow.push(rowDiff + colDiff);\n    }\n\n    diffGrid.push(diffRow);\n  }\n\n  return diffGrid;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/encode_and_decode_tinyurl/encode_and_decode_tinyurl.py",
    "content": "# https://leetcode.com/problems/encode-and-decode-tinyurl\n\nclass Codec:\n    count = 0\n    tiny_to_url = {}\n    url_to_tiny = {}\n    tiny_url_prefix = 'http://tinyurl.com/'\n\n    def encode(self, longUrl: str) -> str:\n        if longUrl in self.url_to_tiny:\n            return self.url_to_tiny[longUrl]\n\n        tiny_url = self.tiny_url_prefix + str(self.count)\n        self.url_to_tiny[longUrl] = tiny_url\n        self.tiny_to_url[tiny_url] = longUrl\n        self.count += 1\n        return tiny_url\n\n    def decode(self, shortUrl: str) -> str:\n        return self.tiny_to_url[shortUrl]\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/execution-of-all-suffix-instructions-staying-in-a-grid/execution-of-all-suffix-instructions-staying-in-a-grid.js",
    "content": "// https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid\n\nfunction isOffGrid(row, col, n) {\n  return row < 0 || row >= n || col < 0 || col >= n;\n}\n\nfunction executeInstructions(n, startPos, s) {\n  let answer = [];\n\n  for (let index = 0; index < s.length; index++) {\n    let instructionIndex = index;\n    let instruction = s[instructionIndex];\n    let row = startPos[0];\n    let col = startPos[1];\n    let numOfInstructions = 0;\n\n    if (instruction === 'R') col++;\n    if (instruction === 'L') col--;\n    if (instruction === 'U') row--;\n    if (instruction === 'D') row++;\n\n    while (instructionIndex < s.length && !isOffGrid(row, col, n)) {\n      instructionIndex++;\n      instruction = s[instructionIndex];\n      if (instruction === 'R') col++;\n      if (instruction === 'L') col--;\n      if (instruction === 'U') row--;\n      if (instruction === 'D') row++;\n      numOfInstructions++;\n    }\n\n    answer.push(numOfInstructions);\n  }\n\n  return answer;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/find-the-original-array-of-prefix-xor/README.md",
    "content": "# Find The Original Array of Prefix Xor\n\n[Problem link](https://leetcode.com/problems/find-the-original-array-of-prefix-xor)\n\n- If you want `5 ^ ? = 2`, you can do a reverse xor using `5 ^ 2 = ?`, which in this case `? = 7`\n- If you want to do consecutive XOR operations like `5 ^ 7 ^ 2 ^ 3 ^ 2`, you can replace that with the previous `pref` item\n  - e.g. `5 ^ 7 ^ ? = 0.`, you want to find `?`\n  - so you need to do `5 ^ 7 ^ 0 = ?` but at that point, if you don't store the previous result, you don't have `5 ^ 7`\n  - but you can get this calculation from the previous `pref` item because it can replace `5 ^ 7`, in this case, it is `2`\n- Runtime complexity: O(N), where N is prev.length\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/find-the-original-array-of-prefix-xor/find-the-original-array-of-prefix-xor.js",
    "content": "function findArray(pref) {\n  let output = [pref[0]];\n\n  for (let index = 1; index < pref.length; index++) {\n    output.push(pref[index - 1] ^ pref[index]);\n  }\n\n  return output;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/find-the-winner-of-the-circular-game/find-the-winner-of-the-circular-game.js",
    "content": "// https://leetcode.com/problems/find-the-winner-of-the-circular-game\n\nfunction toArray(n) {\n  let list = [];\n\n  for (let num = 1; num <= n; num++) {\n    list.push(num);\n  }\n\n  return list;\n}\n\nfunction findTheWinner(n, k) {\n  let list = toArray(n);\n  let index = 0;\n\n  while (list.length > 1) {\n    index = (index + k - 1) % list.length;\n    list.splice(index, 1);\n  }\n\n  return list[0];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/find-the-winner-of-the-circular-game/queue-find-the-winner-of-the-circular-game.js",
    "content": "// https://leetcode.com/problems/find-the-winner-of-the-circular-game\n\nfunction buildQueue(n) {\n  let queue = [];\n\n  for (let num = 1; num <= n; num++) {\n    queue.push(num);\n  }\n\n  return queue;\n}\n\nfunction findTheWinner(n, k) {\n  let queue = buildQueue(n);\n\n  while (queue.length > 1) {\n    let count = 1;\n\n    while (count < k) {\n      queue.push(queue.shift());\n      count++;\n    }\n\n    queue.shift();\n  }\n\n  return queue[0];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/find-triangular-sum-of-an-array/find-triangular-sum-of-an-array.js",
    "content": "function calculate(num1, num2) {\n  return (num1 + num2) % 10;\n}\n\nexport function triangularSum(nums) {\n  let numsCopy = [...nums];\n  let newNums = [];\n  let N = nums.length;\n\n  for (let i = 0; i < N - 1; i++) {\n    newNums = [];\n\n    for (let index = 0; index < numsCopy.length - 1; index++) {\n      newNums.push(calculate(numsCopy[index], numsCopy[index + 1]));\n    }\n\n    numsCopy = newNums;\n  }\n\n  return numsCopy;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/find-triangular-sum-of-an-array/tests/find-triangular-sum-of-an-array.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { triangularSum } from '../find-triangular-sum-of-an-array';\n\ndescribe('triangularSum', () => {\n  it('', () => {\n    expect(triangularSum([1, 2, 3, 4, 5])).toEqual([8]);\n  });\n\n  it('', () => {\n    expect(triangularSum([5])).toEqual([5]);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/find-valid-matrix-given-row-and-column-sums/find-valid-matrix-given-row-and-column-sums.js",
    "content": "function buildMatrix(rows, cols) {\n  const matrix = [];\n\n  for (let row = 0; row < rows; row++) {\n    let matrixRow = [];\n\n    for (let col = 0; col < cols; col++) {\n      matrixRow.push(0);\n    }\n\n    matrix.push(matrixRow);\n  }\n\n  return matrix;\n}\n\nfunction restoreMatrix(rowSum, colSum) {\n  const matrix = buildMatrix(rowSum.length, colSum.length);\n\n  for (let row = 0; row < matrix.length; row++) {\n    for (let col = 0; col < matrix[0].length; col++) {\n      const min = Math.min(rowSum[row], colSum[col]);\n      matrix[row][col] = min;\n      rowSum[row] -= min;\n      colSum[col] -= min;\n    }\n  }\n\n  return matrix;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/find_and_replace_pattern/find_and_replace_pattern.py",
    "content": "# https://leetcode.com/problems/find-and-replace-pattern\n\ndef find_and_replace_pattern(words, pattern):\n    matchers = []\n    \n    for word in words:\n        mapper = {}\n        match = True\n        used_pattern_letters = set()\n        \n        for index in range(len(word)):\n            word_letter = word[index]\n            pattern_letter = pattern[index]\n            \n            if word_letter in mapper and mapper[word_letter] != pattern_letter or (pattern_letter in used_pattern_letters and word_letter not in mapper):\n                match = False\n                break\n            \n            if word_letter not in mapper:\n                used_pattern_letters.add(pattern_letter)\n                mapper[word_letter] = pattern_letter\n                \n        if match: matchers.append(word)\n    \n    return matchers\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/finding_pairs_with_a_certain_sum/finding_pairs_with_a_certain_sum.py",
    "content": "# https://leetcode.com/problems/finding-pairs-with-a-certain-sum\n\nclass FindSumPairs:\n    def __init__(self, nums1, nums2):\n        self.nums1 = nums1\n        self.nums2 = nums2\n        self.nums2_freq = Counter(nums2)\n\n    def add(self, index, val):\n        self.nums2_freq[self.nums2[index]] -= 1\n        self.nums2[index] += val\n        self.nums2_freq[self.nums2[index]] += 1\n\n    def count(self, total):\n        count = 0\n\n        for num in self.nums1:\n            if (total - num) in self.nums2_freq:\n                count += self.nums2_freq[total - num]\n                    \n        return count\n\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/finding_the_users_active_minutes/finding_the_users_active_minutes.py",
    "content": "# https://leetcode.com/problems/finding-the-users-active-minutes\n\ndef build_unique_actions_by_id(logs):\n    unique_actions_by_id = {}    \n    \n    for [id, minute] in logs:\n        if id in unique_actions_by_id:\n            unique_actions_by_id[id].add(minute)\n        else:\n            unique_actions_by_id[id] = set({minute})\n            \n    return unique_actions_by_id\n\ndef build_count_by_actions_number(unique_actions_by_id):\n    count = {}\n    \n    for _, actions in unique_actions_by_id.items():\n        if len(actions) in count:\n            count[len(actions)] += 1\n        else:\n            count[len(actions)] = 1\n            \n    return count\n\ndef build_answer(count_by_actions_number, k):\n    answer = []\n\n    for num in range(1, k + 1):\n        if num in count_by_actions_number:\n            answer.append(count_by_actions_number[num])\n        else:\n            answer.append(0)\n            \n    return answer\n\ndef finding_users_active_minutes(logs, k):\n    unique_actions_by_id = build_unique_actions_by_id(logs)\n    count_by_actions_number = build_count_by_actions_number(unique_actions_by_id)\n    return build_answer(count_by_actions_number, k)\n\n# -------------------------------------------------------------------------------\n\ndef finding_users_active_minutes(logs, k):\n    d = defaultdict(set)\n\n    for id, minute in logs:\n        d[id].add(minute)\n    \n    answer = [0] * k\n\n    for _, actions in d.items():\n        count = len(actions)\n        answer[count - 1] += 1\n    \n    return answer"
  },
  {
    "path": "coding_interviews/leetcode/medium/fraction_to_decimal/fraction_to_decimal.py",
    "content": "def fraction_to_decimal(numerator, denominator):\n    if numerator == 0:\n        return '0'\n\n    if numerator % denominator == 0:\n        return str(numerator // denominator)\n\n    result = ''\n\n    if ('-' in str(numerator)) ^ ('-' in str(denominator)):\n        result += '-'\n\n    numerator = abs(numerator)\n    denominator = abs(denominator)\n\n    number = str(numerator // denominator)\n\n    result += number\n    result += '.'\n\n    mapper = {}\n    remainder = numerator % denominator\n\n    while True:\n        if remainder == 0:\n            break\n\n        if remainder in mapper:\n            result = result[:mapper[remainder]] + \\\n                '(' + result[mapper[remainder]:] + ')'\n            break\n\n        mapper[remainder] = len(result)\n        remainder *= 10\n        result += str(remainder // denominator)\n        remainder %= denominator\n\n    return result\n\n\ndata_test = [\n    (1, 2, \"0.5\"),\n    (2, 1, \"2\"),\n    (2, 3, \"0.(6)\"),\n    (4, 333, \"0.(012)\"),\n    (1, 4, \"0.25\"),\n    (1, 6, \"0.1(6)\"),\n    (-1, 6, \"-0.1(6)\"),\n    (1, -6, \"-0.1(6)\"),\n    (-50, 8, \"-6.25\"),\n    (1, 214748364, \"0.00(000000465661289042462740251655654056577585848337359161441621040707904997124914069194026549138227660723878669455195477065427143370461252966751355553982241280310754777158628319049732085502639731402098131932683780538602845887105337854867197032523144157689601770377165713821223802198558308923834223016478952081795603341592860749337303449725)\")\n]\n\nfor numerator, denominator, expected in data_test:\n    result = fraction_to_decimal(numerator, denominator)\n    print(result, result == expected)\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/group-anagrams/group-anagrams.js",
    "content": "function sort(string) {\n  return [...string].sort((c1, c2) => c1.localeCompare(c2)).join('');\n}\n\nfunction groupAnagrams(strs) {\n  let hashmap = {};\n\n  for (let string of strs) {\n    let sortedString = sort(string);\n\n    if (hashmap[sortedString]) {\n      hashmap[sortedString].push(string);\n    } else {\n      hashmap[sortedString] = [string];\n    }\n  }\n\n  return Object.values(hashmap);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/group_the_people/group_the_people.py",
    "content": "# https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/\n\n\ndef group_the_people(groupSizes):\n    grouped_by_size = {}\n\n    for index in range(len(groupSizes)):\n        size = groupSizes[index]\n\n        if size in grouped_by_size:\n            grouped_by_size[size] += [index]\n        else:\n            grouped_by_size[size] = [index]\n\n    grouped_by_ids = []\n\n    for size, indices in grouped_by_size.items():\n        for index in range(0, len(indices), size):\n            grouped_by_ids.append(indices[index:index+size])\n\n    return grouped_by_ids\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/insert-greatest-common-divisors-in-linked-list/insert-greatest-common-divisors-in-linked-list.js",
    "content": "/**\n * https://leetcode.com/problems/insert-greatest-common-divisors-in-linked-list\n *\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.next = (next===undefined ? null : next)\n * }\n */\n\nfunction calculateGCD(x, y) {\n  x = Math.abs(x);\n  y = Math.abs(y);\n  while (y) {\n    var t = y;\n    y = x % y;\n    x = t;\n  }\n  return x;\n}\n\nfunction insertGreatestCommonDivisors(head) {\n  if (!head.next) return head;\n\n  let curr = head;\n  let next = head.next;\n\n  while (next) {\n    let newNode = new ListNode(calculateGCD(curr.val, next.val), next);\n    curr.next = newNode;\n    curr = next;\n    next = next.next;\n  }\n\n  return head;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/insert-into-a-binary-search-tree/insert-into-a-binary-search-tree.js",
    "content": "function insertIntoBST(root, val) {\n  if (!root) {\n    return new TreeNode(val);\n  }\n\n  if (val < root.val) {\n    root.left = insertIntoBST(root.left, val);\n  }\n\n  if (val > root.val) {\n    root.right = insertIntoBST(root.right, val);\n  }\n\n  return root;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/insert_bst/insert_bst.py",
    "content": "class TreeNode:\n    def __init__(self, val=0, left=None, right=None):\n        self.val = val\n        self.left = left\n        self.right = right\n\n\ndef insert_into_BST(root, val):\n    if root is None:\n        return TreeNode(val)\n\n    if val < root.val:\n        root.left = insert_into_BST(root.left, val)\n\n    if val > root.val:\n        root.right = insert_into_BST(root.right, val)\n\n    return root\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/keep_city_skyline/keep_city_skyline.py",
    "content": "# https://leetcode.com/problems/max-increase-to-keep-city-skyline/description/\n\n# input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]\n# output: 35\n\ndef build_top_or_bottom(grid):\n    top_or_bottom = []\n\n    for i in range(len(grid[0])):\n        highest_building = 0\n\n        for j in range(len(grid)):\n            if grid[j][i] > highest_building:\n                highest_building = grid[j][i]\n\n        top_or_bottom.append(highest_building)\n\n    return top_or_bottom\n\ndef build_left_or_right(grid):\n    left_or_right = []\n\n    for line in grid:\n        highest_building = 0\n\n        for building_height in line:\n            if building_height > highest_building:\n                highest_building = building_height\n\n        left_or_right.append(highest_building)\n\n    return left_or_right\n\ndef max_increase_keeping_skyline(grid):\n    top_or_bottom = build_top_or_bottom(grid)\n    left_or_right = build_left_or_right(grid)\n\n    increased_number = 0\n\n    for i in range(len(grid)):\n        for j in range(len(grid[i])):\n            if left_or_right[i] < top_or_bottom[j]:\n                increased_number += (left_or_right[i] - grid[i][j])\n            else:\n                increased_number += (top_or_bottom[j] - grid[i][j])\n\n    return increased_number\n\nprint(max_increase_keeping_skyline([[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]))\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst-1.js",
    "content": "function traverse(node, list) {\n  return node\n    ? [\n        ...list,\n        ...traverse(node.left, list),\n        node.val,\n        ...traverse(node.right, list),\n      ]\n    : [];\n}\n\nfunction kthSmallest(root, k) {\n  return traverse(root, [])[k - 1];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst-2.js",
    "content": "let counter;\nlet nodeValue;\n\nfunction traverseAndGetKthSmallest(node, k) {\n  if (!node) return;\n\n  traverseAndGetKthSmallest(node.left, k);\n  counter++;\n\n  if (counter === k) {\n    nodeValue = node.val;\n  }\n\n  traverseAndGetKthSmallest(node.right, k);\n}\n\nfunction kthSmallest(root, k) {\n  counter = 0;\n  nodeValue = -1;\n  traverseAndGetKthSmallest(root, k);\n  return nodeValue;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst.js",
    "content": "// Solution 1\n// additional memory usage: array\n\nfunction traverse(node, list) {\n  return node\n    ? [\n        ...list,\n        ...traverse(node.left, list),\n        node.val,\n        ...traverse(node.right, list),\n      ]\n    : [];\n}\n\nfunction kthSmallest(root, k) {\n  return traverse(root, [])[k - 1];\n}\n\n// =========================== // ===========================\n\n// Solution 2\n// Less memory\nlet counter;\nlet nodeValue;\n\nfunction traverseAndGetKthSmallest(node, k) {\n  if (!node) return;\n\n  traverseAndGetKthSmallest(node.left, k);\n  counter++;\n\n  if (counter === k) {\n    nodeValue = node.val;\n  }\n\n  traverseAndGetKthSmallest(node.right, k);\n}\n\nfunction kthSmallest(root, k) {\n  counter = 0;\n  nodeValue = -1;\n  traverseAndGetKthSmallest(root, k);\n  return nodeValue;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/letter_tile_possibilities/letter_tile_possibilities.py",
    "content": "# https://leetcode.com/problems/letter-tile-possibilities\n\ndef num_tile_possibilities(tiles):\n    res = set()\n\n    def dfs(path, tile):\n        if path not in res:\n            if path: res.add(path)\n            for i in range(len(tile)):\n                dfs(path + tile[i], tile[:i] + tile[i+1:])\n            \n    dfs('', tiles)\n\n    return len(res)\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.js",
    "content": "/**\nabcadccb => abc / bcad / cad / adc / dc / c / cb\n=> 4\n\n\"abcadccb\"\n ^  ^\n\nlocalCount = 0 -> 1 -> 2 -> 1 -> 2 -> 3;\nmaxCount = 0 -> 1 -> 2 -> 3;\nset = ['b', 'c'] -> ['c', 'd', 'a'] -> ['c', 'd', 'a', 'b']\n*/\n\nfunction lengthOfLongestSubstring(s) {\n  let leftPointer = 0;\n  let maxCount = 0;\n  let charToIndex = {};\n\n  for (let rightPointer = 0; rightPointer < s.length; rightPointer++) {\n    let num = s[rightPointer];\n    let index = charToIndex[num];\n\n    if (index == undefined) {\n      maxCount = Math.max(maxCount, rightPointer - leftPointer + 1);\n    } else {\n      if (index >= leftPointer) {\n        leftPointer = index + 1;\n      } else {\n        maxCount = Math.max(maxCount, rightPointer - leftPointer + 1);\n      }\n    }\n\n    charToIndex[num] = rightPointer;\n  }\n\n  return maxCount;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/max-area-of-island/max-area-of-island.js",
    "content": "function isOffTheGrid(grid, row, col) {\n  let gridRows = grid.length;\n  let gridCols = grid[0].length;\n  return row < 0 || row >= gridRows || col < 0 || col >= gridCols;\n}\n\nfunction dfs(grid, row, col, maximumLocalIslandArea = 0) {\n  if (isOffTheGrid(grid, row, col) || grid[row][col] === 0) {\n    return 0;\n  }\n\n  grid[row][col] = 0; // visited\n\n  return (\n    1 +\n    dfs(grid, row - 1, col, maximumLocalIslandArea) + // top\n    dfs(grid, row + 1, col, maximumLocalIslandArea) + // bottom\n    dfs(grid, row, col + 1, maximumLocalIslandArea) + // right\n    dfs(grid, row, col - 1, maximumLocalIslandArea) // left\n  );\n}\n\nfunction maxAreaOfIsland(grid) {\n  let maximumIslandArea = 0;\n\n  for (let row = 0; row < grid.length; row++) {\n    for (let col = 0; col < grid[row].length; col++) {\n      let maximumLocalIslandArea = dfs(grid, row, col);\n      maximumIslandArea = Math.max(maximumIslandArea, maximumLocalIslandArea);\n    }\n  }\n\n  return maximumIslandArea;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/max_coins/max_coins.py",
    "content": "# https://leetcode.com/problems/maximum-number-of-coins-you-can-get\n\n\ndef max_coins(piles):\n    piles = sorted(piles)\n    bob = 0\n    me = len(piles) - 2\n    alice = len(piles) - 1\n    counter = 0\n\n    while me > bob:\n        counter += piles[me]\n        bob += 1\n        me -= 2\n        alice -= 2\n\n    return counter\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/maximum-sum-of-an-hourglass/maximum-sum-of-an-hourglass.js",
    "content": "// https://leetcode.com/problems/maximum-sum-of-an-hourglass\n\nfunction maxRowSum(grid, row, col) {\n  return (\n    grid[row][col] +\n    grid[row][col + 1] +\n    grid[row][col + 2] +\n    grid[row + 1][col + 1] +\n    grid[row + 2][col] +\n    grid[row + 2][col + 1] +\n    grid[row + 2][col + 2]\n  );\n}\n\nfunction maxSum(grid) {\n  let maxSumOfAnHourglass = 0;\n\n  for (let row = 0; row + 2 < grid.length; row++) {\n    for (let col = 0; col + 2 < grid[row].length; col++) {\n      maxSumOfAnHourglass = Math.max(\n        maxSumOfAnHourglass,\n        maxRowSum(grid, row, col)\n      );\n    }\n  }\n\n  return maxSumOfAnHourglass;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/maximum_binary_tree/maximum_binary_tree.py",
    "content": "'''\nhttps://leetcode.com/problems/maximum-binary-tree/description/\n\nInput: [3,2,1,6,0,5]\nOutput: return the tree root node representing the following tree:\n\n      6\n    /   \\\n   3     5\n    \\    /\n     2  0\n       \\\n        1\n'''\n\nclass TreeNode(object):\n    def __init__(self, x):\n        self.val = x\n        self.left = None\n        self.right = None\n\ndef construct_maximum_binary_tree(nums):\n    if not nums: return None\n    root_node = TreeNode(max(nums))\n    root_node.left = construct_maximum_binary_tree(nums[0:nums.index(max(nums))])\n    root_node.right = construct_maximum_binary_tree(nums[nums.index(max(nums))+1:])\n    return root_node\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/median_tree/median_tree.py",
    "content": "class Node:\n    def __init__(self, value, left, right):\n        self.value = value\n        self.left = left\n        self.right = right\n\n\ndef sum_and_count_nodes(node, sum_of_values, count):\n    if node is None:\n        return sum_of_values, count\n    \n    sum_of_values, count = sum_and_count_nodes(node.left, sum_of_values + node.value, count + 1)\n    sum_of_values, count = sum_and_count_nodes(node.right, sum_of_values + node.value, count + 1)\n    return sum_of_values, count\n    \n\ndef median(tree):\n    sum_of_values, count = sum_and_count_nodes(tree, 0, 0)\n    if count == 0: return 0\n    return sum_of_values / count\n\n\nleft = Node(1, None, None)\nright = Node(2, None, None)\nroot = Node(3, left, right)\n\nresult = median(root)\nprint(result)\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/merge-nodes-in-between-zeros/merge-nodes-in-between-zeros.js",
    "content": "export class ListNode {\n  constructor(val, next) {\n    this.val = val === undefined ? 0 : val;\n    this.next = next === undefined ? null : next;\n  }\n}\n\nexport function mergeNodes(head) {\n  let nonZeroHead;\n  let node;\n  let nextNode;\n  let currentNode = head.next;\n  let valueSum = 0;\n  let gotFirstNode = false;\n\n  while (currentNode) {\n    valueSum += currentNode.val;\n\n    if (currentNode.val === 0) {\n      nextNode = new ListNode(valueSum);\n      valueSum = 0;\n\n      if (gotFirstNode) {\n        node.next = nextNode;\n        node = node.next;\n      } else {\n        node = nextNode;\n        nonZeroHead = nextNode;\n        gotFirstNode = true;\n      }\n    }\n\n    currentNode = currentNode.next;\n  }\n\n  return nonZeroHead;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/merge-nodes-in-between-zeros/tests/merge-nodes-in-between-zeros.test.js",
    "content": "import { describe, it, expect } from 'vitest';\nimport { ListNode, mergeNodes } from '../merge-nodes-in-between-zeros';\n\nfunction buildList(nums, initValue = 0) {\n  let head = new ListNode(initValue);\n  let node = head;\n  let nextNode;\n\n  for (let i = 1; i < nums.length; i++) {\n    nextNode = new ListNode(nums[i]);\n    node.next = nextNode;\n    node = node.next;\n  }\n\n  return head;\n}\n\ndescribe('mergeNodes', () => {\n  it('removes zeros and merges nodes', () => {\n    const head = buildList([0, 3, 1, 0, 4, 5, 2, 0]);\n    const result = buildList([4, 11], 4);\n    expect(mergeNodes(head)).toEqual(result);\n  });\n\n  it('removes zeros and merges nodes', () => {\n    const head = buildList([0, 1, 0, 3, 0, 2, 2, 0]);\n    const result = buildList([1, 3, 4], 1);\n    expect(mergeNodes(head)).toEqual(result);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/min-cost-climbing-stairs/min-cost-climbing-stairs.js",
    "content": "// https://leetcode.com/problems/min-cost-climbing-stairs\n// https://leetcode.com/problems/min-cost-climbing-stairs/solutions/476388/4-ways-step-by-step-from-recursion-top-down-dp-bottom-up-dp-fine-tuning\n\nfunction getMinCost(stairs, index, dp) {\n  if (index < 0) return 0;\n  if (index === 0 || index === 1) return stairs[index];\n  if (dp[index]) return dp[index];\n\n  dp[index] =\n    stairs[index] +\n    Math.min(\n      getMinCost(stairs, index - 1, dp),\n      getMinCost(stairs, index - 2, dp)\n    );\n\n  return dp[index];\n}\n\nfunction minCostClimbingStairs(cost) {\n  let dp = [];\n  let minCostFirst = getMinCost(cost, cost.length - 1, dp);\n  let minCostSecond = getMinCost(cost, cost.length - 2, dp);\n  return Math.min(minCostFirst, minCostSecond);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/min_operations/min_operations.py",
    "content": "def min_operations(n):\n    operations = 0\n\n    for index in range(n // 2):\n        operations += n - (2 * index + 1)\n\n    return operations\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/min_pair_sum/min_pair_sum.py",
    "content": "# https://leetcode.com/problems/minimize-maximum-pair-sum-in-array\n\ndef min_pair_sum(nums):\n    sorted_nums = sorted(nums)\n    maximum_pair_sum = float('-Inf')\n    \n    for i in range(len(nums) // 2):\n        pair_sum = sorted_nums[i] + sorted_nums[len(sorted_nums) - i - 1]\n        maximum_pair_sum = max(maximum_pair_sum, pair_sum)\n        \n    return maximum_pair_sum\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/min_partitions/min_partitions.py",
    "content": "# https://leetcode.com/problems/partitioning-into-minimum-number-of-deci-binary-numbers\n\ndef min_partitions(n):\n    count = '0'\n\n    for digit_char in n:\n        if digit_char > count:\n            count = digit_char\n\n    return int(count)\n\ndef min_partitions(n):\n    return int(max(n))\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/minimum-add-to-make-parentheses-valid/minimum-add-to-make-parentheses-valid.js",
    "content": "/*\n\"(\" => 1\n\")\" => 1\n\"()\" => 0\n\"(()\" => 1\n\"())\" => 1\n\"(((\" => 3\n\")))\" => 3\n\")(\" => 2 => \"()(\" => \"()()\"\n\"()))((\" => 4\n*/\n\nfunction minAddToMakeValid(s) {\n  let closeParenthesisCount = 0;\n  let openParenthesisStack = [];\n\n  for (let stringIndex = 0; stringIndex < s.length; stringIndex++) {\n    const char = s[stringIndex];\n\n    if (char === '(') {\n      openParenthesisStack.push(char);\n    } else {\n      if (openParenthesisStack.length) {\n        openParenthesisStack.pop();\n      } else {\n        closeParenthesisCount++;\n      }\n    }\n  }\n\n  return closeParenthesisCount + openParenthesisStack.length;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/minimum-amount-of-time-to-collect-garbage/minimum-amount-of-time-to-collect-garbage.js",
    "content": "function measure(garbage, travel, garbageType) {\n  let minutes = 0;\n  let lastGarbageItem = -1;\n\n  for (let [index, garbageItems] of garbage.entries()) {\n    let itemCount = 0;\n\n    for (let item of garbageItems) {\n      if (item === garbageType) {\n        lastGarbageItem = index;\n        itemCount++;\n      }\n    }\n\n    minutes += itemCount;\n  }\n\n  for (let index = 0; index < lastGarbageItem; index++) {\n    minutes += travel[index];\n  }\n\n  return minutes;\n}\n\nfunction garbageCollection(garbage, travel) {\n  let minutes = 0;\n  minutes += measure(garbage, travel, 'G');\n  minutes += measure(garbage, travel, 'M');\n  minutes += measure(garbage, travel, 'P');\n  return minutes;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/minimum-cost-of-buying-candies-with-discount/minimum-cost-of-buying-candies-with-discount.js",
    "content": "// https://leetcode.com/problems/minimum-cost-of-buying-candies-with-discount\n\nfunction sum(cost) {\n  let sumOfAllCost = 0;\n\n  for (let c of cost) {\n    sumOfAllCost += c;\n  }\n\n  return sumOfAllCost;\n}\n\nfunction minimumCost(cost) {\n  if (cost.length <= 2) return sum(cost);\n  cost.sort((a, b) => a - b);\n\n  let allCost = 0;\n  let index;\n\n  for (index = cost.length - 1; index > 1; index -= 3) {\n    if (cost[index] <= cost[index - 2]) {\n      allCost += cost[index - 1] + cost[index - 2];\n    } else {\n      allCost += cost[index] + cost[index - 1];\n    }\n  }\n\n  allCost += sum(cost.slice(0, index + 1));\n\n  return allCost;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/minimum-number-of-steps-to-make-two-strings-anagram/README.md",
    "content": "# Minimum Number of Steps to Make Two Strings Anagram\n\n[Problem link](https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram)\n\n- Using the hash map data structure\n- Runtime complexity: O(N), where N is the length of `s` and `t`\n- Counting and comparing characters require hash maps to get the count based on each character\n  - key: characters\n  - value: count of each character\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/minimum-number-of-steps-to-make-two-strings-anagram/minimum-number-of-steps-to-make-two-strings-anagram.js",
    "content": "function buildMap(string) {\n  let map = new Map();\n\n  for (let char of string) {\n    if (map.has(char)) map.set(char, map.get(char) + 1);\n    else map.set(char, 1);\n  }\n\n  return map;\n}\n\nfunction minSteps(s, t) {\n  let sMap = buildMap(s);\n  let tMap = buildMap(t);\n  let minimumSteps = 0;\n\n  for (let [char, count] of sMap.entries()) {\n    if (!tMap.has(char)) {\n      minimumSteps += count;\n    } else if (count > tMap.get(char)) {\n      minimumSteps += count - tMap.get(char);\n    }\n  }\n\n  return minimumSteps;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/minimum_number_of_operations_to_move_all_balls_to_each_box/minimum_number_of_operations_to_move_all_balls_to_each_box.py",
    "content": "# https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/\n\ndef min_operations(boxes):\n    answer = []\n    \n    for index in range(len(boxes)):\n        counter = 0\n        for box_index in range(len(boxes)):\n            if index != box_index and boxes[box_index] == '1':\n                counter += abs(index - box_index)\n                \n        answer.append(counter)\n        \n    return answer\n\ndef sum_moves(answer, boxes, boxes_indices):\n    moves, number_of_balls_seen = 0, 0\n    \n    for index in boxes_indices:\n        answer[index] += moves\n\n        if boxes[index] == '1':\n            number_of_balls_seen += 1\n\n        moves += number_of_balls_seen\n\n    return answer\n\ndef min_operations(boxes):\n    length_boxes = len(boxes)\n    answer, moves, number_of_balls_seen = [0] * length_boxes, 0, 0\n    answer = sum_moves(answer, boxes, range(length_boxes))\n    return sum_moves(answer, boxes, reversed(range(length_boxes)))"
  },
  {
    "path": "coding_interviews/leetcode/medium/number-of-closed-islands/number-of-closed-islands.js",
    "content": "/**\n- is it in the border: no closed island\n- length == 1, 2: no closed island\n- visited data structure: map\n- iterate: [1,1] -> [n-1,n-1]\n  - is it 0\n  - go to top, bottom, left, right with a dfs fn\n    - is it 0: go to top, bottom, left, right with recursive call to the dfs fn\n*/\nfunction generateVisitedKey(row, col) {\n  return `${row}-${col}`;\n}\n\nfunction isInsideTheGrid(grid, row, col) {\n  return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length;\n}\n\nfunction dfs(grid, row, col, visited) {\n  let key = generateVisitedKey(row, col);\n\n  if (!isInsideTheGrid(grid, row, col)) {\n    return false;\n  }\n\n  if (grid[row][col] === 1 || visited[key]) {\n    return true;\n  }\n\n  if (grid[row][col] === 0 && !visited[key]) {\n    visited[key] = true;\n\n    let top = dfs(grid, row - 1, col, visited);\n    let bottom = dfs(grid, row + 1, col, visited);\n    let left = dfs(grid, row, col - 1, visited);\n    let right = dfs(grid, row, col + 1, visited);\n\n    return top && bottom && left && right;\n  }\n}\n\nfunction closedIsland(grid) {\n  if (grid.length <= 2 || grid[0].length <= 2) {\n    return 0;\n  }\n\n  let visited = {};\n  let closedIslandsNumber = 0;\n\n  for (let row = 1; row < grid.length - 1; row++) {\n    for (let col = 1; col < grid[row].length - 1; col++) {\n      let cell = grid[row][col];\n      let key = generateVisitedKey(row, col);\n\n      if (cell === 0 && !visited[key]) {\n        visited[key] = true;\n\n        let top = dfs(grid, row - 1, col, visited);\n        let bottom = dfs(grid, row + 1, col, visited);\n        let left = dfs(grid, row, col - 1, visited);\n        let right = dfs(grid, row, col + 1, visited);\n        let isClosedIsland = top && bottom && left && right;\n\n        if (isClosedIsland) {\n          closedIslandsNumber++;\n        }\n      }\n    }\n  }\n\n  return closedIslandsNumber;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/number-of-enclaves/number-of-enclaves.js",
    "content": "/**\n - 0 => true\n - dfs => (top, bottom, left, right)\n - off the grid => false\n */\nfunction getVisitedKey(row, col) {\n  return `${row}-${col}`;\n}\n\nfunction isOffTheGrid(grid, row, col) {\n  return row < 0 || col < 0 || row >= grid.length || col >= grid[0].length;\n}\n\nfunction dfs(grid, row, col, visited) {\n  if (isOffTheGrid(grid, row, col)) {\n    return -1;\n  }\n\n  if (grid[row][col] === 0) {\n    return 0;\n  }\n\n  let key = getVisitedKey(row, col);\n\n  if (visited[key]) {\n    return 0;\n  }\n\n  visited[key] = true;\n\n  let top = dfs(grid, row - 1, col, visited);\n  let bottom = dfs(grid, row + 1, col, visited);\n  let left = dfs(grid, row, col - 1, visited);\n  let right = dfs(grid, row, col + 1, visited);\n\n  return top === -1 || bottom === -1 || left === -1 || right === -1\n    ? -1\n    : 1 + top + bottom + left + right;\n}\n\nfunction numEnclaves(grid) {\n  let numberOfLands = 0;\n  let visited = {};\n\n  for (let row = 0; row < grid.length; row++) {\n    for (let col = 0; col < grid[row].length; col++) {\n      let cell = grid[row][col];\n      let key = getVisitedKey(row, col);\n\n      if (cell && !visited[key]) {\n        visited[key] = true;\n\n        let top = dfs(grid, row - 1, col, visited);\n        let bottom = dfs(grid, row + 1, col, visited);\n        let left = dfs(grid, row, col - 1, visited);\n        let right = dfs(grid, row, col + 1, visited);\n\n        numberOfLands +=\n          top === -1 || bottom === -1 || left === -1 || right === -1\n            ? 0\n            : 1 + top + bottom + left + right;\n      }\n    }\n  }\n\n  return numberOfLands;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/number-of-islands/number-of-islands.js",
    "content": "function isInsideTheGrid(grid, row, col) {\n  return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length;\n}\n\nfunction dfs(grid, row, col) {\n  if (isInsideTheGrid(grid, row, col) && grid[row][col] === '1') {\n    grid[row][col] = 0; // marked as visited\n    dfs(grid, row - 1, col); // top\n    dfs(grid, row + 1, col); // bottom\n    dfs(grid, row, col - 1); // left\n    dfs(grid, row, col + 1); // right\n  }\n}\n\nfunction numIslands(grid) {\n  let numberOfIslands = 0;\n\n  for (let row = 0; row < grid.length; row++) {\n    for (let col = 0; col < grid[row].length; col++) {\n      if (grid[row][col] === '1') {\n        numberOfIslands++;\n        grid[row][col] = 0; // marked as visited\n\n        dfs(grid, row - 1, col); // top\n        dfs(grid, row + 1, col); // bottom\n        dfs(grid, row, col - 1); // left\n        dfs(grid, row, col + 1); // right\n      }\n    }\n  }\n\n  return numberOfIslands;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/number-of-laser-beams-in-a-bank/number-of-laser-beams-in-a-bank.js",
    "content": "/*\nAnti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device.\n\nThere is one laser beam between any two security devices if both conditions are met:\n\nThe two devices are located on two different rows: r1 and r2, where r1 < r2.\n- For each row i where r1 < i < r2, there are no security devices in the ith row.\n- Laser beams are independent, i.e., one beam does not interfere nor join with another.\n\nReturn the total number of laser beams in the bank.\n*/\n\nexport function numberOfBeams(bank) {\n  let lasersCount = 0;\n  const securityDevices = [];\n\n  for (let row = 0; row < bank.length; row++) {\n    let numberOfSecurityDevices = 0;\n\n    for (let col = 0; col < bank[row].length; col++) {\n      numberOfSecurityDevices += Number(bank[row][col]);\n    }\n\n    if (numberOfSecurityDevices) {\n      securityDevices.push(numberOfSecurityDevices);\n    }\n  }\n\n  for (let i = 0; i < securityDevices.length - 1; i++) {\n    lasersCount += securityDevices[i] * securityDevices[i + 1];\n  }\n\n  return lasersCount;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/number-of-laser-beams-in-a-bank/tests/number-of-laser-beams-in-a-bank.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { numberOfBeams } from '../number-of-laser-beams-in-a-bank';\n\ndescribe('numberOfBeams', () => {\n  it('', () => {\n    expect(numberOfBeams(['011001', '000000', '010100', '001000'])).toEqual(8);\n  });\n\n  it('', () => {\n    expect(numberOfBeams(['000', '111', '000'])).toEqual(0);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/optimal-partition-of-string/optimal-partition-of-string.js",
    "content": "// https://leetcode.com/problems/optimal-partition-of-string\n\nfunction partitionString(s) {\n  let partition = [];\n  let substring = '';\n  let substringMap = new Map();\n\n  for (let index = 0; index < s.length; index++) {\n    if (substringMap.has(s[index])) {\n      partition.push(substring);\n      substring = s[index];\n      substringMap = new Map([[s[index], 1]]);\n    } else {\n      substring += s[index];\n      substringMap.set(s[index], 1);\n    }\n\n    if (index === s.length - 1) {\n      partition.push(substring);\n    }\n  }\n\n  return partition.length;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/optimal-partition-of-string/optimized-optimal-partition-of-string.js",
    "content": "// https://leetcode.com/problems/optimal-partition-of-string\n\nfunction partitionString(s) {\n  let substringMap = new Map([[s[0], 1]]);\n  let count = 1;\n\n  for (let index = 1; index < s.length; index++) {\n    if (substringMap.has(s[index])) {\n      substringMap = new Map([[s[index], 1]]);\n      count++;\n    } else {\n      substringMap.set(s[index], 1);\n    }\n  }\n\n  return count;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/pair-sum/pair-sum.js",
    "content": "/*\nIn a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1.\n\nFor example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4.\nThe twin sum is defined as the sum of a node and its twin.\n\nGiven the head of a linked list with even length, return the maximum twin sum of the linked list.\n\nInput: head = [5,4,2,1]\nOutput: 6\n\nInput: head = [4,2,2,3]\nOutput: 7\n\nInput: head = [1,100000]\nOutput: 100001\n*/\n\nexport function pairSum(list) {\n  let maximumTwin = 0;\n\n  for (let i = 0; i < Math.floor(list.length / 2); i++) {\n    maximumTwin = Math.max(maximumTwin, list[i] + list[list.length - 1 - i]);\n  }\n\n  return maximumTwin;\n}\n\nexport function pairSumLinkedList(head) {\n  const list = [];\n\n  while (head) {\n    list.push(head.val);\n    head = head.next;\n  }\n\n  return pairSum(list);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/pair-sum/tests/pair-sum.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { pairSum } from '../pair-sum';\n\ndescribe('pairSum', () => {\n  it('', () => {\n    expect(pairSum([5, 4, 2, 1])).toEqual(6);\n  });\n\n  it('', () => {\n    expect(pairSum([4, 2, 2, 3])).toEqual(7);\n  });\n\n  it('', () => {\n    expect(pairSum([1, 100000])).toEqual(100001);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/partition-array-according-to-given-pivot/partition-array-according-to-given-pivot.js",
    "content": "/*\nYou are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied:\n\nEvery element less than pivot appears before every element greater than pivot.\nEvery element equal to pivot appears in between the elements less than and greater than pivot.\nThe relative order of the elements less than pivot and the elements greater than pivot is maintained.\nMore formally, consider every pi, pj where pi is the new position of the ith element and pj is the new position of the jth element. For elements less than pivot, if i < j and nums[i] < pivot and nums[j] < pivot, then pi < pj. Similarly for elements greater than pivot, if i < j and nums[i] > pivot and nums[j] > pivot, then pi < pj.\n\nReturn nums after the rearrangement.\n*/\n\nexport function pivotArray(nums, pivot) {\n  const lessThanPivot = [];\n  const equalToPivot = [];\n  const greaterThanPivot = [];\n\n  nums.forEach((num) => {\n    if (num === pivot) {\n      equalToPivot.push(num);\n    }\n\n    if (num < pivot) {\n      lessThanPivot.push(num);\n    }\n\n    if (num > pivot) {\n      greaterThanPivot.push(num);\n    }\n  });\n\n  return [...lessThanPivot, ...equalToPivot, ...greaterThanPivot];\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/partition-array-according-to-given-pivot/tests/partition-array-according-to-given-pivot.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { pivotArray } from '../partition-array-according-to-given-pivot';\n\ndescribe('pivotArray', () => {\n  it('', () => {\n    expect(pivotArray([9, 12, 5, 10, 14, 3, 10], 10)).toEqual([\n      9, 5, 3, 10, 10, 12, 14,\n    ]);\n  });\n\n  it('', () => {\n    expect(pivotArray([-3, 4, 3, 2], 2)).toEqual([-3, 2, 4, 3]);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/permutation-in-string/permutation-in-string-sliding-window.js",
    "content": "function buildCharCount(string) {\n  let charCount = {};\n\n  for (let char of string) {\n    if (charCount[char]) {\n      charCount[char]++;\n    } else {\n      charCount[char] = 1;\n    }\n  }\n\n  return charCount;\n}\n\nfunction isPermutation(possiblePermutation, string) {\n  let charCount = buildCharCount(string);\n\n  for (let char of possiblePermutation) {\n    if (charCount[char]) {\n      charCount[char]--;\n    } else {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nfunction checkInclusion(s1, s2) {\n  for (let pointer1 = 0; pointer1 <= s2.length - s1.length; pointer1++) {\n    let pointer2 = pointer1 + s1.length;\n    let possiblePermutation = s2.substring(pointer1, pointer2);\n\n    if (isPermutation(possiblePermutation, s1)) {\n      return true;\n    }\n  }\n\n  return false;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/permutation-in-string/permutation-in-string.js",
    "content": "function buildCharCount(string) {\n  let charCount = {};\n\n  for (let char of string) {\n    if (charCount[char]) {\n      charCount[char]++;\n    } else {\n      charCount[char] = 1;\n    }\n  }\n\n  return charCount;\n}\n\nfunction isPermutation(possiblePermutation, string) {\n  let charCount = buildCharCount(string);\n\n  for (let char of possiblePermutation) {\n    if (charCount[char]) {\n      charCount[char]--;\n    } else {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nfunction checkInclusion(s1, s2) {\n  let char = s1[0];\n  let charIndices = [];\n\n  for (let index = 0; index < s2.length; index++) {\n    if (s2[index] === char) {\n      charIndices.push(index);\n    }\n  }\n\n  let possiblePermutations = [];\n\n  for (let index of charIndices) {\n    for (let pointer = 1; pointer <= s1.length; pointer++) {\n      let startIndex = index - s1.length + pointer;\n      let endIndex = index + pointer;\n      let substring = s2.substring(startIndex, endIndex);\n\n      if (substring.length === s1.length) {\n        possiblePermutations.push(substring);\n      }\n    }\n  }\n\n  for (let possiblePermutation of possiblePermutations) {\n    if (isPermutation(possiblePermutation, s1)) {\n      return true;\n    }\n  }\n\n  return false;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node-simpler.js",
    "content": "function dfs(node, next) {\n  if (!node) return;\n\n  node.next = next;\n\n  dfs(node.left, node.right);\n  dfs(node.right, next && next.left);\n}\n\nfunction connect(root) {\n  dfs(root, null);\n  return root;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.js",
    "content": "function connectHelperRight(node) {\n  if (!node) {\n    return;\n  }\n\n  connectHelper(node.left, node.right);\n  connectHelperRight(node.right);\n}\n\nfunction connectHelper(node, next) {\n  if (!node || !next) {\n    return;\n  }\n\n  node.next = next;\n\n  connectHelper(node.left, node.right);\n  connectHelper(node.right, next.left);\n}\n\nfunction connect(root) {\n  if (!root) {\n    return root;\n  }\n\n  connectHelper(root.left, root.right);\n  connectHelperRight(root.right);\n\n  return root;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/process_queries/process_queries.py",
    "content": "def process_queries(queries, m):\n    result = []\n    list_m = list(range(1, m + 1))\n\n    for index in range(len(queries)):\n        for index_m in range(len(list_m)):\n            if queries[index] == list_m[index_m]:\n                result.append(index_m)\n                list_m = [list_m[index_m]\n                          ] + list_m[:index_m] + list_m[index_m + 1:]\n                break\n\n    return result\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/product-of-array-except-self/product-of-array-except-self.js",
    "content": "function productExceptSelf(nums) {\n  let zeros = 0;\n  let answer = [];\n  let product = 1;\n\n  for (let num of nums) {\n    if (num) product *= num;\n    else zeros++;\n  }\n\n  for (let num of nums) {\n    if (num) {\n      answer.push(zeros ? 0 : product / num);\n    } else {\n      answer.push(zeros > 1 ? 0 : product);\n    }\n  }\n\n  return answer;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/rearrange-array-elements-by-sign/rearrange-array-elements-by-sign.js",
    "content": "/*\nYou are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.\n\nYou should rearrange the elements of nums such that the modified array follows the given conditions:\n\nEvery consecutive pair of integers have opposite signs.\nFor all integers with the same sign, the order in which they were present in nums is preserved.\nThe rearranged array begins with a positive integer.\nReturn the modified array after rearranging the elements to satisfy the aforementioned conditions.\n\nExample 1:\nInput: nums = [3,1,-2,-5,2,-4]\nOutput: [3,-2,1,-5,2,-4]\nExplanation:\nThe positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].\nThe only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].\nOther ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions.  \n\nExample 2:\nInput: nums = [-1,1]\nOutput: [1,-1]\nExplanation:\n1 is the only positive integer and -1 the only negative integer in nums.\nSo nums is rearranged to [1,-1].\n*/\n\nfunction isPositive(num) {\n  return num > 0;\n}\n\nexport function rearrangeArray(nums) {\n  const negative = [];\n  const positive = [];\n\n  nums.forEach((num) => {\n    if (isPositive(num)) {\n      positive.push(num);\n    } else {\n      negative.push(num);\n    }\n  });\n\n  const rearrangeArray = [];\n\n  for (let i = 0; i < negative.length; i++) {\n    rearrangeArray.push(positive[i]);\n    rearrangeArray.push(negative[i]);\n  }\n\n  return rearrangeArray;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/rearrange-array-elements-by-sign/tests/rearrange-array-elements-by-sign.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { rearrangeArray } from '../rearrange-array-elements-by-sign';\n\ndescribe('rearrangeArray', () => {\n  it('', () => {\n    expect(rearrangeArray([3, 1, -2, -5, 2, -4])).toEqual([\n      3, -2, 1, -5, 2, -4,\n    ]);\n  });\n\n  it('', () => {\n    expect(rearrangeArray([-1, 1])).toEqual([1, -1]);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/reduce_array_size_to_the_half/reduce_array_size_to_the_half.py",
    "content": "# https://leetcode.com/problems/reduce-array-size-to-the-half\n\n'''\nTime Complexity: O(NlogN)\nSpace Complexity: O(N)\n'''\n\ndef min_set_size(arr):\n    num_to_count, counts, min_size, current_length = {}, [], 0, len(arr)\n    \n    for num in arr:\n        if num in num_to_count:\n            num_to_count[num] += 1\n        else:\n            num_to_count[num] = 1\n        \n    for num in num_to_count:\n        counts.append(num_to_count[num])\n        \n    counts = reversed(sorted(counts))\n    \n    if len(arr) % 2 == 0:\n        cut = len(arr) / 2\n    else:\n        cut = len(arr + 1) / 2\n        \n    for count in counts:\n        min_size += 1\n        current_length -= count\n        \n        if current_length <= cut:\n            return min_size\n        \n    return min_size\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list-fast-slow.js",
    "content": "function removeNthFromEnd(head, n) {\n  fast = head;\n  slow = head;\n\n  while (n) {\n    fast = fast.next;\n    n--;\n  }\n\n  if (!fast) {\n    return head.next;\n  }\n\n  while (fast.next) {\n    fast = fast.next;\n    slow = slow.next;\n  }\n\n  slow.next = slow.next.next;\n\n  return head;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.js",
    "content": "/**\n * function ListNode(val, next) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.next = (next===undefined ? null : next)\n * }\n */\n\nfunction countNodes(head) {\n  let count = 0;\n\n  while (head) {\n    count++;\n    head = head.next;\n  }\n\n  return count;\n}\n\nfunction removeNthFromEnd(head, n) {\n  let count = countNodes(head);\n  let nth = count - n;\n  let node = head;\n\n  if (nth === 0) {\n    head = head.next;\n    return head;\n  }\n\n  while (node) {\n    if (nth === 1) {\n      node.next = node.next.next;\n    }\n\n    nth--;\n    node = node.next;\n  }\n\n  return head;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/rotate-array/rotate-array-optimized.js",
    "content": "function reverseInPlace(nums, start, end) {\n  while (start < end) {\n    let temporaryStart = nums[start];\n    nums[start] = nums[end];\n    nums[end] = temporaryStart;\n    start++;\n    end--;\n  }\n}\n\nfunction rotate(nums, k) {\n  if (k <= 0) {\n    return;\n  }\n\n  let start = 0;\n  let end = nums.length - 1;\n  let limit = k % nums.length;\n\n  reverseInPlace(nums, start, end - limit);\n  reverseInPlace(nums, end - limit + 1, end);\n  reverseInPlace(nums, start, end);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/rotate-array/rotate-array.js",
    "content": "function rotate(nums, k) {\n  let count = 0;\n\n  while (count < k) {\n    const num = nums.pop();\n    nums.unshift(num);\n    count++;\n  }\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/rotate-image/rotate-image.js",
    "content": "function setupMatrix(matrix) {\n  const newMatrix = [];\n\n  for (let row = 0; row < matrix.length; row++) {\n    const newRow = [];\n\n    for (let col = 0; col < matrix[row].length; col++) {\n      newRow.push(matrix[row][col]);\n    }\n\n    newMatrix.push(newRow);\n  }\n\n  return newMatrix;\n}\n\nfunction rotateBorder(newMatrix, matrix, minRow, minCol, maxRow, maxCol) {\n  if (minRow >= maxRow && minCol >= maxCol) {\n    return;\n  }\n\n  // top\n  let row = minRow;\n\n  for (let col = minCol; col <= maxCol; col++) {\n    const value = newMatrix[minRow][col];\n    matrix[row][maxCol] = value;\n    row++;\n  }\n\n  // right\n  let col = maxCol;\n\n  for (let row = minRow; row <= maxRow; row++) {\n    const value = newMatrix[row][maxCol];\n    matrix[maxRow][col] = value;\n    col--;\n  }\n\n  // bottom\n  row = minRow;\n\n  for (let col = minCol; col <= maxCol; col++) {\n    const value = newMatrix[maxRow][col];\n    matrix[row][minCol] = value;\n    row++;\n  }\n\n  // left\n  col = maxCol;\n\n  for (let row = minRow; row <= maxRow; row++) {\n    const value = newMatrix[row][minCol];\n    matrix[minRow][col] = value;\n    col--;\n  }\n\n  rotateBorder(\n    newMatrix,\n    matrix,\n    minRow + 1,\n    minCol + 1,\n    maxRow - 1,\n    maxCol - 1\n  );\n}\n\nfunction rotate(matrix) {\n  const newMatrix = setupMatrix(matrix);\n  const minRow = 0;\n  const minCol = 0;\n  const maxRow = matrix.length - 1;\n  const maxCol = matrix[0].length - 1;\n\n  rotateBorder(newMatrix, matrix, minRow, minCol, maxRow, maxCol);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/search-a-2d-matrix/search-a-2d-matrix.js",
    "content": "function getMiddle(start, end) {\n  return Math.floor((start + end) / 2);\n}\n\nfunction binarySearch(list, target) {\n  let start = 0;\n  let end = list.length - 1;\n  let middle = getMiddle(start, end);\n\n  while (start <= end) {\n    if (list[middle] === target) {\n      return true;\n    } else if (list[middle] > target) {\n      end = middle - 1;\n      middle = getMiddle(start, end);\n    } else {\n      start = middle + 1;\n      middle = getMiddle(start, end);\n    }\n  }\n\n  return false;\n}\n\nfunction searchMatrix(matrix, target) {\n  let targetRow;\n\n  for (let rowIndex = 0; rowIndex < matrix.length; rowIndex++) {\n    let rowFirstNum = matrix[rowIndex][0];\n    let rowLastNum = matrix[rowIndex][matrix[rowIndex].length - 1];\n\n    if (target >= rowFirstNum && target <= rowLastNum) {\n      targetRow = rowIndex;\n    }\n  }\n\n  return matrix[targetRow] ? binarySearch(matrix[targetRow], target) : false;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/search-a-2d-matrix/search-a-2d-matrix.py",
    "content": "# https://leetcode.com/problems/search-a-2d-matrix\n\n'''\nRuntime Complexity: O(logNM)\nSpace Complexity: O(1)\n'''\n\ndef search_matrix(matrix, target):\n    rows, columns = len(matrix), len(matrix[0])\n    start, end = 0, rows * columns - 1\n\n    while start <= end:\n        middle = (start + end) // 2\n        number = matrix[middle // columns][middle % columns]\n        \n        if number == target:\n            return True\n        \n        if target < number:\n            end = middle - 1\n        else:\n            start = middle + 1\n            \n    return False\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/search-a-2d-matrix-ii/search-a-2d-matrix-ii.py",
    "content": "# https://leetcode.com/problems/search-a-2d-matrix-ii\n\n'''\nRuntime Complexity: O(NlogM), where N is the number of rows and M is the number of columns\nSpace Complexity: O(1)\n'''\n\ndef search_matrix(matrix, target):\n    for row in matrix:\n        if target_in_row(row, target):\n            return True\n        \n    return False\n\ndef target_in_row(array, target):\n    start, end = 0, len(array) - 1\n    \n    while start <= end:\n        middle = (start + end) // 2\n        number = array[middle]\n        \n        if number == target:\n            return True\n        \n        if number > target:\n            end = middle - 1\n        else:\n            start = middle + 1\n            \n    return False"
  },
  {
    "path": "coding_interviews/leetcode/medium/set-matrix-zeroes/set-matrix-zeroes.js",
    "content": "function updateRow(matrix, row, visited) {\n  for (let col = 0; col < matrix[row].length; col++) {\n    if (matrix[row][col]) {\n      matrix[row][col] = 0;\n      visited[`${row}-${col}`] = true;\n    }\n  }\n}\n\nfunction updateCol(matrix, col, visited) {\n  for (let row = 0; row < matrix.length; row++) {\n    if (matrix[row][col]) {\n      matrix[row][col] = 0;\n      visited[`${row}-${col}`] = true;\n    }\n  }\n}\n\nfunction setZeroes(matrix) {\n  let visited = {};\n\n  for (let row = 0; row < matrix.length; row++) {\n    for (let col = 0; col < matrix[row].length; col++) {\n      let cell = matrix[row][col];\n\n      if (cell === 0 && !visited[`${row}-${col}`]) {\n        if (!visited[`row-${row}`]) {\n          updateRow(matrix, row, visited);\n        }\n\n        if (!visited[`col-${col}`]) {\n          updateCol(matrix, col, visited);\n        }\n\n        visited[`row-${row}`] = true;\n        visited[`col-${col}`] = true;\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/sort-the-students-by-their-kth-score/sort-the-students-by-their-kth-score.js",
    "content": "function sortTheStudents(score, k) {\n  let column = [];\n  let sortedScores = [];\n\n  for (let row = 0; row < score.length; row++) {\n    column.push([row, score[row][k]]);\n  }\n\n  column.sort((pair1, pair2) => pair2[1] - pair1[1]);\n\n  for (let [row] of column) {\n    sortedScores.push(score[row]);\n  }\n\n  return sortedScores;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/sort_the_matrix_diagonally/sort_the_matrix_diagonally.py",
    "content": "def diagonal_sort(mat):\n    for column in range(len(mat[0]) - 1):\n        diagonal_list = []\n        col = column\n\n        for row in range(len(mat)):\n            diagonal_list.append(mat[row][col])\n            col += 1\n\n            if col >= len(mat[0]):\n                break\n\n        diagonal_list = sorted(diagonal_list)\n        col = column\n\n        for row in range(len(mat)):\n            mat[row][col] = diagonal_list[row]\n            col += 1\n\n            if col >= len(mat[0]):\n                break\n\n    for row in range(1, len(mat)):\n        diagonal_list = []\n        r = row\n\n        for column in range(len(mat[0])):\n            diagonal_list.append(mat[r][column])\n            r += 1\n\n            if r >= len(mat):\n                break\n\n        diagonal_list = sorted(diagonal_list)\n        r = row\n\n        for column in range(len(mat[0])):\n            mat[r][column] = diagonal_list[column]\n            r += 1\n\n            if r >= len(mat):\n                break\n\n    return mat\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/string-compression/string-compression-copy.js",
    "content": "// https://leetcode.com/problems/string-compression\n\nfunction compress(chars) {\n  let counter = 1;\n  let result = [];\n\n  for (let index = 0; index < chars.length - 1; index++) {\n    if (chars[index] === chars[index + 1]) counter++;\n    else {\n      result.push(chars[index]);\n      if (counter > 1) result.push(...counter.toString());\n      counter = 1;\n    }\n\n    if (index + 1 === chars.length - 1) {\n      result.push(chars[index + 1]);\n      if (counter > 1) result.push(...counter.toString());\n    }\n  }\n\n  return result.length;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/string-compression/string-compression.js",
    "content": "// https://leetcode.com/problems/string-compression\n\nfunction compress(chars) {\n  let index = 0,\n    p1 = 0;\n\n  while (p1 < chars.length) {\n    let p2 = p1;\n\n    while (p2 < chars.length && chars[p1] === chars[p2]) {\n      p2++;\n    }\n\n    let count = p2 - p1;\n    chars[index++] = chars[p1];\n\n    if (count > 1) {\n      let countString = count.toString();\n\n      for (let char of countString) {\n        chars[index++] = char;\n      }\n    }\n\n    p1 = p2;\n  }\n\n  while (chars.length > index) {\n    chars.pop();\n  }\n\n  return chars.length;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/subrectangle_queries/subrectangle_queries.py",
    "content": "# https://leetcode.com/problems/subrectangle-queries\n\n\nclass SubrectangleQueries:\n    def __init__(self, rectangle):\n        self.rectangle = rectangle\n\n    def updateSubrectangle(self, row1, col1, row2, col2, newValue):\n        for row in range(row1, row2 + 1):\n            for col in range(col1, col2 + 1):\n                self.rectangle[row][col] = newValue\n\n    def getValue(self, row, col):\n        return self.rectangle[row][col]\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/sum_of_nodes/sum_of_nodes.py",
    "content": "# https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent\n\n'''\nGiven a binary tree, return the sum of values of nodes with even-valued grandparent.\n(A grandparent of a node is the parent of its parent, if it exists.)\n\nIf there are no nodes with an even-valued grandparent, return 0.\n'''\n\n\ndef sum_even_grandparent(node):\n    left = 0\n    right = 0\n\n    if node.left and node.left.left and node.val % 2 == 0:\n        left += node.left.left.val\n\n    if node.left and node.left.right and node.val % 2 == 0:\n        left += node.left.right.val\n\n    if node.left:\n        left += sum_even_grandparent(node.left)\n\n    if node.right and node.right.left and node.val % 2 == 0:\n        right += node.right.left.val\n\n    if node.right and node.right.right and node.val % 2 == 0:\n        right += node.right.right.val\n\n    if node.right:\n        right += sum_even_grandparent(node.right)\n\n    return right + left\n\n\ndef sum_even_grandparent_2(node):\n    return helper(node, 1, 1)\n\n\ndef helper(node, parent, grandparent):\n    if node is None:\n        return 0\n\n    return helper(node.left, node.val, parent) \\\n        + helper(node.right, node.val, parent) \\\n        + (node.val if grandparent % 2 == 0 else 0)\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted-2.js",
    "content": "function twoSum(numbers, target) {\n  let start = 0;\n  let end = numbers.length - 1;\n  let result = [];\n\n  while (start < end) {\n    let sum = numbers[start] + numbers[end];\n\n    if (sum === target) {\n      result.push(start + 1);\n      result.push(end + 1);\n      break;\n    }\n\n    if (sum > target) end--;\n    else start++;\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.js",
    "content": "function twoSum(numbers, target) {\n  let numberMap = {};\n\n  for (let index = 0; index < numbers.length; index++) {\n    let number = numbers[index];\n    numberMap[number] = index + 1;\n  }\n\n  let index1;\n  let index2;\n\n  for (let index = 0; index < numbers.length; index++) {\n    let remainder = target - numbers[index];\n    let remaindersIndex = numberMap[remainder];\n\n    if (remaindersIndex) {\n      index1 = index + 1;\n      index2 = remaindersIndex;\n      return [index1, index2];\n    }\n  }\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/valid-sudoku/valid-sudoku.js",
    "content": "function isValidRow(board, row) {\n  let allNumbersInRow = new Set();\n  let countOfNumbersInRow = 0;\n\n  for (let index = 0; index <= 8; index++) {\n    let num = board[row][index];\n\n    if (num !== '.') {\n      allNumbersInRow.add(num);\n      countOfNumbersInRow++;\n    }\n  }\n\n  return allNumbersInRow.size === countOfNumbersInRow;\n}\n\nfunction isValidCol(board, col) {\n  let allNumbersInCol = new Set();\n  let countOfNumbersInCol = 0;\n\n  for (let index = 0; index <= 8; index++) {\n    let num = board[index][col];\n\n    if (num !== '.') {\n      allNumbersInCol.add(num);\n      countOfNumbersInCol++;\n    }\n  }\n\n  return allNumbersInCol.size === countOfNumbersInCol;\n}\n\nfunction isValidSquare(board, row, col) {\n  let allNumbersInSquare = new Set();\n  let countOfNumbersInSquare = 0;\n\n  for (let rowIndex = row; rowIndex <= row + 2; rowIndex++) {\n    for (let colIndex = col; colIndex <= col + 2; colIndex++) {\n      let num = board[rowIndex][colIndex];\n\n      if (num !== '.') {\n        allNumbersInSquare.add(num);\n        countOfNumbersInSquare++;\n      }\n    }\n  }\n\n  return allNumbersInSquare.size === countOfNumbersInSquare;\n}\n\nfunction isValidSudoku(board) {\n  let isValid = true;\n\n  for (let row = 0; row <= 8; row++) {\n    isValid = isValid && isValidRow(board, row);\n  }\n\n  for (let col = 0; col <= 8; col++) {\n    isValid = isValid && isValidCol(board, col);\n  }\n\n  for (let col = 0; col <= 6; col += 3) {\n    for (let row = 0; row <= 6; row += 3) {\n      isValid = isValid && isValidSquare(board, row, col);\n    }\n  }\n\n  return isValid;\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/validate-binary-search-tree/validate-binary-search-tree-2.js",
    "content": "function isValidBST(node, min = -Infinity, max = Infinity) {\n  if (!node) return true;\n  if (node.val <= min || node.val >= max) return false;\n  return (\n    isValidBST(node.left, min, node.val) &&\n    isValidBST(node.right, node.val, max)\n  );\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/validate-binary-search-tree/validate-binary-search-tree-almost-right.js",
    "content": "function isValidLeft(node, left) {\n  return node.val > left.val;\n}\n\nfunction isValidRight(node, right) {\n  return node.val < right.val;\n}\n\nfunction isValid(node, left, right) {\n  return isValidLeft(node, left) && isValidRight(node, right);\n}\n\nfunction compareNodeAndChildren(node, left, right) {\n  if (left && right) {\n    return (\n      isValid(node, left, right) &&\n      compareNodeAndChildren(left, left.left, left.right) &&\n      compareNodeAndChildren(right, right.left, right.right)\n    );\n  }\n\n  if (left) {\n    return (\n      isValidLeft(node, left) &&\n      compareNodeAndChildren(left, left.left, left.right)\n    );\n  }\n\n  if (right) {\n    return (\n      isValidRight(node, right) &&\n      compareNodeAndChildren(right, right.left, right.right)\n    );\n  }\n\n  return true;\n}\n\nfunction isValidBST(root) {\n  return compareNodeAndChildren(root, root.left, root.right);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/validate-binary-search-tree/validate-binary-search-tree.js",
    "content": "function toList(node, treeList) {\n  if (!node) {\n    return;\n  }\n\n  treeList.push(node.val);\n\n  toList(node.left, treeList);\n  toList(node.right, treeList);\n}\n\nfunction dfs(node, value) {\n  if (!node) {\n    return new TreeNode(value);\n  }\n\n  if (value < node.val) {\n    node.left = dfs(node.left, value);\n  } else if (value > node.val) {\n    node.right = dfs(node.right, value);\n  }\n\n  return node;\n}\n\nfunction buildTree(treeList) {\n  let root = new TreeNode(treeList[0]);\n\n  for (let value of treeList.slice(1)) {\n    dfs(root, value);\n  }\n\n  return root;\n}\n\nfunction compareTrees(node1, node2) {\n  if (!node1 && !node2) {\n    return true;\n  }\n\n  if ((node1 && !node2) || (!node1 && node2)) {\n    return false;\n  }\n\n  return (\n    node1.val === node2.val &&\n    compareTrees(node1.left, node2.left) &&\n    compareTrees(node1.right, node2.right)\n  );\n}\n\nfunction isValidBST(root) {\n  let treeList = [];\n  toList(root, treeList);\n  let newTree = buildTree(treeList);\n  return compareTrees(root, newTree);\n}\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/watering-plants/tests/watering-plants.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { wateringPlants } from '../watering-plants';\n\ndescribe('wateringPlants', () => {\n  it('', () => {\n    expect(wateringPlants([2, 2, 3, 3], 5)).toEqual(14);\n  });\n\n  it('', () => {\n    expect(wateringPlants([1, 1, 1, 4, 2, 3], 4)).toEqual(30);\n  });\n\n  it('', () => {\n    expect(wateringPlants([7, 7, 7, 7, 7, 7, 7], 8)).toEqual(49);\n  });\n\n  it('', () => {\n    expect(wateringPlants([2, 1], 2)).toEqual(4);\n  });\n\n  it('', () => {\n    expect(wateringPlants([3, 2, 4, 2, 1], 6)).toEqual(17);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/leetcode/medium/watering-plants/watering-plants.js",
    "content": "/*\nYou want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. There is a river at x = -1 that you can refill your watering can at.\n\nEach plant needs a specific amount of water. You will water the plants in the following way:\n\nWater the plants in order from left to right.\nAfter watering the current plant, if you do not have enough water to completely water the next plant, return to the river to fully refill the watering can.\nYou cannot refill the watering can early.\nYou are initially at the river (i.e., x = -1). It takes one step to move one unit on the x-axis.\n\nGiven a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants.\n\nExample 1:\nInput: plants = [2,2,3,3], capacity = 5\nOutput: 14\n\nExample 2:\nInput: plants = [1,1,1,4,2,3], capacity = 4\nOutput: 30\n\nExample 3:\nInput: plants = [7,7,7,7,7,7,7], capacity = 8\nOutput: 49\n*/\n\n// [2, 2, 3, 3]\n// capacity: 5 -> 3 -> 1\n// steps:    1 -> 2 -> 4\n\nexport function wateringPlants(plants, capacity) {\n  let steps = 0;\n  const CAPACITY = capacity;\n\n  for (let i = 0; i < plants.length; i++) {\n    steps++;\n    capacity -= plants[i];\n\n    if (i < plants.length - 1 && capacity < plants[i + 1]) {\n      steps += i + 1;\n      steps += i + 1;\n      capacity = CAPACITY;\n    }\n  }\n\n  return steps;\n}\n"
  },
  {
    "path": "coding_interviews/python/string.py",
    "content": "# length of a string\nlen('a string') # 8\n\n# concatenate strings\ns1 = 'string 1'\ns2 = 'string 2'\ns3 = s1 + s2 # 'string 1string 2'\n\n# indexing\ns1 = 'string 1'\ns1[3] # 'i'\n\n# slicing\ns1 = 'string 1'\ns1[:3] # 'str'\ns1[2:] # 'ring 1'\n\n# striping a string\ns = '  a string   '\ns.strip() # 'a string'\n\n# string in string\ns1 = 'string 1'\ns2 = 'string'\ns3 = 'other'\ns2 in s1 # True\ns3 in s1 # False\n"
  },
  {
    "path": "coding_interviews/top-problems/are-anagrams.js",
    "content": "// Time Complexity: O(N) where N is the size of the string\n// more precisely, it should be O(N1) + O(N2) where N1 = length of string1 and N2 = length of string2\n// Space Complexity: O(N) where N is the size of the string\n\nfunction hasDifferentLengths(string1, string2) {\n  return string1.length !== string2.length;\n}\n\nfunction buildCharsCount(string) {\n  let charactersCounter = {};\n\n  for (let char of string) {\n    if (charactersCounter[char]) {\n      charactersCounter[char]++;\n    } else {\n      charactersCounter[char] = 1;\n    }\n  }\n\n  return charactersCounter;\n}\n\nexport function areAnagrams(string1, string2) {\n  if (hasDifferentLengths(string1, string2)) return false;\n\n  let charactersCounter1 = buildCharsCount(string1);\n  let charactersCounter2 = buildCharsCount(string2);\n\n  for (let char of Object.keys(charactersCounter1)) {\n    if (charactersCounter1[char] !== charactersCounter2[char]) {\n      return false;\n    }\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "coding_interviews/top-problems/first-and-last-index.js",
    "content": "/*\nGiven a sorted array of integers `arr` and an integer target,\nfind the index of the first and last position of target in `arr`.\nIn target can't be found in `arr`, return [-1, -1]\n*/\n\n// Runtime: O(N)\n// Space: O(1)\n\nexport function firstAndLastIndex(list, target) {\n  let first = -1;\n  let last = -1;\n\n  for (let index = 0; index < list.length; index++) {\n    if (list[index] === target) {\n      first = index;\n      break;\n    }\n  }\n\n  for (let index = list.length; index >= 0; index--) {\n    if (list[index] === target) {\n      last = index;\n      break;\n    }\n  }\n\n  return [first, last];\n}\n\n// Runtime: O(logN)\n// Space: O(1)\n\nfunction getMiddle(start, end) {\n  return Math.floor((start + end) / 2);\n}\n\nfunction findIndex(list, target, type) {\n  let start = 0;\n  let end = list.length - 1;\n  let middle = getMiddle(start, end);\n  let index = -1;\n\n  while (start <= end) {\n    if (target > list[middle]) {\n      start = middle + 1;\n      middle = getMiddle(start, end);\n    }\n\n    if (target < list[middle]) {\n      end = middle - 1;\n      middle = getMiddle(start, end);\n    }\n\n    if (target === list[middle]) {\n      index = middle;\n\n      if (type === 'findFirst') {\n        end = middle - 1;\n      }\n\n      if (type === 'findLast') {\n        start = middle + 1;\n      }\n\n      middle = getMiddle(start, end);\n    }\n  }\n\n  return index;\n}\n\nfunction findFirstIndex(list, target) {\n  return findIndex(list, target, 'findFirst');\n}\n\nfunction findLastIndex(list, target) {\n  return findIndex(list, target, 'findLast');\n}\n\nexport function firstAndLastIndexBinarySearch(list, target) {\n  return [findFirstIndex(list, target), findLastIndex(list, target)];\n}\n"
  },
  {
    "path": "coding_interviews/top-problems/kth-largest.js",
    "content": "// Given an array of integers `arr` and an integer `k`, find the kth largest element\n\n// Runtime: O(NlogN)\n// Space: O(1)\nexport function kthLargest(list, k) {\n  return list.sort((num1, num2) => num1 - num2)[list.length - k];\n}\n"
  },
  {
    "path": "coding_interviews/top-problems/min-sliding-window.js",
    "content": "function buildCharsCounter(s) {\n  let charsCounter = {};\n\n  for (let char of s) {\n    if (charsCounter[char]) {\n      charsCounter[char]++;\n    } else {\n      charsCounter[char] = 1;\n    }\n  }\n\n  return charsCounter;\n}\n\nfunction compare(s1, s2) {\n  let chars1 = buildCharsCounter(s1);\n  let chars2 = buildCharsCounter(s2);\n\n  for (let [char, counter] of Object.entries(chars1)) {\n    if (chars2[char] == undefined || chars2[char] > counter) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nfunction minSlidingWindow(s, t) {\n  for (let i = 0; i < s.length - t.length; i++) {\n    for (let j = i + t.length; j < s.length; j++) {\n      const substring = s.slice(i, j);\n    }\n  }\n}\n\nminSlidingWindow('adcfebeceabebadfcdfcbfcbead', 'abca');\n"
  },
  {
    "path": "coding_interviews/top-problems/tests/are-anagrams.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { areAnagrams } from '../are-anagrams';\n\ndescribe('areAnagrams', () => {\n  it('', () => {\n    expect(areAnagrams('', '')).toBeTruthy();\n  });\n\n  it('', () => {\n    expect(areAnagrams('a', 'a')).toBeTruthy();\n  });\n\n  it('', () => {\n    expect(areAnagrams('bla', 'alb')).toBeTruthy();\n  });\n\n  it('', () => {\n    expect(areAnagrams('hahahehe', 'hehehaha')).toBeTruthy();\n  });\n\n  it('', () => {\n    expect(areAnagrams('a', 'b')).toBeFalsy();\n  });\n\n  it('', () => {\n    expect(areAnagrams('aa', 'a')).toBeFalsy();\n  });\n\n  it('', () => {\n    expect(areAnagrams('bla', 'elb')).toBeFalsy();\n  });\n\n  it('', () => {\n    expect(areAnagrams(' ', '  ')).toBeFalsy();\n  });\n});\n"
  },
  {
    "path": "coding_interviews/top-problems/tests/first-and-last-index.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport {\n  firstAndLastIndex,\n  firstAndLastIndexBinarySearch,\n} from '../first-and-last-index';\n\ndescribe('firstAndLastIndex', () => {\n  it('', () => {\n    expect(firstAndLastIndex([1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9], 5)).toEqual([\n      5, 7,\n    ]);\n  });\n\n  it('', () => {\n    expect(firstAndLastIndex([1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9], 4)).toEqual([\n      4, 4,\n    ]);\n  });\n\n  it('', () => {\n    expect(firstAndLastIndex([1, 1, 2, 3, 4, 5, 5, 5, 6, 8, 9], 7)).toEqual([\n      -1, -1,\n    ]);\n  });\n});\n\ndescribe('firstAndLastIndexBinarySearch', () => {\n  it('', () => {\n    expect(\n      firstAndLastIndexBinarySearch([1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9], 5)\n    ).toEqual([5, 7]);\n  });\n\n  it('', () => {\n    expect(\n      firstAndLastIndexBinarySearch([1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9], 4)\n    ).toEqual([4, 4]);\n  });\n\n  it('', () => {\n    expect(\n      firstAndLastIndexBinarySearch([1, 1, 2, 3, 4, 5, 5, 5, 6, 8, 9], 7)\n    ).toEqual([-1, -1]);\n  });\n});\n"
  },
  {
    "path": "coding_interviews/top-problems/tests/kth-largest.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { kthLargest } from '../kth-largest';\n\ndescribe('kthLargest', () => {\n  it('', () => {\n    expect(kthLargest([4, 2, 9, 7, 5, 6, 7, 1, 3], 4)).toEqual(6);\n  });\n});\n"
  },
  {
    "path": "college/graph/atoms.py",
    "content": "import networkx as nx\nimport matplotlib.pyplot as plt\n\ndef plot_graph(graph, pos, title):\n    plt.figure(figsize=(6, 6))\n    nx.draw(graph, pos, with_labels=True, node_color='lightblue', node_size=2000, font_size=12, font_weight='bold', edge_color='gray')\n    plt.title(title)\n    plt.show()\n\n\n# H₂O\n# Adiciona vértices e conectas os átomos com arestas\n# Define as posições de cada átomo\n# Plota o grafo de água\nwater = nx.Graph()\nwater.add_nodes_from(['O', 'H1', 'H2'])\nwater.add_edges_from([('O', 'H1'), ('O', 'H2')])\nwater_pos = {'O': (0, 0), 'H1': (-1, -1), 'H2': (1, -1)}\nplot_graph(water, water_pos, '(H2O)')\n\n# CO₂\n# Adiciona vértices e conectas os átomos com arestas\n# Define as posições de cada átomo\n# Plota o grafo de CO₂\nco2 = nx.Graph()\nco2.add_nodes_from(['C', 'O1', 'O2'])\nco2.add_edges_from([('C', 'O1'), ('C', 'O2')])\nco2_pos = {'C': (0, 0), 'O1': (-1, 0), 'O2': (1, 0)}\nplot_graph(co2, co2_pos, '(CO2)')"
  },
  {
    "path": "college/web/css/estilos.css",
    "content": "body {\n  background-color: #f7f9ac;\n}\n\nh1 {\n  color: green;\n  text-align: center;\n}\n\np.corpoDoTexto {\n  color: blue;\n}\n\np.corpoDoTexto2 {\n  color: red;\n}\n"
  },
  {
    "path": "college/web/css/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <meta charset=\"utf-8\" />\n    <title>CSS</title>\n    <link rel=\"stylesheet\" href=\"./estilos.css\" />\n  </head>\n  <body>\n    <h1>Título título título</h1>\n    <p class=\"corpoDoTexto\">\n      Lorem Ipsum is simply dummy text of the printing and typesetting industry.\n    </p>\n    <p class=\"corpoDoTexto2\">\n      Lorem Ipsum is simply dummy text of the printing and typesetting industry.\n    </p>\n  </body>\n</html>\n"
  },
  {
    "path": "college/web/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <meta charset=\"utf-8\" />\n    <title>Título da página</title>\n  </head>\n  <body>\n    <h1>Título Principal - H1</h1>\n    <h2>Sub-título H2</h2>\n    <h3>Sub-título H3</h3>\n    <h4>Sub-título H4</h4>\n    <h5>Sub-título H5</h5>\n    <h5>Sub-título H6</h5>\n    <p>Testando o parágrafo</p>\n  </body>\n</html>\n"
  },
  {
    "path": "college/web/js.js",
    "content": "Math.max(1, 2); // 2\nMath.min(1, 2); // 1\nMath.pow(2, 2); // 4\nMath.sqrt(4); // 2\n"
  },
  {
    "path": "college/web/loop.js",
    "content": "let matrix = [];\n\nfor (let row = 1; row <= 4; row++) {\n  let nums = [];\n  let num = row + 1;\n\n  for (let col = 1; col <= 5; col++) {\n    nums.push(num);\n    num += row + 1;\n  }\n\n  matrix.push(nums);\n}\n\nconsole.log(matrix);\n"
  },
  {
    "path": "competitive-programming/4clojure/problem01.clj",
    "content": "; http://www.4clojure.com/problem/1\n(= true true)\n"
  },
  {
    "path": "competitive-programming/4clojure/problem02.clj",
    "content": "; http://www.4clojure.com/problem/2\n(= (- 10 (* 2 3)) 4)\n"
  },
  {
    "path": "competitive-programming/4clojure/problem03.clj",
    "content": "; http://www.4clojure.com/problem/3#prob-title\n(= \"HELLO WORLD\" (.toUpperCase \"hello world\"))\n"
  },
  {
    "path": "competitive-programming/4clojure/problem04.clj",
    "content": ";; http://www.4clojure.com/problem/4\n\n(= (list :a :b :c) '(:a :b :c))\n"
  },
  {
    "path": "competitive-programming/4clojure/problem05.clj",
    "content": ";; http://www.4clojure.com/problem/5#prob-title\n\n(= '(1 2 3 4) (conj '(2 3 4) 1))\n(= '(1 2 3 4) (conj '(3 4) 2 1))\n"
  },
  {
    "path": "competitive-programming/4clojure/problem06.clj",
    "content": ";; http://www.4clojure.com/problem/6\n\n(= [:a :b :c] (list :a :b :c) (vec '(:a :b :c)) (vector :a :b :c))\n"
  },
  {
    "path": "competitive-programming/4clojure/problem07.clj",
    "content": ";; http://www.4clojure.com/problem/7\n\n(= [1 2 3 4] (conj [1 2 3] 4))\n(= [1 2 3 4] (conj [1 2] 3 4))\n"
  },
  {
    "path": "competitive-programming/4clojure/problem19.clj",
    "content": "; http://www.4clojure.com/problem/19\n\n; Solution 1\n(fn [coll]\n  (loop [item (first coll)\n         coll coll]\n    (if (empty? (rest coll))\n      item\n      (recur (first (rest coll)) (rest coll)))))\n\n; Solution 2\n(fn [coll]\n  (first (reverse coll)))\n\n; Solution 3\n#(first (reverse %))\n\n; Solution 4\n(comp first reverse)\n\n; Solution 5\n(fn [coll]\n  (-> coll\n      reverse\n      first))\n\n; Solution 6\n(fn [coll]\n  (loop [[item & remaining] coll]\n    (if (empty? remaining)\n      item\n      (recur remaining))))\n"
  },
  {
    "path": "competitive-programming/4clojure/problem20.clj",
    "content": "; http://www.4clojure.com/problem/20\n\n(comp second reverse)\n"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2011/armstrong.cpp",
    "content": "#include <stdio.h>\n#include <math.h>\n#include <string>\n#include <vector>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\n    long int n;\n    scanf(\"%li\", &n);\n    vector<int> vetor;\n\n    while (n != 0) {\n\n        int total = 0, temp = n, teste, result=0;\n\n        while (temp != 0) {\n            teste = temp % 10;\n            vetor.push_back(teste);\n            temp = temp / 10;\n        }\n\n        for (int i = 2; i < 10; i++) {\n            total = 0;\n            for (int j = 0; j < vetor.size(); j++) {\n                total += pow(vetor[j], i);\n            }\n\n            if (total == n) {\n                result = i;\n                break;\n            }\n        }\n\n        if (result)\n            cout << result << endl;\n        else\n            cout << \"N\" << endl;\n\n    \tscanf(\"%li\", &n);\n        vetor.clear();\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2011/calculadora.cpp",
    "content": "#include<stdio.h>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\n    int ip1[4];\n    int ip2[4];\n    int mas[4];\n    \n\n    while (scanf(\"%i.%i.%i.%i %i.%i.%i.%i %i.%i.%i.%i\", &ip1[0],&ip1[1],&ip1[2],&ip1[3],&ip2[0],&ip2[1],&ip2[2],&ip2[3],&mas[0],&mas[1],&mas[2],&mas[3]) != -1) {\n        int r = 1;\n        int i = 0;\n        for (i = 0; i < 4; i++)\n        {\n        \tif ((ip1[i] & mas[i]) != (ip2[i] & mas[i]))\n        \t\tr = 0;\n        }\n\n        if (r)\n        \tcout << \"S\" << endl;\n       \telse\n       \t\tcout << \"N\" << endl;\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2011/cartoes.cpp",
    "content": "#include <vector>\n#include <iostream>\n\nusing namespace std;\n\nint is_alberto_turn(int counter) {\n  if (counter % 2 == 0)\n    return 1;\n\n  return 0;\n}\n\nint main() {\n\n  int n, temp;\n  vector<int> v, vetor_a;\n\n  cin >> n;\n\n  for (int i = 0; i < n; i++) {\n    cin >> temp;\n    v.push_back(temp);\n  }\n\n  for (int i = 0; i < n; i++) {\n\n    if (is_alberto_turn(i)) {\n      if (v[0] > v.back()) {\n        vetor_a.push_back(v[0]);\n        v.erase(v.begin());\n      } else {\n        vetor_a.push_back(v.back());\n        v.pop_back();\n      }\n    } else if (v.size() > 1) {\n      if (v[0] > v.back())\n        v.erase(v.begin());\n      else\n        v.pop_back();\n    }\n  }\n\n  int total = 0;\n\n  for (int i = 0; i < n; i++)\n    total += vetor_a[i];\n\n  cout << total << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2011/concurso.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <stdio.h>\n\nusing namespace std;\n\nint main() {\n\tint n, l, c, result;\n\tstring conto;\n\n\twhile (scanf(\"%d %d %d\", &n, &l, &c) != EOF) {\n\t\tcin.ignore();\n\t\tgetline(cin, conto);\n\n\t\tif (conto.size() == (l * c)) result = 1;\n\t\telse result = (conto.size() / (l * c)) + 1;\n\n\t\tcout << result << endl;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2011/coral.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <ctype.h>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nbool is_integer(float k) {\n  return std::floor(k) == k;\n}\n\nbool all_equal(vector<int> &vetorzin) {\n  sort(vetorzin.begin(), vetorzin.end());\n\n  return (vetorzin[0] == vetorzin.back());\n}\n\nint main() {\n\n  int n, temp;\n  float total=0;\n  vector<int> v;\n\n  cin >> n;\n\n  for (int i = 0; i < n; i++) {\n    cin >> temp;\n    total += temp;\n    v.push_back(temp);\n  }\n\n  if (is_integer(total / n))\n    cout << -1 << endl;\n  else {\n    if (all_equal(v))\n      cout << 1 << endl;\n    else {\n      // algorithm to know how many times\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2011/elevador.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <string>\n#include <sstream>\n#include <stdio.h>\n\nusing namespace std;\n\nbool has_four(string number) {\n\t\n\tfor (int i = 0; i < number.length(); i++)\n\t\tif (number[i] == '4') return true;\n\n\treturn false;\n}\n\nbool has_thirteen(string number) {\t\n\n\tfor (int i = 0; i < number.length()-1; i++)\n\t\tif (number[i] == '1' && number[i+1] == '3') return true;\t\t\t\t\n\n\treturn false;\n}\n\nint main () {\n\n\tint n, total=0;\n\n\twhile (scanf(\"%d\", &n) != EOF) {\n\t\tostringstream converter;\n\t\tconverter << n;\n\t\tstring number = converter.str();\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (has_four(number) || has_thirteen(number)) total++;\n\t\t\tcout << total << endl;\n\t\t}\n\n\t\tcout << n + total << endl;\n\t\ttotal = 0;\n\t}\t\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2011/estacionamento.cpp",
    "content": "#include <vector>\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int v, p, result=0;\n\n  cin >> v >> p;\n\n  while (v + p != 0) {\n    vector<int> v1;\n    vector< vector<int> > v2;\n\n    while (p--) {\n      int he, me, hs, ms, found=0;\n      cin >> he >> me >> hs >> ms;\n      v1.push_back(he);\n      v1.push_back(me);\n      v1.push_back(hs);\n      v1.push_back(ms);\n\n      if (v > 0) {\n        v2.push_back(v1);\n        v--;\n      } else {\n        for (int i = 0; i < v2.size(); i++) {\n          if (v1[0] > v2[i][2] || (v1[0] == v2[i][2] && v1[1] > v2[i][3])) {\n            v2.push_back(v1);\n            found = 1;\n            break;\n          }\n        }\n\n        if (!found) result++;\n      }\n\n      v1.clear();\n    }\n\n    cout << result << endl;\n    cin >> v >> p;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2011/extenso.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\n// stringstream ss;\n// string num1;\n// ss << n1[0];\n// ss >> num1;\n\nvoid split(string &n1, string &n2, string number) {\n\tint dot_index = number.find(\".\");\n\tn1 = number.substr(0, dot_index);\n\tn2 = number.substr(dot_index+1, number.size()-1);\n}\n\nstring transformNumberToCents(string cents) {\n\tstring result=\"\";\n\tstring ar[] = { \"DEZ\", \"ONZE\", \"DOZE\", \"TREZE\", \"QUATORZE\", \"QUINZE\", \"DEZESSEIS\", \"DEZESSETE\", \"DEZOITO\", \"DEZENOVE\" };\n\tstring um_a_nove[] = { \"UM\", \"DOIS\", \"TRES\", \"QUATRO\", \"CINCO\", \"SEIS\", \"SETE\", \"OITO\", \"NOVE\" };\n\tvector<string> values(ar, ar + sizeof(ar)/sizeof(ar[0]));\n\tvector<string> sec_values(um_a_nove, um_a_nove + sizeof(um_a_nove)/sizeof(um_a_nove[0]));\n\n\tstringstream ss;\n\tstring num1;\n\tss << cents[0];\n\tss >> num1;\n\tint cent_unit = stoi(num1);\n\n\tif \t\t\t(cents[0] == '0') result += sec_values[cent_unit-1];\n\telse if (cents[0] == '1') result += values[cent_unit];\n\telse if (cents[0] == '2') result += \"VINTE E \"     + sec_values[cent_unit-1];\n\telse if (cents[0] == '3') result += \"TRINTA E \"    + sec_values[cent_unit-1];\n\telse if (cents[0] == '4') result += \"QUARENTA E \"  + sec_values[cent_unit-1];\n\telse if (cents[0] == '5') result += \"CINQUENTA E \" + sec_values[cent_unit-1];\n\telse if (cents[0] == '6') result += \"SESSENTA E \"  + sec_values[cent_unit-1];\n\telse if (cents[0] == '7') result += \"SETENTA E \"   + sec_values[cent_unit-1];\n\telse if (cents[0] == '8') result += \"OITENTA E \"   + sec_values[cent_unit-1];\n\telse if (cents[0] == '9') result += \"NOVENTA E \"   + sec_values[cent_unit-1];\n\n\treturn result;\n}\n\nstring transformNumberToReal(string reais) {\n\tstring result=\"\";\n\n\tstring um_a_nove[] = { \"UM\", \"DOIS\", \"TRES\", \"QUATRO\", \"CINCO\", \"SEIS\", \"SETE\", \"OITO\", \"NOVE\" };\n\tvector<string> sec_values(um_a_nove, um_a_nove + sizeof(um_a_nove)/sizeof(um_a_nove[0]));\n\n\tstring ar[] = { \"DEZ\", \"ONZE\", \"DOZE\", \"TREZE\", \"QUATORZE\", \"QUINZE\", \"DEZESSEIS\", \"DEZESSETE\", \"DEZOITO\", \"DEZENOVE\" };\n\tvector<string> values(ar, ar + sizeof(ar)/sizeof(ar[0]));\n\n\tstring dez_a_noventa[] = { \"VINTE\", \"TRINTA\", \"QUARENTA\", \"CINQUENTA\", \"SESSENTA\", \"SETENTA\", \"OITENTA\", \"NOVENTA\" };\n\tvector<string> dicker(dez_a_noventa, dez_a_noventa + sizeof(dez_a_noventa)/sizeof(dez_a_noventa[0]));\n\n\tstring cem_a_novecentos[] = { \"CENTO\", \"DUZENTOS\", \"TREZENTOS\", \"QUATROCENTOS\", \"QUINHENTOS\", \"SEICENTOS\", \"SETECENTOS\", \"OITOCENTOS\", \"NOVECENTOS\" };\n\tvector<string> hundred(cem_a_novecentos, cem_a_novecentos + sizeof(cem_a_novecentos)/sizeof(cem_a_novecentos[0]));\n\n\tif (reais.size() == 1) {\n\t\tresult += sec_values[stoi(reais)-1];\n\t}\telse if (reais.size() == 2) {\n\t\tstringstream ss; string n1, n2;\n\t\tss << reais[0]; ss >> n1;\n\t\tss << reais[1]; ss >> n2;\n\t\tif (reais[0] == '1') {\n\t\t\tresult += values[stoi(n2)];\n\t\t}\telse {\n\t\t\tresult += dicker[stoi(n1)-1] + \" E \" + sec_values[stoi(n2)-1];\n\t\t}\n\t} else if (reais.size() == 3) {\n\t\tstringstream ss; string n1, n2, n3;\n\t\tss << reais[0]; ss >> n1;\n\t\tss << reais[1]; ss >> n2;\n\t\tss << reais[2]; ss >> n3;\n\t\tresult += hundred[stoi(n1)-1] + \" E \" + dicker[stoi(n2)-1] + \" E \" + sec_values[stoi(n3)-1];\n\t}\telse if (reais.size() == 4){\n\t\tstringstream ss; string n1, n2, n3, n4;\n\t\tss << reais[0]; ss >> n1;\n\t\tss << reais[1]; ss >> n2;\n\t\tss << reais[2]; ss >> n3;\n\t\tss << reais[3]; ss >> n4;\n\t\tresult += sec_values[stoi(n1)-1] + \" MIL E \" + hundred[stoi(n2)-1] + \" E \" + dicker[stoi(n3)-1] + \" E \" + sec_values[stoi(n4)-1];\n\t}\telse if (reais.size() == 5) {\n\t\tstringstream ss; string n1, n2, n3, n4, n5;\n\t\tss << reais[0]; ss >> n1;\n\t\tss << reais[1]; ss >> n2;\n\t\tss << reais[2]; ss >> n3;\n\t\tss << reais[3]; ss >> n4;\n\t\tss << reais[4]; ss >> n5;\n\t\tif (reais[0] == '1') {\n\t\t\tresult += values[stoi(n2)] + \" MIL E \" + hundred[stoi(n3)-1] + \" E \" + dicker[stoi(n4)-1] + \" E \" + sec_values[stoi(n5)-1];\n\t\t}\telse {\n\t\t\tresult += dicker[stoi(n1)-1] + \" E \" + sec_values[stoi(n2)-1]; + \" MIL E \" + hundred[stoi(n3)-1] + \" E \" + dicker[stoi(n4)-1] + \" E \" + sec_values[stoi(n5)-1];\n\t\t}\n\t}\telse if (reais.size() == 6) {\n\t\tstringstream ss; string n1, n2, n3, n4, n5, n6;\n\t\tss << reais[0]; ss >> n1;\n\t\tss << reais[1]; ss >> n2;\n\t\tss << reais[2]; ss >> n3;\n\t\tss << reais[3]; ss >> n4;\n\t\tss << reais[4]; ss >> n5;\n\t\tss << reais[5]; ss >> n6;\n\t\tresult += hundred[stoi(n1)-1] + \" E \" + dicker[stoi(n2)-1] + \" E \" + sec_values[stoi(n3)-1] + \" MIL E\" + hundred[stoi(n4)-1] + \" E \" + dicker[stoi(n5)-1] + \" E \" + sec_values[stoi(n6)-1];\n\t}\telse {\n\t\tresult += \"UM MILHAO\";\n\t}\n\n\treturn result;\n}\n\nint main() {\n\n\tstring number;\n\tcin >> number;\n\n\twhile(number != \"0.00\") {\n\t\tstring n1, n2, result=\"\";\n\n\t\tsplit(n1, n2, number);\n\n\t\tn1 = transformNumberToReal(n1);\n\t\tn2 = transformNumberToCents(n2);\n\n\t\tif (n1 == \"0\") {\n\t\t\tif (n2 == \"01\")\n\t\t\t\tresult += n2 + \" CENTAVO\";\n\t\t\telse\n\t\t\t\tresult += n2 + \" CENTAVOS\";\n\t\t} else if (n1 == \"1\") {\n\t\t\tif (n2 == \"00\")\n\t\t\t\tresult += n1 + \" REAL\";\n\t\t\telse if (n2 == \"01\")\n\t\t\t\tresult += n1 + \" REAL E \" + n2 + \" CENTAVO\";\n\t\t\telse\n\t\t\t\tresult += n1 + \" REAL E \" + n2 + \" CENTAVOS\";\n\t\t} else {\n\t\t\tif (n2 == \"00\")\n\t\t\t\tresult += n1 + \" REAIS\";\n\t\t\telse if (n2 == \"01\")\n\t\t\t\tresult += n1 + \" REAIS E \" + n2 + \" CENTAVO\";\n\t\t\telse\n\t\t\t\tresult += n1 + \" REAIS E \" + n2 + \" CENTAVOS\";\n\t\t}\n\n\t\tcout << result;\n\t\tcin >> number;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2011/goldbach.cpp",
    "content": "#include<stdio.h>\n#include <iostream>\n#include <math.h>\n\nusing namespace std;\n\nint verifica_primo(int n) {\n\tint total_divisivel = 0;\n\n\n\tif (n == 2) {\n\t\treturn 1;\n\t}\n\tif ((n % 2) == 0)\n\t\treturn 0;\n\n\n\tint s = sqrt(n);\n\n\tfor (int i = 3; i <= s; i += 2) {\n\t\tif (n % i == 0){\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\treturn 1;\n}\n\nint main()\n{\n    \n\n    int n, n1, n2;\n    scanf(\"%i\", &n);\n\n    while (n != 0) {\n\n    \tif (n % 2 != 0)\n    \t\tcout << \"erro\" << endl;\n    \telse {\n    \t\tfor (int i = 2; i <= n; i++) {\n    \t\t\tif (verifica_primo(i)) {\n    \t\t\t\tn1 = i;\n    \t\t\t\tif (verifica_primo(n-n1)) {\n    \t\t\t\t\tn2 = n - n1;\n    \t\t\t\t\tbreak;\n    \t\t\t\t}\n    \t\t\t}\n    \t\t}\n\n    \t\tcout << n1 << \" \" << n2 << endl;\n    \t}\n\n    \tscanf(\"%i\", &n);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2011/matriz_esparsa.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, x, total, zeros, medium;\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> x;\n\t\ttotal = x * x;\n\t\tzeros = total - (3 * x - 2);\n\t\tmedium = total / 2;\n\t\tif (zeros > medium) cout << \"S \" << zeros << endl;\n\t\telse cout << \"N \" << zeros << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2011/pascal.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint triangulo_pascal(int n, int m) {\r\n\r\n\tif ((m == 0 || n == 0) || (m == 1 && n == 1) || (m == n))\r\n\t\treturn 1;\r\n\t\t\r\n\treturn triangulo_pascal(n - 1, m) + triangulo_pascal(n - 1, m - 1);\r\n}\r\n\r\nint main() {\r\n\r\n\tint n, x, y;\r\n\r\n\tcin >> n;\r\n\t\r\n\twhile (n--) {\r\n\r\n\t\tcin >> x;\r\n\t\tcin >> y;\r\n\t\t\r\n\t\tcout << triangulo_pascal(x, y) << endl;\r\n\t}\t\r\n\r\n\treturn 0;\r\n}"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2011/polinomio.cpp",
    "content": "#include <string>\n#include <vector>\n#include <iostream>\n#include <math.h>\n#include <sstream>\n\nusing namespace std;\n\nint solvePartEquation(string part_equation, int value) {\n  int result, inicio=0, constante, expo;\n\n  int x = part_equation.find(\"x\");\n  stringstream ss1; ss1 << part_equation.substr(0, x); ss1 >> constante;\n  stringstream ss2; ss2 << part_equation.substr(x+1, part_equation.size()-x); ss2 >> expo;  \n\n  result = constante * (pow(value, expo));\n\n  return result;\n}\n\nint main() {\n\n  int n, time=1, i_inicio=0, total;\n  string temp;\n  vector<string> vetor_de_valores, vetor_de_variaveis, vetor_de_sinais;\n  vector<int> vetor_de_resultados;\n\n  cin >> n;\n\n  while (n--) {\n    string equacao;\n    int number_of_values;\n\n    cin >> equacao;\n    cin >> number_of_values;\n\n    for (int i = 0; i < number_of_values; i++){\n      cin >> temp;\n      vetor_de_valores.push_back(temp);\n    }\n\n    for (int i = 0; i < equacao.size(); i++) {\n      if (equacao[i] == '+' || equacao[i] == '-') {\n        vetor_de_variaveis.push_back(equacao.substr(i_inicio, i-i_inicio));\n        vetor_de_sinais.push_back(equacao.substr(i, 1));\n        i_inicio = i+1;\n      }\n    }\n\n    for (int i = 0; i < vetor_de_valores.size(); i++) {\n      int valor;\n      stringstream ss; ss << vetor_de_valores[i]; ss >> valor;      \n      total = solvePartEquation(vetor_de_variaveis[0], valor);\n      for (int j = 1; j < vetor_de_variaveis.size(); j++){\n        if (vetor_de_sinais[j-1] == \"+\")\n          total += solvePartEquation(vetor_de_variaveis[j], valor);\n        else\n          total -= solvePartEquation(vetor_de_variaveis[j], valor);\n\n        vetor_de_resultados.push_back(total);\n      }\n    }\n\n    cout << \"Caso \" << time << \": \";\n    for (int i = 0; vetor_de_resultados.size(); i++)\n      cout << vetor_de_resultados[i] << \" \";\n\n    cout << endl;\n    time++;\n  }\n\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2011/quadrado.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\tvector<int> v;\n\tcin >> n;\n\t\n\twhile (n--) {\n\t\tint temp;\n\t\t\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\tcin >> temp;\n\t\t\tv.push_back(temp);\n\t\t}\n\t\t\t\n\t\tsort(v);\n\t\t\n\t\tif (v[0] == v[1] && v[0] == v[2] && v[0] == v[3]) cout << \"quadrado\" << endl;\n\t\telse if (v[0] == v[1] && v[2] == v[3]) cout << \"retangulo\" << endl;\n\t\telse if (v[0] + v[1] + v[2] > v[3]) cout << \"quadrilatero\" << endl;\n\t\telse cout << \"invalido\" << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2011/vagas.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\r\n\tint c, total;\r\n\t\r\n\tcin >> c;\r\n\t\r\n\twhile (c != -1) {\r\n\t\r\n\t\ttotal = (c - 6) / 5;\r\n\t\tcout << total << endl;\r\n\t\t\r\n\t\tcin >> c;\r\n\t}\r\n\r\n\r\n\treturn 0;\r\n}"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2017_1/A.cpp",
    "content": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define MAX_SIZE (1 << 20)\n\nint segtree[MAX_SIZE];\nint lazy[MAX_SIZE];\n\nvoid build_segtree(int A[], int node, int start, int end) {\n  if (start == end) {\n    segtree[node] = A[start];\n  } else {\n    int middle = (start + end) / 2;\n    build_segtree(A, node * 2, start, middle);\n    build_segtree(A, node * 2 + 1, middle + 1, end);\n  }\n}\n\nvoid propagate(int p, int start, int end) {\n  if (lazy[p] != 0) {\n    segtree[p] += lazy[p];\n\n    if (start != end) {\n      lazy[p * 2] += lazy[p];\n      lazy[p * 2 + 1] += lazy[p];\n    }\n\n    lazy[p] = 0;\n  }\n}\n\nvoid lazy_update(int p, int start, int end, int left, int right, int inc) {\n  propagate(p, start, end);\n\n  if (start > end || end < left || start > right) return; // Totally out of range\n\n  if (start >= left && end <= right) { // Totally in the range\n    segtree[p] += inc;\n\n    if (start != end) { // Not a leaf\n      lazy[p * 2] += inc;\n      lazy[p * 2 + 1] += inc;\n    }\n\n    return;\n  }\n\n  // Partially in the range\n  int middle = (start + end) / 2;\n  lazy_update(p * 2, start, middle, left, right, inc);\n  lazy_update(p * 2 + 1, middle + 1, end, left, right, inc);\n}\n\nint lazy_query(int p, int start, int end, int left, int right) {\n  if (start > end || left > end || right < start) return -1;\n\n  propagate(p, start, end);\n\n  if (start >= left && end <= right) return segtree[p];\n\n  int middle = (end + start) / 2;\n  int left_f = lazy_query(p * 2, start, middle, left, right);\n  int right_f = lazy_query(p * 2 + 1, middle + 1, end, left, right);\n}\n\nvoid print_all_leaves(int p, int start, int end) {\n  if (start > end) return;\n  propagate(p, start, end);\n  if (start == end) cout << segtree[p] << endl;\n\n  int middle = (start + end) / 2;\n  print_all_leaves(p * 2, start, middle);\n  print_all_leaves(p * 2 + 1, middle + 1, end);\n}\n\nint main() {\n  int N, C, left, right, most_frequent;\n  cin >> N >> C;\n\n  int A[N];\n  for (int i = 0; i < N; i++) A[i] = 1;\n\n  build_segtree(A, 1, 0, N - 1);\n\n  while (C--) {\n    cin >> left >> right;\n    most_frequent = lazy_query(1, 0, N - 1, left, right);\n    lazy_update(1, 0, N - 1, left, right, most_frequent);\n  }\n\n  //print_all_leaves(1, 0, N - 1);\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2017_2/D.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nbool is_prime(int N) {\n  return true;\n}\n\nint main() {\n  int N;\n  cin >> N;\n\n  if (is_prime(N)) {\n    cout << 0 << endl;\n  } else {\n    \n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2017_2/F.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n  int N, M, num;\n  vector<int> V;\n\n  cin >> N >> M;\n\n  while (N--) {\n    cin >> num;\n    V.push_back(num);\n  }\n\n  sort(V.begin(), V.end(), greater<int>());\n\n  int result = M;\n\n  for (int i = M; i < V.size(); i++) {\n    if (V[i] == V[i-1]) result++;\n    else break;\n  }\n\n  cout << result << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2017_2/J.py",
    "content": "n = input()\nprint n % 3\n"
  },
  {
    "path": "competitive-programming/acm-icpc-br/regionals_2017_2/M.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int N1, N2, N3;\n\n  cin >> N1 >> N2 >> N3;\n\n  int one = N2 * 2 + N3 * 4,\n      two = N1 * 2 + N3 * 2,\n      three = N1 * 4 + N2 * 2;\n\n  if (one <= two && one <= three) cout << one << endl;\n  else if (two <= three) cout << two << endl;\n  else cout << three << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/codeforces/div2/black_square.cpp",
    "content": "// http://codeforces.com/problemset/problem/828/B\n\n#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nint main() {\n  int N, M, black = 0,\n      smaller_black_x = 101,\n      smaller_black_y = 101,\n      bigger_black_x = -1,\n      bigger_black_y = -1,\n      result_square,\n      bigger_side;\n\n  vector<string> matrix;\n  string line;\n  cin >> N >> M;\n  cin.ignore();\n\n  for (int i = 0; i < N; i++) {\n    getline(cin, line);\n    matrix.push_back(line);\n  }\n\n  for (int i = 0; i < N; i++) {\n    for (int j = 0; j < M; j++) {\n      if (matrix[i][j] == 'B') {\n        if (i < smaller_black_y) smaller_black_y = i;\n        if (i > bigger_black_y) bigger_black_y = i;\n        if (j < smaller_black_x) smaller_black_x = j;\n        if (j > bigger_black_x) bigger_black_x = j;\n        black++;\n      }\n    }\n  }\n\n  if (black == 0) {\n    cout << 1 << endl;\n    return 0;\n  }\n\n  bigger_side = max(bigger_black_x - smaller_black_x + 1, bigger_black_y - smaller_black_y + 1);\n\n  if (bigger_side > N || bigger_side > M) cout << -1 << endl;\n  else cout << bigger_side * bigger_side - black << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/codeforces/div2/karen_and_morning.cpp",
    "content": "// http://codeforces.com/contest/816/problem/A\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint to_digit(char c) {\n  return c - '0';\n}\n\nint main() {\n  string hour;\n  cin >> hour;\n\n  int hour_decimal = to_digit(hour[0]),\n      hour_unit = to_digit(hour[1]),\n      minute_decimal = to_digit(hour[3]),\n      minute_unit = to_digit(hour[4]),\n      hour_int, minute;\n\n  hour_int = hour_decimal * 10 + hour_unit;\n  minute = minute_decimal * 10 + minute_unit;\n\n  if (hour_int == minute_unit * 10 + minute_decimal) cout << 0 << endl;\n  else if (hour_int == 1 && minute < 10) cout << 10 - minute << endl;\n  else if ((hour_int == 0 ||hour_int == 1 || hour_int == 2 || hour_int == 3 || hour_int == 4 || hour_int == 5 ||\n            hour_int == 10 || hour_int == 11 || hour_int == 12 || hour_int == 13 || hour_int == 14 || hour_int == 15 ||\n            hour_int == 20 || hour_int == 21 || hour_int == 22 || hour_int == 23)\n            && minute > 10) cout << 70 - minute << endl;\n  else if ((hour_int == 0 ||hour_int == 1 || hour_int == 2 || hour_int == 3 || hour_int == 4 ||\n            hour_int == 10 || hour_int == 11 || hour_int == 12 || hour_int == 13 || hour_int == 14 ||\n            hour_int == 20 || hour_int == 21 || hour_int == 22 || hour_int == 23)\n            && minute > 10)\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/codeforces/div2/keyboard_layouts.cpp",
    "content": "// http://codeforces.com/problemset/problem/831/B\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nbool is_uppercase(char word) {\n  string original_alphabet = \"ABCDEFGHIJKLMNOPQRSTUVXWYZabcdefghijklmnopqrstuvxwyz\";\n  return original_alphabet.find(word) < 26;\n}\n\nchar build_new_word(char letter, string alpha1, string alpha2) {\n  string original_alphabet = \"ABCDEFGHIJKLMNOPQRSTUVXWYZabcdefghijklmnopqrstuvxwyz\", numbers = \"0123456789\";\n\n  if (numbers.find(letter) >= 0 && numbers.find(letter) <= 9)\n    return letter;\n  else if (is_uppercase(letter)) {\n    char l = original_alphabet[original_alphabet.find(letter) + 26];\n    int index = alpha1.find(l);\n    char new_l = alpha2[index];\n    return original_alphabet[original_alphabet.find(new_l) - 26];\n  }\n\n  return alpha2[alpha1.find(letter)];\n}\n\nint main() {\n  string alpha1, alpha2, word, result;\n\n  cin >> alpha1 >> alpha2 >> word;\n\n  for (int i = 0; i < word.size(); i++) {\n    result += build_new_word(word[i], alpha1, alpha2);\n  }\n\n  cout << result << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/codeforces/div2/the_child_and_the_homework.cpp",
    "content": "// http://codeforces.com/contest/437/problem/A\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstring solve(string a, string b, string c, string d) {\n  bool a_smaller = (a.size()-2 <= (b.size()-2) / 2) && (a.size()-2 <= (c.size()-2) / 2) && (a.size()-2 <= (d.size()-2) / 2),\n       a_bigger = (a.size()-2 >= (b.size()-2) * 2) && (a.size()-2 >= (c.size()-2) * 2) && (a.size()-2 >= (d.size()-2) * 2),\n       b_smaller = (b.size()-2 <= (a.size()-2) / 2) && (b.size()-2 <= (c.size()-2) / 2) && (b.size()-2 <= (d.size()-2) / 2),\n       b_bigger = (b.size()-2 >= (a.size()-2) * 2) && (b.size()-2 >= (c.size()-2) * 2) && (b.size()-2 >= (d.size()-2) * 2),\n       c_smaller = (c.size()-2 <= (a.size()-2) / 2) && (c.size()-2 <= (b.size()-2) / 2) && (c.size()-2 <= (d.size()-2) / 2),\n       c_bigger = (c.size()-2 >= (a.size()-2) * 2) && (c.size()-2 >= (b.size()-2) * 2) && (c.size()-2 >= (d.size()-2) * 2),\n       d_smaller = (d.size()-2 <= (a.size()-2) / 2) && (d.size()-2 <= (b.size()-2) / 2) && (d.size()-2 <= (c.size()-2) / 2),\n       d_bigger = (d.size()-2 >= (b.size()-2) * 2) && (d.size()-2 >= (a.size()-2) * 2) && (d.size()-2 >= (c.size()-2) * 2);\n\n  vector<string> great_choices;\n  if (a_bigger || a_smaller) great_choices.push_back(\"A\");\n  if (b_bigger || b_smaller) great_choices.push_back(\"B\");\n  if (c_bigger || c_smaller) great_choices.push_back(\"C\");\n  if (d_bigger || d_smaller) great_choices.push_back(\"D\");\n  if (great_choices.size() == 1) return great_choices[0];\n  return \"C\";\n}\n\nint main() {\n  string a, b, c, d;\n\n  cin >> a >> b >> c >> d;\n\n  cout << solve(a, b, c, d) << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/codeforces/div2/the_child_and_toy.cpp",
    "content": "// http://codeforces.com/contest/437/problem/C\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nint min(int x, int y, int values[]) {\n  return values[x-1] < values[y-1] ? values[x-1] : values[y-1];\n}\n\nint main() {\n  int n, m, x, y, value, min_energy = 0;\n  cin >> n >> m;\n\n  int values[n];\n\n  for (int i = 0; i < n; i++) {\n    cin >> value;\n    values[i] = value;\n  }\n\n  while (m--) {\n    cin >> x >> y;\n    min_energy += min(x, y, values);\n  }\n\n  cout << min_energy << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/codeforces/div2/valera_and_plates.cpp",
    "content": "// http://codeforces.com/problemset/problem/369/A\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int N, M, K, num, W = 0;\n  cin >> N >> M >> K;\n\n  while (N--) {\n    cin >> num;\n\n    if (num == 1) {\n      if (M == 0) W++;\n      else M--;\n    } else {\n      if (K == 0) {\n        if (M == 0) W++;\n        else M--;\n      } else {\n        K--;\n      }\n    }\n  }\n\n  cout << W << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/exercism/clojure/armstrong-numbers/.exercism/metadata.json",
    "content": "{\"track\":\"clojure\",\"exercise\":\"armstrong-numbers\",\"id\":\"c708010a47824f9daeddb51af2f51b2f\",\"url\":\"https://exercism.io/my/solutions/c708010a47824f9daeddb51af2f51b2f\",\"handle\":\"LeandroTk\",\"is_requester\":true,\"auto_approve\":false}"
  },
  {
    "path": "competitive-programming/exercism/clojure/armstrong-numbers/.lein-failures",
    "content": "{}"
  },
  {
    "path": "competitive-programming/exercism/clojure/armstrong-numbers/.lein-repl-history",
    "content": "(defn int->digits [int]\n  (map (comp #(- % 48) int) (str int)))\n(defn power-by-two [digits]\n  (map #(* % (count digits)) digits))\n(defn powered-sum [num]\n  (->> num\n       int->digits\n       power-by-two\n       (reduce +)))\n(defn armstrong? [num]\n  (= (powered-sum num) num))\n(armstrong? 123)\n(int->digits 123)\nquit\n"
  },
  {
    "path": "competitive-programming/exercism/clojure/armstrong-numbers/README.md",
    "content": "# Armstrong Numbers\n\nAn [Armstrong number](https://en.wikipedia.org/wiki/Narcissistic_number) is a number that is the sum of its own digits each raised to the power of the number of digits.\n\nFor example:\n\n- 9 is an Armstrong number, because `9 = 9^1 = 9`\n- 10 is *not* an Armstrong number, because `10 != 1^2 + 0^2 = 1`\n- 153 is an Armstrong number, because: `153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153`\n- 154 is *not* an Armstrong number, because: `154 != 1^3 + 5^3 + 4^3 = 1 + 125 + 64 = 190`\n\nWrite some code to determine whether a number is an Armstrong number.\n## Source\n\nWikipedia [https://en.wikipedia.org/wiki/Narcissistic_number](https://en.wikipedia.org/wiki/Narcissistic_number)\n\n## Submitting Incomplete Solutions\nIt's possible to submit an incomplete solution so you can see how others have completed the exercise.\n"
  },
  {
    "path": "competitive-programming/exercism/clojure/armstrong-numbers/project.clj",
    "content": "(defproject armstrong-numbers \"0.1.0-SNAPSHOT\"\n  :description \"armstrong-numbers exercise\"\n  :url \"https://github.com/exercism/clojure/tree/master/exercises/armstrong-numbers\"\n  :dependencies [[org.clojure/clojure \"1.10.0\"]])\n"
  },
  {
    "path": "competitive-programming/exercism/clojure/armstrong-numbers/src/armstrong_numbers.clj",
    "content": "(ns armstrong-numbers)\n\n(defn int->digits [num]\n  (map (comp #(- % 48) int) (str num)))\n\n(defn power-by-two [digits digit]\n  (reduce * (repeat (count digits) digit)))\n\n(defn power-all-by-two [digits]\n  (map (partial power-by-two digits) digits))\n\n(defn powered-sum [num]\n  (->> num\n       int->digits\n       power-all-by-two\n       (reduce +)))\n\n(defn armstrong? [num]\n  (= (powered-sum num) num))\n"
  },
  {
    "path": "competitive-programming/exercism/clojure/armstrong-numbers/target/classes/META-INF/maven/armstrong-numbers/armstrong-numbers/pom.properties",
    "content": "#Leiningen\n#Thu Jan 31 22:57:53 BRST 2019\ngroupId=armstrong-numbers\nartifactId=armstrong-numbers\nversion=0.1.0-SNAPSHOT\n"
  },
  {
    "path": "competitive-programming/exercism/clojure/armstrong-numbers/target/stale/leiningen.core.classpath.extract-native-dependencies",
    "content": "[{:dependencies {org.clojure/clojure {:vsn \"1.10.0\", :native-prefix nil}, org.clojure/spec.alpha {:vsn \"0.2.176\", :native-prefix nil}, org.clojure/core.specs.alpha {:vsn \"0.2.44\", :native-prefix nil}, nrepl {:vsn \"0.5.3\", :native-prefix nil}, nrepl/bencode {:vsn \"1.0.0\", :native-prefix nil}, clojure-complete {:vsn \"0.2.5\", :native-prefix nil}}, :native-path \"target/native\"} {:native-path \"target/native\", :dependencies {org.clojure/clojure {:vsn \"1.10.0\", :native-prefix nil, :native? false}, org.clojure/spec.alpha {:vsn \"0.2.176\", :native-prefix nil, :native? false}, org.clojure/core.specs.alpha {:vsn \"0.2.44\", :native-prefix nil, :native? false}, nrepl {:vsn \"0.5.3\", :native-prefix nil, :native? false}, nrepl/bencode {:vsn \"1.0.0\", :native-prefix nil, :native? false}, clojure-complete {:vsn \"0.2.5\", :native-prefix nil, :native? false}}}]"
  },
  {
    "path": "competitive-programming/exercism/clojure/armstrong-numbers/test/armstrong_numbers_test.clj",
    "content": "(ns armstrong-numbers-test\n  (:require [clojure.test :refer [deftest is testing]]\n            [armstrong-numbers :refer [armstrong?]]))\n\n(deftest armstrong-number-5\n  (testing \"Single digit numbers are Armstrong numbers\"\n    (is (armstrong? 5))))\n\n(deftest not-armstrong-number-10\n  (testing \"There are no 2 digit Armstrong numbers\"\n    (is (not (armstrong? 10)))))\n\n(deftest armstrong-number-153\n  (testing \"Three digit number that is an Armstrong number\"\n    (is (armstrong? 153))))\n\n(deftest not-armstrong-number-100\n  (testing \"Three digit number that is not an Armstrong number\"\n    (is (not (armstrong? 100)))))\n\n(deftest armstrong-number-9474\n  (testing \"Four digit number that is an Armstrong number\"\n    (is (armstrong? 9474))))\n\n(deftest not-armstrong-number-9475\n  (testing \"Four digit number that is not an Armstrong number\"\n    (is (not (armstrong? 9476)))))\n\n(deftest armstrong-number-9926315\n  (testing \"Seven digit number that is an Armstrong number\"\n    (is (armstrong? 9926315))))\n\n(deftest not-armstrong-number-9926314\n  (testing \"Seven digit number that is not an Armstrong number\"\n    (is (not (armstrong? 9926314)))))\n\n(deftest armstrong-number-21897142587612075\n  (testing \"Seventeen digit number that is an Armstrong number\"\n    (is (armstrong? 21897142587612075))))\n"
  },
  {
    "path": "competitive-programming/exercism/clojure/hello-world/README.md",
    "content": "# Hello World\n\nThe classical introductory exercise. Just say \"Hello, World!\".\n\n[\"Hello, World!\"](http://en.wikipedia.org/wiki/%22Hello,_world!%22_program) is\nthe traditional first program for beginning programming in a new language\nor environment.\n\nThe objectives are simple:\n\n- Write a function that returns the string \"Hello, World!\".\n- Run the test suite and make sure that it succeeds.\n- Submit your solution and check it at the website.\n\nIf everything goes well, you will be ready to fetch your first real exercise.\n\n### Project Structure\n\nClojure exercises in exercism use [leiningen](http://leiningen.org/) to configure and run your code\nand use [leiningen standard directory structure](https://github.com/technomancy/leiningen/blob/master/doc/TUTORIAL.md#directory-layout).\n\nYou will find a test file named `hello_world_test.clj` inside `test` directory.\nWrite your code in `src/hello_world.clj`. It should use the namespace `hello-world` so that tests can pick it up.\n\n### Running tests\n\nRun the tests using `lein test` command and make them pass:\n\n```\n$ lein test\n\nlein test hello-world-test\n\nRan 1 tests containing 1 assertions.\n0 failures, 0 errors.\n```\n\nThen submit the exercise using:\n\n```\n$ exercism submit src/hello_world.clj\n```\n\nFor more detailed instructions and learning resources refer [exercism's clojure language page](http://exercism.io/languages/clojure).\n\n## Source\n\nThis is an exercise to introduce users to using Exercism [http://en.wikipedia.org/wiki/%22Hello,_world!%22_program](http://en.wikipedia.org/wiki/%22Hello,_world!%22_program)\n\n## Submitting Incomplete Solutions\nIt's possible to submit an incomplete solution so you can see how others have completed the exercise.\n"
  },
  {
    "path": "competitive-programming/exercism/clojure/hello-world/project.clj",
    "content": "(defproject hello-world \"0.1.0-SNAPSHOT\"\n  :description \"hello-world exercise.\"\n  :url \"https://github.com/exercism/clojure/tree/master/exercises/hello-world\"\n  :dependencies [[org.clojure/clojure \"1.9.0\"]])\n"
  },
  {
    "path": "competitive-programming/exercism/clojure/hello-world/src/hello-world.clj",
    "content": "(ns hello-world)\n\n(defn hello [] \"Hello, World!\")\n"
  },
  {
    "path": "competitive-programming/exercism/clojure/hello-world/test/hello-world-test.clj",
    "content": "(ns hello-world-test\n  (:require [clojure.test :refer [deftest is]]\n            hello-world))\n\n(deftest hello-world-test\n  (is (= \"Hello, World!\" (hello-world/hello))))\n"
  },
  {
    "path": "competitive-programming/exercism/clojure/two-fer/.exercism/metadata.json",
    "content": "{\"track\":\"clojure\",\"exercise\":\"two-fer\",\"id\":\"13de8e46adaa41d68299dc2b4a20ff1c\",\"url\":\"https://exercism.io/my/solutions/13de8e46adaa41d68299dc2b4a20ff1c\",\"handle\":\"LeandroTk\",\"is_requester\":true,\"auto_approve\":false}"
  },
  {
    "path": "competitive-programming/exercism/clojure/two-fer/.lein-failures",
    "content": "{}"
  },
  {
    "path": "competitive-programming/exercism/clojure/two-fer/.nrepl-port",
    "content": "62204"
  },
  {
    "path": "competitive-programming/exercism/clojure/two-fer/README.md",
    "content": "# Two Fer\n\n`Two-fer` or `2-fer` is short for two for one. One for you and one for me.\n\nGiven a name, return a string with the message:\n\n```text\nOne for X, one for me.\n```\n\nWhere X is the given name.\n\nHowever, if the name is missing, return the string:\n\n```text\nOne for you, one for me.\n```\n\nHere are some examples:\n\n|Name    | String to return \n|:------:|:-----------------: \n|Alice   | One for Alice, one for me. \n|Bob     | One for Bob, one for me.\n|        | One for you, one for me.\n|Zaphod  | One for Zaphod, one for me.\n## Source\n\n[https://github.com/exercism/problem-specifications/issues/757](https://github.com/exercism/problem-specifications/issues/757)\n\n## Submitting Incomplete Solutions\nIt's possible to submit an incomplete solution so you can see how others have completed the exercise.\n"
  },
  {
    "path": "competitive-programming/exercism/clojure/two-fer/project.clj",
    "content": "(defproject two-fer \"0.1.0-SNAPSHOT\"\n  :description \"two-fer exercise.\"\n  :url \"https://github.com/exercism/clojure/tree/master/exercises/two-fer\"\n  :dependencies [[org.clojure/clojure \"1.8.0\"]])\n"
  },
  {
    "path": "competitive-programming/exercism/clojure/two-fer/src/two_fer.clj",
    "content": "(ns two-fer)\n\n(defn two-fer\n  ([] \"One for you, one for me.\")\n  ([name] (str \"One for \" name \", one for me.\")))\n"
  },
  {
    "path": "competitive-programming/exercism/clojure/two-fer/target/classes/META-INF/maven/two-fer/two-fer/pom.properties",
    "content": "#Leiningen\n#Sun Feb 03 05:19:15 BRST 2019\ngroupId=two-fer\nartifactId=two-fer\nversion=0.1.0-SNAPSHOT\n"
  },
  {
    "path": "competitive-programming/exercism/clojure/two-fer/target/repl-port",
    "content": "62204"
  },
  {
    "path": "competitive-programming/exercism/clojure/two-fer/target/stale/leiningen.core.classpath.extract-native-dependencies",
    "content": "[{:dependencies {org.clojure/clojure {:vsn \"1.8.0\", :native-prefix nil}, nrepl {:vsn \"0.5.3\", :native-prefix nil}, nrepl/bencode {:vsn \"1.0.0\", :native-prefix nil}, clojure-complete {:vsn \"0.2.5\", :native-prefix nil}}, :native-path \"target/native\"} {:native-path \"target/native\", :dependencies {org.clojure/clojure {:vsn \"1.8.0\", :native-prefix nil, :native? false}, clojure-complete {:vsn \"0.2.5\", :native-prefix nil, :native? false}, nrepl {:vsn \"0.5.3\", :native-prefix nil, :native? false}, nrepl/bencode {:vsn \"1.0.0\", :native-prefix nil, :native? false}}}]"
  },
  {
    "path": "competitive-programming/exercism/clojure/two-fer/test/two_fer_test.clj",
    "content": "(ns two-fer-test\n  (:require [clojure.test :refer [deftest is]]\n            two-fer))\n\n(deftest two-fer-test\n  (is (= \"One for you, one for me.\" (two-fer/two-fer))))\n\n(deftest name-alice-test\n  (is (= \"One for Alice, one for me.\" (two-fer/two-fer \"Alice\"))))\n\n(deftest name-bob-test\n  (is (= \"One for Bob, one for me.\" (two-fer/two-fer \"Bob\"))))\n"
  },
  {
    "path": "competitive-programming/exercism/javascript/allergies.js",
    "content": "export class Allergies {\n  constructor(score) {\n    this.score = score;\n    this.scores = [128, 64, 32, 16, 8, 4, 2, 1];\n    this.scoreToFoodMapper = {\n      1: 'eggs',\n      2: 'peanuts',\n      4: 'shellfish',\n      8: 'strawberries',\n      16: 'tomatoes',\n      32: 'chocolate',\n      64: 'pollen',\n      128: 'cats',\n    };\n  }\n\n  list() {\n    this.listOfFoods = [];\n    this.findMaxSmallerThanScore(this.score);\n    return [...new Set(this.listOfFoods)];\n  }\n\n  findMaxSmallerThanScore(score) {\n    if (score === 0) return;\n\n    const maxSmallerThanScore = this.scores.find(\n      (currentScore) => currentScore <= score\n    );\n\n    this.listOfFoods.unshift(this.scoreToFoodMapper[maxSmallerThanScore]);\n    score -= maxSmallerThanScore;\n    return this.findMaxSmallerThanScore(score);\n  }\n\n  allergicTo(food) {\n    return this.list().includes(food);\n  }\n}\n"
  },
  {
    "path": "competitive-programming/exercism/javascript/collatz-conjecture.js",
    "content": "export const steps = n => {\n  if (n <= 0) throw \"Only positive numbers are allowed\";\n\n  let times = 0;\n\n  while (n !== 1) {\n    if (n % 2 === 0) {\n      n /= 2;\n    } else {\n      n = n * 3 + 1;\n    }\n\n    times++;\n  }\n\n  return times;\n};\n"
  },
  {
    "path": "competitive-programming/exercism/javascript/count-words.js",
    "content": "const SPECIAL_CHARACTERS = /[!@#\\$%\\^\\&*\\\".,;:?<>~`(\\){}[\\]\\\\/\\+=_-]/g;\nconst SPACE_CHARACTERS = /\\s+/g;\n\nfunction isEmptySpace(string) {\n  return string !== '';\n}\n\nfunction removeOpenQuote(word) {\n  return word.startsWith(\"'\") ? word.substring(1) : word;\n}\n\nfunction removeCloseQuote(word) {\n  return word.endsWith(\"'\") ? word.substring(0, word.length - 1) : word;\n}\n\nfunction removeQuotes(word) {\n  return removeCloseQuote(removeOpenQuote(word));\n}\n\nexport const countWords = (phrase) => {\n  const words = phrase\n    .toLowerCase()\n    .replaceAll(SPECIAL_CHARACTERS, ' ')\n    .split(SPACE_CHARACTERS)\n    .filter(isEmptySpace)\n    .map(removeQuotes);\n\n  const wordCounter = {};\n\n  for (const word of words) {\n    wordCounter[word] = (wordCounter[word] || 0) + 1;\n  }\n\n  return wordCounter;\n};\n"
  },
  {
    "path": "competitive-programming/exercism/javascript/etl.js",
    "content": "export const transform = (scoreToLetters) => {\n  const obj = {};\n\n  Object.entries(scoreToLetters).forEach(([score, letters]) => {\n    letters.forEach((letter) => {\n      obj[letter.toLowerCase()] = Number(score);\n    });\n  });\n\n  return obj;\n};\n"
  },
  {
    "path": "competitive-programming/exercism/javascript/flatten-array.js",
    "content": "export const flatten = (list) => {\n  const result = [];\n\n  list.forEach((item) => {\n    if (Array.isArray(item)) {\n      result.push(...flatten(item));\n    } else if (item !== undefined && item !== null) {\n      result.push(item);\n    }\n  });\n\n  return result;\n};\n"
  },
  {
    "path": "competitive-programming/exercism/javascript/gigasecond.js",
    "content": "const year = date => date.getUTCFullYear();\nconst month = date => date.getUTCMonth();\nconst day = date => date.getUTCDate() + 11574;\nconst hours = date => date.getUTCHours() + 1;\nconst minutes = date => date.getUTCMinutes() + 46;\nconst second = date => date.getUTCSeconds() + 40;\n\nexport const gigasecond = date =>\n  new Date(\n    Date.UTC(\n      year(date),\n      month(date),\n      day(date),\n      hours(date),\n      minutes(date),\n      second(date)\n    )\n  );\n"
  },
  {
    "path": "competitive-programming/exercism/javascript/hello-world.js",
    "content": "export const hello = () => \"Hello, World!\";\n"
  },
  {
    "path": "competitive-programming/exercism/javascript/leap.js",
    "content": "// https://exercism.io/tracks/javascript/exercises/leap/solutions/0e7bcf1db4974d159ab9ebe9e961bcd1\n\nexport const isLeap = year =>\n  (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n"
  },
  {
    "path": "competitive-programming/exercism/javascript/perfect-numbers.js",
    "content": "const getAllDivisibleNumbers = (number) => {\n  const divisibleNumbers = [];\n\n  for (let i = 1; i <= number / 2; i++) {\n    if (number % i === 0) {\n      divisibleNumbers.push(i);\n    }\n  }\n\n  return divisibleNumbers;\n};\n\nconst sumAllNumbers = (numbers) =>\n  numbers.reduce((sum, number) => sum + number, 0);\n\nexport const classify = (number) => {\n  if (number <= 0) {\n    throw new Error('Classification is only possible for natural numbers.');\n  }\n\n  const divisibleNumbers = getAllDivisibleNumbers(number);\n  const sumOfNumbers = sumAllNumbers(divisibleNumbers);\n  console.log('divisibleNumbers', divisibleNumbers);\n  console.log('sumOfNumbers', sumOfNumbers);\n\n  if (sumOfNumbers === number) {\n    return 'perfect';\n  }\n\n  if (sumOfNumbers > number) {\n    return 'abundant';\n  }\n\n  if (sumOfNumbers < number) {\n    return 'deficient';\n  }\n};\n"
  },
  {
    "path": "competitive-programming/exercism/javascript/phone-number.js",
    "content": "const isDigit = (char) => '0' <= char && char <= '9';\n\nconst getDigits = (phoneNumber) =>\n  phoneNumber.split('').filter(isDigit).join('');\n\nconst verifyDigitsLength = (digits) => {\n  if (digits.length < 10) {\n    throw new Error('Incorrect number of digits');\n  }\n\n  if (digits.length >= 12) {\n    throw new Error('More than 11 digits');\n  }\n};\n\nconst verifyCountryCode = (digits) => {\n  if (digits.length === 11 && digits[0] !== '1') {\n    throw new Error('11 digits must start with 1');\n  }\n};\n\nconst verifyAreaCode = (digits) => {\n  if (digits.length === 10 && digits[0] === '0') {\n    throw new Error('Area code cannot start with zero');\n  }\n\n  if (digits.length === 10 && digits[0] === '1') {\n    throw new Error('Area code cannot start with one');\n  }\n\n  if (digits.length === 11 && digits[1] === '0') {\n    throw new Error('Area code cannot start with zero');\n  }\n\n  if (digits.length === 11 && digits[1] === '1') {\n    throw new Error('Area code cannot start with one');\n  }\n};\n\nconst verifyExchangeCode = (digits) => {\n  if (digits.length === 10 && digits[3] === '0') {\n    throw new Error('Exchange code cannot start with zero');\n  }\n\n  if (digits.length === 10 && digits[3] === '1') {\n    throw new Error('Exchange code cannot start with one');\n  }\n\n  if (digits.length === 11 && digits[4] === '0') {\n    throw new Error('Exchange code cannot start with zero');\n  }\n\n  if (digits.length === 11 && digits[4] === '1') {\n    throw new Error('Exchange code cannot start with one');\n  }\n};\n\nconst verifyAlphabetChars = (digits) => {\n  const alphabetChars = digits.match(/[A-Za-z]/g);\n\n  if (alphabetChars && alphabetChars.length) {\n    throw new Error('Letters not permitted');\n  }\n};\n\nconst verifyPunctuationChars = (digits) => {\n  const punctuationChars = digits.match(/[,\\/#!$%\\^&\\*;:{}=\\_`~]/g);\n\n  if (punctuationChars && punctuationChars.length) {\n    throw new Error('Punctuations not permitted');\n  }\n};\n\nexport const clean = (phoneNumber) => {\n  const digits = getDigits(phoneNumber);\n\n  verifyAlphabetChars(phoneNumber);\n  verifyPunctuationChars(phoneNumber);\n  verifyDigitsLength(digits);\n  verifyCountryCode(digits);\n  verifyAreaCode(digits);\n  verifyExchangeCode(digits);\n\n  return digits.length === 11 ? digits.substring(1) : digits;\n};\n"
  },
  {
    "path": "competitive-programming/exercism/javascript/resistor-color.js",
    "content": "const colorCode = color => COLORS.indexOf(color);\n\nconst COLORS = [\n  \"black\",\n  \"brown\",\n  \"red\",\n  \"orange\",\n  \"yellow\",\n  \"green\",\n  \"blue\",\n  \"violet\",\n  \"grey\",\n  \"white\"\n];\n\nexport { colorCode, COLORS };\n"
  },
  {
    "path": "competitive-programming/exercism/javascript/resistor-colors.js",
    "content": "// https://exercism.io/my/solutions/0a95e6a8ebb94efeac42b2c6e065818b\n\nconst COLORS = [\n  \"black\",\n  \"brown\",\n  \"red\",\n  \"orange\",\n  \"yellow\",\n  \"green\",\n  \"blue\",\n  \"violet\",\n  \"grey\",\n  \"white\"\n];\n\nconst reducer = (acc, resistanceValue) => acc + resistanceValue;\nconst resistanceValuesString = (resistorsColors) =>\n  resistorsColors\n    .map((color) => COLORS.indexOf(color))\n    .reduce(reducer, \"\");\n\nexport const value = (resistorsColors) => {\n  return Number(resistanceValuesString(resistorsColors));\n};\n"
  },
  {
    "path": "competitive-programming/exercism/javascript/reverse-string.js",
    "content": "const lastChar = str => str[str.length - 1];\n\nexport const reverseString = str => {\n  if (str.length <= 1) {\n    return str;\n  }\n\n  return lastChar(str) + reverseString(str.substring(0, str.length - 1));\n};\n"
  },
  {
    "path": "competitive-programming/exercism/javascript/sublist.js",
    "content": "const COMPARISON = {\n  EQUAL: 'EQUAL',\n  SUBLIST: 'SUBLIST',\n  SUPERLIST: 'SUPERLIST',\n  UNEQUAL: 'UNEQUAL',\n};\n\nexport class List {\n  constructor(numbers = []) {\n    this.numbers = numbers;\n  }\n\n  compare(otherList) {\n    const otherNumbers = otherList.numbers;\n    const numbersLength = this.numbers.length;\n    const otherLength = otherNumbers.length;\n\n    if (numbersLength < otherLength) {\n      return this.isSublist(otherNumbers)\n        ? COMPARISON.SUBLIST\n        : COMPARISON.UNEQUAL;\n    }\n\n    if (numbersLength > otherLength) {\n      return this.isSuperList(this.numbers, otherNumbers)\n        ? COMPARISON.SUPERLIST\n        : COMPARISON.UNEQUAL;\n    }\n\n    return this.isIdentical(this.numbers, otherNumbers)\n      ? COMPARISON.EQUAL\n      : COMPARISON.UNEQUAL;\n  }\n\n  isIdentical(numbers, otherList) {\n    if (numbers.length !== otherList.length) return false;\n\n    for (let i = 0; i < numbers.length; i++) {\n      if (numbers[i] !== otherList[i]) return false;\n    }\n\n    return true;\n  }\n\n  isSublist(otherNumbers) {\n    const numbersLength = this.numbers.length;\n    const otherLength = otherNumbers.length;\n\n    for (let i = 0; i < otherLength - numbersLength + 1; i++) {\n      if (\n        this.isIdentical(this.numbers, otherNumbers.slice(i, i + numbersLength))\n      ) {\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  isSuperList(numbers, otherNumbers) {\n    const numbersLength = numbers.length;\n    const otherLength = otherNumbers.length;\n\n    for (let i = 0; i < numbersLength - otherLength + 1; i++) {\n      if (this.isIdentical(numbers.slice(i, i + otherLength), otherNumbers)) {\n        return true;\n      }\n    }\n\n    return false;\n  }\n}\n"
  },
  {
    "path": "competitive-programming/exercism/javascript/sum-of-multiples.js",
    "content": "export const sum = (multiples, limit) => {\n  let sum = 0;\n  let counted = {};\n\n  multiples.forEach((multiple) => {\n    if (!multiple) return;\n\n    let increment = multiple;\n\n    while (increment < limit) {\n      if (!counted[increment]) sum += increment;\n      counted[increment] = true;\n      increment += multiple;\n    }\n  });\n\n  return sum;\n};\n"
  },
  {
    "path": "competitive-programming/exercism/javascript/triangle.js",
    "content": "export function Triangle(side1, side2, side3) {\n  this.side1 = side1;\n  this.side2 = side2;\n  this.side3 = side3;\n}\n\nTriangle.prototype.isEquilateral = function() {\n  return this.side1 == this.side2 && this.side1 == this.side3;\n};\n\nTriangle.prototype.isIsosceles = function() {\n  return (\n    this.side1 == this.side2 ||\n    this.side1 == this.side3 ||\n    this.side2 == this.side3\n  );\n};\n\nTriangle.prototype.anyNonPositiveSide = function() {\n  return this.side1 <= 0 || this.side2 <= 0 || this.side3 <= 0;\n};\n\nTriangle.prototype.isInequality = function() {\n  return (\n    this.side1 > this.side2 + this.side3 ||\n    this.side2 > this.side1 + this.side3 ||\n    this.side3 > this.side2 + this.side1\n  );\n};\n\nTriangle.prototype.kind = function() {\n  if (this.anyNonPositiveSide() || this.isInequality()) {\n    throw \"Not a triangle\";\n  } else if (this.isEquilateral()) {\n    return \"equilateral\";\n  } else if (this.isIsosceles()) {\n    return \"isosceles\";\n  } else {\n    return \"scalene\";\n  }\n};\n"
  },
  {
    "path": "competitive-programming/exercism/javascript/two-fer.js",
    "content": "export const twoFer = (name = \"you\") => `One for ${name}, one for me.`;\n"
  },
  {
    "path": "competitive-programming/hacker-rank/algorithms/strings/palindrome_index.py",
    "content": "# https://www.hackerrank.com/challenges/palindrome-index\n\nimport sys\n\ndef is_palindrome(s):\n    return s == s[::-1]\n\ndef palindrome_index(s):\n    for i in range(len(s)):\n        if is_palindrome(s[i+1:len(s)-i]):\n            return i\n\n        if is_palindrome(s[i:len(s)-i-1]):\n            return len(s)-i-1\n\nq = int(raw_input().strip())\n\nfor num in range(q):\n    s = raw_input().strip()\n    result = palindrome_index(s)\n    print(result)\n"
  },
  {
    "path": "competitive-programming/hacker-rank/algorithms/warmup/birthday_cake_candles.py",
    "content": "# https://www.hackerrank.com/challenges/birthday-cake-candles/problem\n\ndef birthday_cake_candles(n, ar):\n    sorted_ar = sorted(ar, reverse = True)\n    tallest = sorted_ar[0]\n    result = 0\n\n    for candle_height in sorted_ar:\n        if tallest == candle_height:\n            result += 1\n\n    return result\n\nprint(birthday_cake_candles(int(raw_input()), map(int, raw_input().strip().split(' '))))\n"
  },
  {
    "path": "competitive-programming/hacker-rank/algorithms/warmup/mini_max_sum.py",
    "content": "def mini_max_sum(arr):\n    sorted_arr = sorted(arr)\n    print sum(sorted_arr[0:4]), sum(sorted_arr[1:5])\n\nif __name__ == \"__main__\":\n    arr = map(int, raw_input().strip().split(' '))\n    mini_max_sum(arr)\n"
  },
  {
    "path": "competitive-programming/hacker-rank/cpp/introduction/angry_professor.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint t, n, k, time, total_students_arrived_before_class=0;\n\n\tcin >> t;\n\n\twhile (t--) {\n\t\tcin >> n >> k;\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> time;\n\t\t\tif (time <= 0) total_students_arrived_before_class++;\n\t\t}\n\n\t\tif (total_students_arrived_before_class >= k) cout << \"NO\" << endl;\n\t\telse cout << \"YES\" << endl;\n\t\ttotal_students_arrived_before_class=0;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/hacker-rank/cpp/introduction/arrays_introduction.cpp",
    "content": "// https://www.hackerrank.com/challenges/arrays-introduction?h_r=next-challenge&h_v=zen\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\tvector<int> v;\n\tint n, x;\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> x;\n\t\tv.push_back(x);\n\t}\n\n\tfor (int i = v.size()-1; i >= 0; i--) cout << v[i] << \" \";\n\tcout << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/hacker-rank/cpp/introduction/diagonal_difference.cpp",
    "content": "#include <vector>\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  vector< vector<int> > matrix;\n  vector<int> v;\n  int n, diag1=0, diag2=0, temp;\n\n  cin >> n;\n\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < n; j++) {\n      cin >> temp;\n      v.push_back(temp);\n    }\n\n    matrix.push_back(v);\n    v.clear();\n  }\n\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < n; j++) {\n      if (i == j) diag1 += matrix[i][j];\n      if (j == n - 1 - i) diag2 += matrix[i][j];\n    }\n  }\n\n  int result = diag1 - diag2;\n  if (result < 0) result *= -1;\n\n  cout << result << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/hacker-rank/cpp/introduction/input_and_output.cpp",
    "content": "// https://www.hackerrank.com/challenges/cpp-input-and-output\n\n#include <cmath>\n#include <cstdio>\n#include <vector>\n#include <iostream>\n#include <algorithm>\nusing namespace std;\n\nint main() {\n    int a, b, c;\n    cin >> a >> b >> c;\n    cout << a + b + c << endl;\n    return 0;\n}\n"
  },
  {
    "path": "competitive-programming/hacker-rank/cpp/introduction/library_fine.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint day1, day2, month1, month2, year1, year2;\n\n\tcin >> day1 >> month1 >> year1;\n\tcin >> day2 >> month2 >> year2;\n\n\tif (year1 == year2) {\n\t\tif (month1 == month2) {\n\t\t\tif (day1 <= day2)\n\t\t\t\tcout << 0 << endl;\n\t\t\telse\n\t\t\t\tcout << 15 * (day1 - day2) << endl;\n\t\t} else if (month1 > month2) {\n\t\t\tcout << 500 * (month1 - month2) << endl;\n\t\t}\telse {\n\t\t\tcout << 0 << endl;\n\t\t}\n\t} else if (year1 > year2) {\n\t\tcout << 10000 * (year1 - year2) << endl;\n\t} else {\n\t\tcout << 0 << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/hacker-rank/cpp/introduction/plus_minus.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n, temp, num, zeros=0, positives=0, negatives=0;\n\n\tcin >> n;\n\ttemp = n;\n\n\twhile (temp--) {\n\t\tcin >> num;\n\n\t\tif (num > 0) positives++;\n\t\telse if (num < 0) negatives++;\n\t\telse zeros++;\n\t}\n\n\tdouble divisor = n;\n\n\tcout << positives / divisor << endl;\n\tcout << negatives / divisor << endl;\n\tcout << zeros / divisor << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/hacker-rank/cpp/introduction/staircase.cpp",
    "content": "#include <string>\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\tstring result=\"\";\n\n\tcin >> n;\n\tint total = n;\n\n\twhile (n) {\n\n\t\tfor (int i = 1; i < n; i++)\n\t\t\tresult += \" \";\n\n\t\tint num_symbol = total + 1 - n;\n\n\t\tfor (int i = 0; i < num_symbol; i++) {\n\t\t\tresult += \"#\";\n\t\t}\n\n\t\tcout << result << endl;\n\t\tresult.clear();\n\t\tn--;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/hacker-rank/cpp/introduction/time_conversion.cpp",
    "content": "#include <string>\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tstring time;\n\n\tcin >> time;\n\n\tchar letter = time[8];\n\n\tif (letter == 'A'){\n\t\tif (time.substr(0, 2) == \"12\") cout << \"00\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"13\") cout << \"01\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"14\") cout << \"02\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"15\") cout << \"03\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"16\") cout << \"04\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"17\") cout << \"05\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"18\") cout << \"06\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"19\") cout << \"07\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"20\") cout << \"08\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"21\") cout << \"09\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"22\") cout << \"10\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"23\") cout << \"\" + time.substr(2, 6);\n\t\telse cout << time.substr(0, 8);\n\t} else {\n\t\tif (time.substr(0, 2) == \"00\") cout << \"24\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"01\") cout << \"13\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"02\") cout << \"14\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"03\") cout << \"15\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"04\") cout << \"16\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"05\") cout << \"17\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"06\") cout << \"18\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"07\") cout << \"19\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"08\") cout << \"20\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"09\") cout << \"21\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"10\") cout << \"22\" + time.substr(2, 6);\n\t\telse if (time.substr(0, 2) == \"11\") cout << \"23\" + time.substr(2, 6);\n\t\telse cout << time.substr(0, 8);\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/hacker-rank/cpp/introduction/vector_erase.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\t\n\tint time, temp, n;\n\tvector<int> v;\n\n\tcin >> time;\n\n\twhile (time--) {\n\t\tcin >> temp;\n\t\tv.push_back(temp);\n\t}\n\n\tint bla, begin, end;\n\tcin >> bla >> begin >> end;\t\n\n\tcout << end - begin + 1 << endl;\n\n\tv.erase(v.begin() + begin - 1, v.begin() + end);\n\n\tfor (int i = 0; i < v.size(); i++)\n\t\tcout << v[i] << \" \";\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/hacker-rank/cpp/introduction/vector_sort.cpp",
    "content": "#include <vector>\n#include <iostream>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\n\tvector<int> v;\n\n\tint n, temp;\n\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> temp;\n\t\tv.push_back(temp);\n\t}\n\n\tsort(v.begin(), v.end());\n\n\tfor (int i = 0; i < v.size(); i++)\n\t\tcout << v[i] << \" \";\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/hacker-rank/data_structures/trees/in_order_traversal.py",
    "content": "def in_order(node):\n    if node.left:\n        in_order(node.left)\n\n    print node.data,\n\n    if node.right:\n        in_order(node.right)    \n"
  },
  {
    "path": "competitive-programming/hacker-rank/data_structures/trees/post_order_traversal.py",
    "content": "def post_order(node):\n    if node.left:\n        post_order(node.left)\n\n    if node.right:\n        post_order(node.right)\n\n    print(node.data)\n"
  },
  {
    "path": "competitive-programming/hacker-rank/data_structures/trees/pre_order_traversal.py",
    "content": "def pre_order(node):\n    print(node.data)\n\n    if node.left:\n        pre_order(node.left)\n\n    if node.right:\n        pre_order(node.right)\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/array_of_n_elements/array_of_n_elements.clj",
    "content": ";; https://www.hackerrank.com/challenges/fp-array-of-n-elements/problem\n\n(defn array-of-n-elements\n  [n]\n  (range n))\n\n(array-of-n-elements 1)\n(array-of-n-elements 3)\n(array-of-n-elements 5)\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/array_of_n_elements/array_of_n_elements_without_range.clj",
    "content": ";; https://www.hackerrank.com/challenges/fp-array-of-n-elements/problem\n\n(defn array-of-n-elements-without-range\n  [n]\n  (loop [n n list []]\n    (if (pos? n)\n      (recur (dec n) (conj list 0))\n      list)))\n\n(array-of-n-elements-without-range 1)\n(array-of-n-elements-without-range 3)\n(array-of-n-elements-without-range 5)\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/basics/hello_world.clj",
    "content": ";; Problem: https://www.hackerrank.com/challenges/fp-hello-world/problem?h_r=next-challenge&h_v=zen\n\n(print \"Hello World\")\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/basics/hello_world_n_times.clj",
    "content": ";; https://www.hackerrank.com/challenges/fp-hello-world-n-times/problem\n\n(defn greater-than-zero? [n] (> n 0))\n\n(defn hello-word-n-times\n  [n]\n  (if (greater-than-zero? n)\n    (do (println \"Hello World\")\n        (hello-word-n-times (dec n)))))\n\n(hello-word-n-times 4)\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/basics/solve_me_first.clj",
    "content": ";; Problem: https://www.hackerrank.com/challenges/fp-solve-me-first/problem\n\n(defn solve-me-first\n  [a b]\n  (+ a b))\n\n(def a (read-line))\n(def b (read-line))\n\n(println (solve-me-first (Integer/parseInt a) (Integer/parseInt b)))\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/eval_ex/main.clj",
    "content": ";; https://www.hackerrank.com/challenges/eval-ex/problem\n\n;; Approach:\n;; Use map to transform the list of 10 elements from x to (/ (exp x n) (factorial n))\n;; And reduce suming each element\n\n;; For this approach, we can separate in 3 different functions\n;; - exp: exponantial\n;; - factorial\n;; - expansion: function composed of exp and factorial passed to map\n\n;; So we can test these 3 functions\n\n(ns eval-ex\n  (:use [clojure.test]))\n\n(defn exp\n  [x n]\n  (reduce * (repeat n x)))\n\n(defn factorial\n  [n]\n  (reduce * (range 1 (inc n))))\n\n(defn expansion\n  [x]\n  (fn [n]\n    (/ (exp x n) (factorial n))))\n\n(defn series-expansion\n  [x]\n  (read-string\n    (format \"%.4f\"\n      (reduce + (map (expansion x) (range 10))))))\n\n;; -----------------------------------------------------------\n\n;; Tests\n\n(deftest test-exp\n  (testing \"Exponantial function\"\n    (is (= 1 (exp 1 0)))\n    (is (= 1 (exp 1 1)))\n    (is (= 4 (exp 2 2)))))\n\n(deftest test-factorial\n  (testing \"Factorial function\"\n    (is (= 1 (factorial 0)))\n    (is (= 1 (factorial 1)))\n    (is (= 120 (factorial 5)))))\n\n(deftest test-expansion\n  (testing \"Expansion function\"\n    (is (= 1 ((expansion 10) 0)))\n    (is (= 10 ((expansion 10) 1)))\n    (is (= 50 ((expansion 10) 2)))))\n\n(deftest test-series-expansion\n  (testing \"Sample Input - Output\"\n    (is (= 2423600.1887 (series-expansion 20.0000)))\n    (is (= 143.6895 (series-expansion 5.0000)))\n    (is (= 1.6487 (series-expansion 0.5000)))\n    (is (= 0.6065 (series-expansion -0.5000)))))\n\n(run-tests)\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/filter_array/filter_array.clj",
    "content": ";; https://www.hackerrank.com/challenges/fp-filter-array/problem\n\n(defn filter-array\n  [n lst]\n  (filter #(> n %) lst))\n\n(filter-array 25 [-41 46 -28 21 52 83 -29 84 27 40])\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/filter_positions_in_a_list/filter_positions_in_a_list.clj",
    "content": ";; https://www.hackerrank.com/challenges/fp-filter-positions-in-a-list/problem\n\n(defn filter-positions-in-a-list\n  [lst]\n  (take-nth 2 (rest lst)))\n\n(filter-positions-in-a-list [])\n(filter-positions-in-a-list [0 1 2])\n(filter-positions-in-a-list [0 1 2 3 4 5 6 7 8 9])\n(filter-positions-in-a-list [8 15 22 1 10 6 2 18 18 1])\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/list_length/list_length.clj",
    "content": ";; https://www.hackerrank.com/challenges/fp-list-length/problem?h_r=next-challenge&h_v=zen\n\n(defn list-length\n  [lst]\n  (loop [coll lst counter 0]\n    (if (empty? coll)\n      counter\n      (recur (rest coll) (inc counter)))))\n\n(list-length [0 1 2 3 4 5 6 7 8 9])\n(list-length [0 1 2 -1 4 -5 6 7 -8 9])\n(list-length [])\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/list_length/list_length_reduce.clj",
    "content": ";; https://www.hackerrank.com/challenges/fp-list-length/problem?h_r=next-challenge&h_v=zen\n\n(defn list-length\n  [lst]\n  (reduce + (map (constantly 1) lst)))\n\n(list-length [0 1 2 3 4 5 6 7 8 9])\n(list-length [0 1 2 -1 4 -5 6 7 -8 9])\n(list-length [])\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/list_replication/list_replication.clj",
    "content": ";; Problem: https://www.hackerrank.com/challenges/fp-list-replication/problem\n\n(defn list-replication\n  [n list]\n  (sort\n    (flatten\n      (repeat n list))))\n\n(list-replication 3 [1 2 3])\n(list-replication 2 [4 5])\n(list-replication 1 [10 100])\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/reverse_a_list/reverse_a_list.clj",
    "content": ";; https://www.hackerrank.com/challenges/fp-reverse-a-list/problem\n;; last function: returns the last element of a collection\n;; count function: returns the length of a collection\n;; take function: returns the first N taken elements of a collection\n;; not-empty function: returns true if the collection is not empty. Otherwise, false\n\n(def example-list [19 22 3 28 26 17 18 4 28 0])\n\n(defn reverse-a-list\n  [list]\n  (loop [original-list list reversed-list []]\n    (if (not-empty original-list)\n      (recur (take (dec (count original-list)) original-list) (conj reversed-list (last original-list)))\n      reversed-list)))\n\n(reverse-a-list example-list)\n\n;; Implementing an anonymous function\n\n(fn [lst]\n  (loop [original-list lst reversed-list []]\n    (if (not-empty original-list)\n      (recur (take (dec (count original-list)) original-list) (conj reversed-list (last original-list)))\n      reversed-list)))\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/reverse_a_list/reverse_a_list_into.clj",
    "content": ";; https://www.hackerrank.com/challenges/fp-reverse-a-list/problem\n;; basically, the into function is a reduce + conj\n\n(def example-list [19 22 3 28 26 17 18 4 28 0])\n\n(defn reverse-a-list\n  [lst]\n  (into '() lst))\n\n(reverse-a-list example-list)\n\n((fn [lst] (into '() lst)) example-list)\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/reverse_a_list/reverse_a_list_reduce.clj",
    "content": ";; https://www.hackerrank.com/challenges/fp-reverse-a-list/problem\n\n(def example-list [19 22 3 28 26 17 18 4 28 0])\n\n(defn reverse-a-list\n  [lst]\n  (reduce conj '() lst))\n\n(reverse-a-list example-list)\n\n;; Implementing an anonymous function\n\n((fn [lst] (reduce conj '() lst)) example-list)\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/sum_of_odd_elements/sum_of_odd_elements.clj",
    "content": ";; https://www.hackerrank.com/challenges/fp-sum-of-odd-elements/problem\n\n(defn sum-of-odd-elements\n  [lst]\n  (reduce\n    +\n    (filter\n      (odd? n)\n      lst)))\n\n(sum-of-odd-elements [3 2 4 6 5 7 8 0 1])\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/update_list/update_list.clj",
    "content": ";; https://www.hackerrank.com/challenges/fp-update-list/problem\n\n(defn to-absolute\n  [n]\n  (if (neg? n)\n    (+ (* n -2) n)\n    n))\n\n(defn add-element-from-list-to-list\n  [lst1 lst2]\n  (conj lst2 (to-absolute (first lst1))))\n\n(defn update-list\n  [lst]\n  (loop [original-list lst absolute-list []]\n    (if (empty? original-list)\n      absolute-list\n      (recur\n       (rest original-list)\n       (add-element-from-list-to-list original-list absolute-list)))))\n\n(update-list [])\n(update-list [1 2 3 4 5])\n(update-list [-1 -2 -3 -4 -5])\n(update-list [1 -2 3 -4 5])\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/update_list/update_list_anonymous.clj",
    "content": ";; https://www.hackerrank.com/challenges/fp-update-list/problem\n\n(fn\n  [lst]\n  (loop [original-list lst absolute-list []]\n    (if (empty? original-list)\n      absolute-list\n      (recur\n       (rest original-list)\n       (conj\n         absolute-list\n         (if (< (first original-list) 0)\n           (+ (* (first original-list) -2) (first original-list))\n           (first original-list)))))))\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/update_list/update_list_map.clj",
    "content": ";; https://www.hackerrank.com/challenges/fp-update-list/problem\n\n(defn to-absolute\n  [n]\n  (if (neg? n)\n    (+ (* n -2) n)\n    n))\n\n(defn update-list-map\n  [lst]\n  (map to-absolute lst))\n\n(update-list-map [])\n(update-list-map [1 2 3 4 5])\n(update-list-map [-1 -2 -3 -4 -5])\n(update-list-map [1 -2 3 -4 5])\n"
  },
  {
    "path": "competitive-programming/hacker-rank/functional-programming/update_list/update_list_map_anonymous.clj",
    "content": ";; https://www.hackerrank.com/challenges/fp-update-list/problem\n\n(fn\n  [lst]\n  (map\n    (fn\n      [n]\n        (if (neg? n)\n          (+ (* n -2) n)\n          n))\n    lst))\n"
  },
  {
    "path": "competitive-programming/hacker-rank/python/basic_data_types/finding_the_percentage.py",
    "content": "#  https://www.hackerrank.com/challenges/finding-the-percentage/problem\n\nif __name__ == '__main__':\n    n = int(raw_input())\n    student_marks = {}\n\n    for _ in range(n):\n        line = raw_input().split()\n        name, scores = line[0], line[1:]\n        scores = map(float, scores)\n        student_marks[name] = scores\n\n    print('%.2f' %(sum(student_marks[raw_input()]) / 3))\n"
  },
  {
    "path": "competitive-programming/hacker-rank/python/basic_data_types/lists.py",
    "content": "if __name__ == '__main__':\n    N = int(raw_input())\n    l = []\n\n    for i in range(N):\n        u_input = raw_input().split(' ')\n\n        if u_input[0] == 'insert':\n            l.insert(int(u_input[1]), int(u_input[2]))\n        elif u_input[0] == 'remove':\n            l.remove(int(u_input[1]))\n        elif u_input[0] == 'append':\n            l.append(int(u_input[1]))\n        elif u_input[0] == 'sort':\n            l.sort()\n        elif u_input[0] == 'pop':\n            l.pop()\n        elif u_input[0] == 'reverse':\n            l.reverse()\n        else:\n            print(l)\n"
  },
  {
    "path": "competitive-programming/hacker-rank/python/basic_data_types/nested_list.py",
    "content": "# https://www.hackerrank.com/challenges/nested-list/problem\n\nmarksheet = [[raw_input(), float(raw_input())] for _ in range(int(raw_input()))]\nsecond_lowest = sorted(list(set([score for name, score in marksheet])))[1]\nnames = sorted([name for name, score in marksheet if score == second_lowest])\n\nfor name in names:\n    print name\n"
  },
  {
    "path": "competitive-programming/hacker-rank/python/basic_data_types/runner_up_score.py",
    "content": "# [1,6,3,6,5,4]\n# [1,-1]\n# [6, 1]\n# [6, 3]\n# [6, 3]\n# [6, 5]\n# [6, 5]\n\nif __name__ == '__main__':\n    n = int(raw_input())\n    arr = map(int, raw_input().split())\n\n    maximum = -999999999999999999999\n    runner_up = -999999999999999999999\n\n    for el in arr:\n        if el > maximum:\n            runner_up = maximum\n            maximum = el\n        elif el < maximum and el > runner_up:\n            runner_up = el\n\n    print(runner_up)\n"
  },
  {
    "path": "competitive-programming/hacker-rank/python/basic_data_types/tuple.py",
    "content": "# https://www.hackerrank.com/challenges/python-tuples/problem\n\nif __name__ == '__main__':\n    n = int(raw_input())\n    integer_list = map(int, raw_input().split())\n    print(hash(tuple(integer_list)))\n"
  },
  {
    "path": "competitive-programming/hacker-rank/python/introduction/arithmetic_operators.py",
    "content": "if __name__ == '__main__':\n    a = int(raw_input())\n    b = int(raw_input())\n    print(a + b)\n    print(a - b)\n    print(a * b)\n"
  },
  {
    "path": "competitive-programming/hacker-rank/python/introduction/division.py",
    "content": "from __future__ import division\n\nif __name__ == '__main__':\n    a = int(raw_input())\n    b = int(raw_input())\n    print(a // b)\n    print(a / b)\n"
  },
  {
    "path": "competitive-programming/hacker-rank/python/introduction/if_else.py",
    "content": "if __name__ == '__main__':\n    n = int(raw_input())\n\n    if n % 2 != 0:\n        print(\"Weird\")\n    else:\n        if n >= 2 and n <= 5:\n            print(\"Not Weird\")\n        elif n >= 6 and n <= 20:\n            print(\"Weird\")\n        elif n > 20:\n            print(\"Not Weird\")\n"
  },
  {
    "path": "competitive-programming/hacker-rank/python/sets/intro_to_sets.py",
    "content": "# https://www.hackerrank.com/challenges/py-introduction-to-sets/problem\n\ndef average(array):\n    return sum(list(set(array))) / float(len(set(array)))\n"
  },
  {
    "path": "competitive-programming/hacker-rank/python/strings/find_a_string.py",
    "content": "# https://www.hackerrank.com/challenges/find-a-string/problem\n\n# ABCDCDC\n# CDC\n# 2\n\n# ABCDCDCD\n# CD\n# 3\n\n# ABCDCDC\n# AD\n# 0\n\ndef count_substring(string, sub_string):\n    counter = 0\n\n    for index in range(0, len(string) - len(sub_string) + 1):\n        if sub_string == string[index:index + len(sub_string)]:\n            counter += 1\n\n    return counter\n\nprint(count_substring('ABCDCDC', 'CDC'))\nprint(count_substring('ABCDCDCD', 'CD'))\nprint(count_substring('ABCDCDC', 'AD'))\n"
  },
  {
    "path": "competitive-programming/hacker-rank/python/strings/mutate_string.py",
    "content": "# https://www.hackerrank.com/challenges/python-mutations/problem\n\n# abracadabra\n# 5 k\n# abrackdabra\n\ndef mutate_string(string, position, character):\n    mutated_string = ''\n\n    for i in range(len(string)):\n        if i == position:\n            mutated_string += character\n        else:\n            mutated_string += string[i]\n\n    return mutated_string\n\nprint(mutate_string('abracadabra', 5, 'k'))\n"
  },
  {
    "path": "competitive-programming/hacker-rank/python/strings/split_and_join.py",
    "content": "# https://www.hackerrank.com/challenges/python-string-split-and-join/problem\n\n# this is a string => this-is-a-string\n# 123 456 789 => 123-456-789\n# ... ... ... => ...-...-...\n\ndef split_and_join(line):\n    new_line = ''\n\n    for c in line:\n        if c == ' ':\n            new_line += '-'\n        else:\n            new_line += c\n\n    return new_line\n\nprint(split_and_join('this is a string'))\nprint(split_and_join('123 456 789'))\nprint(split_and_join('... ... ...'))\nprint(split_and_join('... ... ...  '))\n"
  },
  {
    "path": "competitive-programming/hacker-rank/python/strings/string_validators.py",
    "content": "# https://www.hackerrank.com/challenges/string-validators/problem\n\nif __name__ == '__main__':\n    s = raw_input()\n    print(any(c.isalnum() for c in s))\n    print(any(c.isalpha() for c in s))\n    print(any(c.isdigit() for c in s))\n    print(any(c.islower() for c in s))\n    print(any(c.isupper() for c in s))\n"
  },
  {
    "path": "competitive-programming/hacker-rank/python/strings/swap_case.py",
    "content": "# https://www.hackerrank.com/challenges/swap-case/problem\n\n# A - Z (65 - 90)\n# a - z (97 - 122)\n\ndef swap_case(s):\n    difference = 32\n    swapped_s = ''\n\n    for i in s:\n        if ord(i) < 65 or (ord(i) > 90 and ord(i) < 97) or ord(i) > 122:\n            swapped_s += i\n        elif ord(i) <= 90:\n            swapped_s += chr(ord(i) + difference)\n        else:\n            swapped_s += chr(ord(i) - difference)\n\n\n    return swapped_s\n\nprint(swap_case('Www.HackerRank.com'))\nprint(swap_case('Pythonist 2'))\nprint(swap_case('HackerRank.com presents \"Pythonist 2\".'))\n"
  },
  {
    "path": "competitive-programming/hacker-rank/python/strings/text_wrap.py",
    "content": "# https://www.hackerrank.com/challenges/text-wrap/problem\n\nimport textwrap\n\ndef wrap(string, max_width):\n    wrapped_text = ''\n\n    for i in range(1, len(string) + 1):\n        if i % max_width == 0:\n            wrapped_text += string[i-1]\n            print(wrapped_text)\n            wrapped_text = ''\n        else:\n            wrapped_text += string[i-1]\n\n    return wrapped_text\n\nprint(wrap('ABCDEFGHIJKLIMNOQRSTUVWXYZ', 4))\n"
  },
  {
    "path": "competitive-programming/hacker-rank/python/strings/whats_your_name.py",
    "content": "# https://www.hackerrank.com/challenges/whats-your-name/problem\n\n# Guido\n# Rossum\n# Hello Guido Rossum! You just delved into python.\n\ndef print_full_name(a, b):\n    print \"Hello %s %s! You just delved into python.\" %(a, b)\n\nprint_full_name('Guido', 'Rossum')\n"
  },
  {
    "path": "competitive-programming/interfatecs/1_2016/a.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n  int marq, n, e;\n  string s;\n\n  while (cin >> marq) {\n    cin >> n;\n    cin.ignore();\n    getline(cin, s);\n    string st = s + s;\n    cin >> e;\n    e = e % n;\n\n    while(st.size() < marq) {\n      st += s;\n    }\n\n    if (marq > n) cout << st.substr(e, n) << endl;\n    else cout << st.substr(e, marq) << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/interfatecs/1_2016/b.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n  int n;\n\n  while (cin >> n && n != -1) {\n    cout << 31 % n << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/interfatecs/1_2016/g.cpp",
    "content": "#include <iostream>\n#include <stdio.h>\n#include <vector>\n#include <string>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\n  int n;\n  double bang;\n  cin >> n;\n\n  while (n--) {\n    vector<float> v;\n    for (int i = 0; i < 12; i++) {\n      cin >> bang;\n      v.push_back(bang);\n    }\n\n    sort(v.begin(), v.end());\n\n    float total = 0;\n\n    for (int i = 3; i < 12; i++) {\n      total += v[i];\n    }\n\n    float media = total / 9;\n\n    if (media * 0.2 < 1.75) {\n      cout << \"REPROVADO\" << endl;\n    } else {\n      double coisa = ((5.75 - (media * 0.2)) / 0.8) * 2;\n      printf(\"%.1f\\n\", coisa);\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/interfatecs/1_2016/i.cpp",
    "content": "#include <iostream>\n#include <stdio.h>\n\nusing namespace std;\n\nint main() {\n\n  double br, ext, h, gastobr, gastoext, cam;\n\n  cin >> br >> ext >> h >> gastobr >> gastoext >> cam;\n  double bang = (br * h * (1 - gastobr / 100) * 1.01);\n  bang += (br * h * (1 - gastobr / 100) * 1.01 * 1.01 * 1.01);\n  bang += (br * h * (1 - gastobr / 100)* 1.01 * 1.01);\n\n  double bang2 = 0;\n  bang2 += (ext * h * cam * (1 - gastoext / 100)* 1.01);\n  bang2 += (ext * h * cam * (1 - gastoext / 100)* 1.01* 1.01);\n  bang2 += (ext * h * cam * (1 - gastoext / 100)* 1.01* 1.01* 1.01);\n\n\n  printf(\"%.2fBR %.2fES\\n\", (bang), bang2);\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/interfatecs/1_2018/a.cpp",
    "content": "// A\r\n\r\n#include <iostream>\r\n#include <bitset>\r\n#include <complex>\r\n#include <cstdlib>\r\n#include <string>\r\n#include <vector>\r\n#include <sstream>\r\n#include <queue>\r\n#include <stack>\r\n#include <deque>\r\n#include <set>\r\n#include <map>\r\n#include <algorithm>\r\n#include <functional>\r\n#include <utility>\r\n\r\nusing namespace std;\r\n\r\n#define DEBUG\r\n\r\n#ifdef DEBUG\r\n\t#define debug(args...) { cerr << #args << \": \"; dbg,args; cerr << endl; }\r\n\t\r\n\tstruct debugger\r\n\t{\r\n\t\ttemplate<typename T> debugger& operator , (const T& v)\r\n\t\t{    \r\n\t\t\tcerr << v << \" \";    \r\n\t\t\treturn *this;    \r\n\t\t}\r\n\t} dbg;\r\n#else\r\n    #define debug(args...)\r\n#endif\r\n\r\nbool maior(const pair<int, int> &a, const pair<int, int> &b) {\r\n\tif (a.second == b.second) {\r\n\t\treturn a.first < b.first;\r\n\t}\r\n\telse {\r\n\t\treturn a.second > b.second;\r\n\t}\r\n}\r\n\r\nint main(void) {\r\n    ios::sync_with_stdio(false);\r\n\t\r\n\tint N;\r\n\t\r\n\tvector<int> quantidades(61, 0);\r\n\tvector< pair<int, int> > pares;\r\n\tvector<int> selecionados;\r\n\t\r\n\tcin >> N;\r\n\r\n\t\r\n\tfor (int i = 0; i < N; i++) {\r\n\t\tfor (int j = 0; j < 6; j++) {\r\n\t\t\tint s;\r\n\t\t\t\r\n\t\t\tcin >> s;\r\n\t\t\t\r\n\t\t\tquantidades[s] += 1;\r\n\t\t}\r\n\t}\r\n\t\r\n\tfor (int i = 1; i <= 60; i++) {\r\n\t\tpares.push_back(make_pair(i, quantidades[i]));\r\n\t}\r\n\t\r\n\tsort(pares.begin(), pares.end(), maior);\r\n\t\r\n\tfor (int i = 0; i < 6; i++) {\r\n\t\tint n;\r\n\t\t\r\n\t\tcin >> n;\r\n\t\t\r\n\t\tselecionados.push_back(pares[n - 1].first);\r\n\t\t\r\n\t}\r\n\t\r\n\tcout << selecionados[0];\r\n\tfor (int i = 1; i < 6; i++) {\r\n\t\tcout << \" \" << selecionados[i];\r\n\t}\r\n\tcout << endl;\r\n\r\n\treturn EXIT_SUCCESS;\r\n}\r\n\r\n\r\n\r\n"
  },
  {
    "path": "competitive-programming/interfatecs/1_2018/b.cpp",
    "content": "#include <iostream>\r\n#include <bitset>\r\n#include <complex>\r\n#include <cstdlib>\r\n#include <string>\r\n#include <vector>\r\n#include <sstream>\r\n#include <queue>\r\n#include <stack>\r\n#include <deque>\r\n#include <set>\r\n#include <map>\r\n#include <algorithm>\r\n#include <functional>\r\n#include <utility>\r\n\r\nusing namespace std;\r\n\r\n#ifdef DEBUG\r\n\t#define debug(args...) { cerr << #args << \": \"; dbg,args; cerr << endl; }\r\n\t\r\n\tstruct debugger\r\n\t{\r\n\t\ttemplate<typename T> debugger& operator , (const T& v)\r\n\t\t{    \r\n\t\t\tcerr << v << \" \";    \r\n\t\t\treturn *this;    \r\n\t\t}\r\n\t} dbg;\r\n#else\r\n    #define debug(args...)\r\n#endif\r\n\r\nint main(void) {\r\n    ios::sync_with_stdio(false);\r\n\t\r\n\tchar C;\r\n\tint N;\r\n\t\r\n\tint TA = 0,\r\n\t\tTV = 0;\r\n\t\r\n\tcin >> C >> ws >> N;\r\n\t\r\n\t\r\n\t\r\n\tfor (int i = 0; i < N; i++) {\r\n\t\tint n;\r\n\t\t\r\n\t\tcin >> n;\r\n\t\t\r\n\t\tif (C == 'V') {\r\n\t\t\tTV += n;\r\n\t\t\tC = 'A';\r\n\t\t}\r\n\t\telse {\r\n\t\t\tTA += n;\r\n\t\t\tC = 'V';\r\n\t\t}\r\n\t}\r\n\r\n\tcout << \"VOCE: \" << TV << \" AMIGO: \" << TA << endl;\r\n\t\r\n\treturn EXIT_SUCCESS;\r\n}\r\n"
  },
  {
    "path": "competitive-programming/interfatecs/1_2018/c.cpp",
    "content": "#include <iostream>\r\n#include <bitset>\r\n#include <complex>\r\n#include <cstdlib>\r\n#include <string>\r\n#include <vector>\r\n#include <sstream>\r\n#include <queue>\r\n#include <stack>\r\n#include <deque>\r\n#include <set>\r\n#include <map>\r\n#include <algorithm>\r\n#include <functional>\r\n#include <utility>\r\n\r\nusing namespace std;\r\n\r\n#ifdef DEBUG\r\n\t#define debug(args...) { cerr << #args << \": \"; dbg,args; cerr << endl; }\r\n\t\r\n\tstruct debugger\r\n\t{\r\n\t\ttemplate<typename T> debugger& operator , (const T& v)\r\n\t\t{    \r\n\t\t\tcerr << v << \" \";    \r\n\t\t\treturn *this;    \r\n\t\t}\r\n\t} dbg;\r\n#else\r\n    #define debug(args...)\r\n#endif\r\n\r\nint main(void) {\r\n    ios::sync_with_stdio(false);\r\n\t\r\n\tint sum = 0;\r\n\t\r\n\tfor (int i = 0; i < 3; i++) {\r\n\t\tint T, Q;\r\n\t\t\r\n\t\tcin >> T >> Q;\r\n\t\t\r\n\t\tsum += T / Q;\r\n\t}\r\n\t\r\n\tcout << sum << endl;\r\n\r\n\treturn EXIT_SUCCESS;\r\n}\r\n"
  },
  {
    "path": "competitive-programming/interfatecs/1_2018/d.py",
    "content": "palavra = input()\r\ndirecoes = input().split(' ')\r\nl, c = list(map(int, input().split(' ')))\r\nmat = []\r\n\r\nlocais_da_primeira_letra = []\r\n\r\nfor i in range(l):\r\n\t\r\n\tlinha = []\r\n\t\r\n\tfor j, letra in enumerate(input()):\r\n\t\tlinha.append(letra)\r\n\t\t\r\n\t\tif letra == palavra[0]:\r\n\t\t\tlocais_da_primeira_letra.append((i, j))\r\n\t\r\n\tmat.append(linha)\r\n\t\r\ndef direction(letter):\r\n\tif letter == 'd':\r\n\t\treturn (0, 1)\r\n\telif letter == 'c':\r\n\t\treturn (-1, 0)\r\n\telif letter == 'b':\r\n\t\treturn (1, 0)\r\n\telse:\r\n\t\treturn (0, -1)\r\n\t\r\ndef letra_correta(i, j, pc):\r\n\treturn 0 <= i < l and 0 <= j < c and mat[i][j] == pc\r\n\t\r\n\t\r\ndef procura(visitados, i, j, palavra, sequencia):\r\n\tif palavra == '':\r\n\t\treturn sequencia\r\n\t\t\t\r\n\tresult = None\r\n\t\r\n\tif (i, j) not in visitados and letra_correta(i, j, palavra[0]):\t\t\r\n\t\tfor direcao in direcoes:\r\n\t\t\tdi, dj = direction(direcao)\t\t\r\n\r\n\t\t\tresult = procura(visitados + [(i, j)], i + di, j + dj, palavra[1:], sequencia + [(i + 1, j + 1)])\r\n\t\t\r\n\t\t\tif result != None:\r\n\t\t\t\tbreak\r\n\t\t\r\n\treturn result\r\n\t\r\n\t\r\nresult = None\r\n\r\nfor i, j in locais_da_primeira_letra:\r\n\tresult = procura([], i, j, palavra, [])\r\n\t\r\n\tif result != None:\r\n\t\tbreak\r\n\t\r\nif result != None:\r\n\tprint(','.join(list(map(str, result))).replace(' ','') + '.')\r\nelse:\r\n\tprint('impossivel!')\r\n\r\n"
  },
  {
    "path": "competitive-programming/interfatecs/1_2018/e.py",
    "content": "linha = input()\r\n\r\nlinha = linha.replace('PQ', '').replace(' ', '')\r\n\r\nlinha_final = ''\r\nespeciais = '?.,!'\r\n\r\n\r\nfor i in range(len(linha)):\r\n\tif linha[i] == 'R':\r\n\t\tif linha[i + 1] in especiais:\r\n\t\t\tpass\r\n\t\telse:\r\n\t\t\tlinha_final += ' '\r\n\telse:\r\n\t\tlinha_final += linha[i]\r\n\t\t\r\n\r\nprint(linha_final)"
  },
  {
    "path": "competitive-programming/interfatecs/1_2018/f.py",
    "content": "codigo_set = set()\r\ncodido_set_saiu = set()\r\n\r\ns = input()\r\ncodigos = input().split(' ')\r\n\r\nfor codigo in codigos:\r\n\tcodigo_set.add(codigo)\r\n\t\r\ni = input()\r\nsaidas = input().split(' ')\r\n\r\nA = 0\r\nI = 0\r\nR = 0\r\n\r\nfor saida in saidas:\r\n\tif saida in codigo_set:\r\n\t\tif saida in codido_set_saiu:\r\n\t\t\tR += 1\r\n\t\telse:\r\n\t\t\tA += 1\r\n\t\t\tcodido_set_saiu.add(saida)\r\n\telse:\r\n\t\tif saida in codido_set_saiu:\r\n\t\t\tR += 1\r\n\t\telse:\r\n\t\t\tI += 1\r\n\t\t\tcodido_set_saiu.add(saida)\r\n\r\nprint('%d A' % A)\r\nprint('%d I' % I)\r\nprint('%d R' % R)\r\n"
  },
  {
    "path": "competitive-programming/interfatecs/1_2018/g.cpp",
    "content": "#include <iostream>\r\n#include <bitset>\r\n#include <complex>\r\n#include <cstdlib>\r\n#include <string>\r\n#include <vector>\r\n#include <sstream>\r\n#include <queue>\r\n#include <stack>\r\n#include <deque>\r\n#include <set>\r\n#include <map>\r\n#include <algorithm>\r\n#include <functional>\r\n#include <utility>\r\n\r\nusing namespace std;\r\n\r\n#ifdef DEBUG\r\n\t#define debug(args...) { cerr << #args << \": \"; dbg,args; cerr << endl; }\r\n\t\r\n\tstruct debugger\r\n\t{\r\n\t\ttemplate<typename T> debugger& operator , (const T& v)\r\n\t\t{    \r\n\t\t\tcerr << v << \" \";    \r\n\t\t\treturn *this;    \r\n\t\t}\r\n\t} dbg;\r\n#else\r\n    #define debug(args...)\r\n#endif\r\n\r\nint main(void) {\r\n    ios::sync_with_stdio(false);\r\n\t\r\n\tstring line;\r\n\t\r\n\tchar c = '\\n';\r\n\tint qc = 0,\r\n\t\tic, jc;\r\n\t\r\n\tchar d = '\\n';\r\n\tint qd = 0,\r\n\t\tid, jd;\r\n\t\r\n\tint z = 0;\r\n\twhile (getline(cin, line)) {\r\n\t\tfor (int i = 0; i < line.length(); i++) {\r\n\t\t\tif (c == '\\n') {\r\n\t\t\t\tc = line[i];\r\n\t\t\t}\r\n\t\t\telse if (c != line[i] && d == '\\n') {\r\n\t\t\t\td = line[i];\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif (line[i] == c) {\r\n\t\t\t\tqc += 1;\r\n\t\t\t\tic = z + 1;\r\n\t\t\t\tjc = i + 1;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tqd += 1;\r\n\t\t\t\tid = z + 1;\r\n\t\t\t\tjd = i + 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tz += 1;\r\n\t}\r\n\t\r\n\t\r\n\tif (qc < qd) {\r\n\t\tcout << \"LINHA \" << ic << \" COLUNA \" << jc << endl;\r\n    }\r\n\telse {\r\n\t\tcout << \"LINHA \" << id << \" COLUNA \" << jd << endl;\r\n\t}\r\n\r\n\r\n\treturn EXIT_SUCCESS;\r\n}\r\n"
  },
  {
    "path": "competitive-programming/interfatecs/1_2018/h.cpp",
    "content": "#include <iostream>\r\n#include <bitset>\r\n#include <complex>\r\n#include <cstdlib>\r\n#include <string>\r\n#include <vector>\r\n#include <sstream>\r\n#include <queue>\r\n#include <stack>\r\n#include <deque>\r\n#include <set>\r\n#include <memory.h>\r\n#include <map>\r\n#include <algorithm>\r\n#include <functional>\r\n#include <utility>\r\n\r\nusing namespace std;\r\n\r\n#ifdef DEBUG\r\n\t#define debug(args...) { cerr << #args << \": \"; dbg,args; cerr << endl; }\r\n\t\r\n\tstruct debugger\r\n\t{\r\n\t\ttemplate<typename T> debugger& operator , (const T& v)\r\n\t\t{    \r\n\t\t\tcerr << v << \" \";    \r\n\t\t\treturn *this;    \r\n\t\t}\r\n\t} dbg;\r\n#else\r\n    #define debug(args...)\r\n#endif\r\n\r\nint A;\r\ndouble R = 0.0;\r\n\r\ndouble saldo[32], resgate[32];\r\n\r\nint main(void) {\r\n    ios::sync_with_stdio(false);\r\n\t\r\n\tfor(int i = 1; i <= 31; i++) {\r\n\t\r\n\t\tsaldo[i] = 0.0;\t\r\n\t\tresgate[i] = 0.0;\r\n\t\r\n\t}\r\n\t\r\n\tcin >> A >> R;\r\n\t\t\r\n\tint temp;\r\n\twhile(cin >> temp) {\r\n\t\tcin >> saldo[temp];\r\n\t}\r\n\t\r\n\tdouble valor_restante = R;\r\n\t\r\n\tdouble cont = 0.0;\r\n\tfor(int dia = 1; dia <= 31; dia++) cont += saldo[dia];\r\n\t\r\n\tif(cont < R) {\r\n\t\tprintf(\"INSUFICIENTE\\n\");\r\n\t\treturn 0;\r\n\t}\r\n\t\r\n\t\r\n\tfor(int dia = A; valor_restante >= 0.0 && dia >= 1; dia--) {\r\n\t\tif(saldo[dia] <= valor_restante) {\r\n\t\t\tresgate[dia] = saldo[dia];\r\n\t\t\tvalor_restante -= resgate[dia];\r\n\t\t} else {\r\n\t\t\tresgate[dia] = valor_restante;\r\n\t\t\tvalor_restante = 0.0;\r\n\t\t}\r\n\t}\r\n\t\r\n\t\r\n\tfor(int dia = 31; valor_restante >= 0.0 && dia > A; dia--) {\r\n\t\tif(saldo[dia] <= valor_restante) {\r\n\t\t\tresgate[dia] = saldo[dia];\r\n\t\t\tvalor_restante -= resgate[dia];\r\n\t\t} else {\r\n\t\t\tresgate[dia] = valor_restante;\r\n\t\t\tvalor_restante = 0.0;\r\n\t\t}\r\n\t}\r\n\t\r\n\tfor(int dia = 1; dia <= 31; dia++) {\r\n\t\tif(resgate[dia] > 0.0) printf(\"%d %.2f (resgate de %.2f)\\n\", dia, saldo[dia] - resgate[dia], resgate[dia]);\r\n\t}\r\n\r\n\treturn EXIT_SUCCESS;\r\n}\r\n"
  },
  {
    "path": "competitive-programming/interfatecs/1_2018/i.py",
    "content": "boletos = []\r\n\r\ntry:\r\n\twhile True:\r\n\t\tboletos.append(input())\r\nexcept EOFError:\r\n\tpass\r\n\t\r\ndef data(data_string):\r\n\tano = data_string[4:6]\r\n\tmes = data_string[2:4]\r\n\tdia =  data_string[0:2]\r\n\t\r\n\treturn int(''.join([ano, mes, dia]))\r\n\t\r\ndef analisar_boleto(boleto):\r\n\tvencimento = boleto[4:10]\r\n\tpagamento = boleto[22:28]\r\n\tvalor_inteiro = boleto[10:16]\r\n\tvalor_decimal = boleto[16:18]\r\n\t\r\n\tvalor = int(valor_inteiro) + int(valor_decimal) / 100\r\n\t\r\n\tif data(pagamento) > data(vencimento):\r\n\t\treturn 0, valor\r\n\telse:\r\n\t\treturn valor, 0\r\n\t\r\ntotal_ad = 0\r\ntotal_id = 0\r\n\r\nfor boleto in boletos:\r\n\tad, id = analisar_boleto(boleto)\r\n\ttotal_ad += ad\r\n\ttotal_id += id\r\n\t\r\nprint('%.2f-ADIMPLENTE' % total_ad)\r\nprint('%.2f-INADIMPLENTE' % total_id)"
  },
  {
    "path": "competitive-programming/interfatecs/1_2018/j.cpp",
    "content": "// J\r\n\r\n#include <iostream>\r\n#include <bitset>\r\n#include <complex>\r\n#include <cstdlib>\r\n#include <string>\r\n#include <vector>\r\n#include <sstream>\r\n#include <queue>\r\n#include <stack>\r\n#include <deque>\r\n#include <set>\r\n#include <map>\r\n#include <memory.h>\r\n#include <algorithm>\r\n#include <functional>\r\n#include <utility>\r\n\r\nusing namespace std;\r\n\r\n#ifdef DEBUG\r\n\t#define debug(args...) { cerr << #args << \": \"; dbg,args; cerr << endl; }\r\n\t\r\n\tstruct debugger\r\n\t{\r\n\t\ttemplate<typename T> debugger& operator , (const T& v)\r\n\t\t{    \r\n\t\t\tcerr << v << \" \";    \r\n\t\t\treturn *this;    \r\n\t\t}\r\n\t} dbg;\r\n#else\r\n    #define debug(args...)\r\n#endif\r\n\r\nbool processado[101][101];\r\nint mapa[101][101];\r\nint L, C, Y, X, D;\r\nint cont = 0;\r\n\r\nvoid preenche(int y, int x) {\r\n\tif(!processado[y][x]) {\r\n\t\tprocessado[y][x] = true;\r\n\t\tcont++;\r\n\t\t\r\n\t\tif(x + 1 <= C && abs(mapa[Y][X] - mapa[y][x+1]) <= D) preenche(y, x+1);\r\n\t\tif(x - 1 >= 1 && abs(mapa[Y][X] - mapa[y][x-1]) <= D) preenche(y, x-1);\r\n\t\tif(y + 1 <= L && abs(mapa[Y][X] - mapa[y+1][x]) <= D) preenche(y+1, x);\r\n\t\tif(y - 1 >= 1 && abs(mapa[Y][X] - mapa[y-1][x]) <= D) preenche(y-1, x);\r\n\t}\r\n\r\n}\r\n\r\nint main(void) {\r\n    ios::sync_with_stdio(false);\r\n\t\r\n\tmemset(processado, false, sizeof processado);\r\n\t\r\n\tcin >> L >> C >> Y >> X >> D;\r\n\t\r\n\tfor(int i = 1; i <= L; i++) {\t\r\n\t\tfor(int j = 1; j <= C; j++) {\t\t\r\n\t\t\tcin >> mapa[i][j];\t\t\r\n\t\t}\t\t\t\r\n\t}\r\n\t\r\n\tpreenche(Y, X);\r\n\t\r\n\tcout << cont << endl;\r\n\t\r\n\r\n\treturn EXIT_SUCCESS;\r\n}\r\n"
  },
  {
    "path": "competitive-programming/spoj-br/aero.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <map>\n\nusing namespace std;\n\nint main() {\n\n  int n1, n2, test=1;\n\n  cin >> n1 >> n2;\n\n  while (n1 + n2 != 0) {\n\n    vector< pair<int, int> > v;\n\n    while (n2--) {\n      int line1, line2;\n      cin >> line1 >> line2;\n      v.push_back(make_pair(line1, line2));\n    }\n\n    map<int, int> mapper;\n\n    for (int i = 0; i < v.size(); i++) {\n      if (mapper.find(v[i].first) != mapper.end()) mapper.find(v[i].first)->second++;\n      else mapper[v[i].first] = 1;\n\n      if (mapper.find(v[i].second) != mapper.end()) mapper.find(v[i].second)->second++;\n      else mapper[v[i].second] = 1;\n    }\n\n    vector<int> lines;\n\n    for (map<int, int>::iterator it = mapper.begin(); it != mapper.end(); ++it) {\n      lines.push_back(it->second);\n    }\n\n    int max=0;\n\n    for (int i = 0; i < lines.size(); i++)\n      if (lines[i] > max) max = lines[i];\n\n    cout << \"Teste \" << test << endl;\n\n    for (int i = 0; i < lines.size(); i++)\n      if (lines[i] == max) printf(\"%d \", i+1);\n\n    printf(\"\\n\\n\");\n\n    test++;\n    cin >> n1 >> n2;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/bafo.cpp",
    "content": "// BAFO\n\n#include <iostream>\n#include <string>\nusing namespace std;\n\nint main() {\n\n  int n, t_beto=0, t_aldo=0, x, y, counter=1;\n  string result;\n\n  cin >> n;\n\n  if(n == 0)\n    return 0;\n\n  while(n != 0) {\n\n    for (int i = 0; i < n; i++) {\n      cin >> x >> y;\n      t_aldo += x;\n      t_beto += y;\n    }\n\n    if (t_aldo > t_beto)\n      result = \"Aldo\";\n    else\n      result = \"Beto\";\n\n    cout << \"Teste \" << counter << endl;\n    cout << result << endl << endl;\n\n    cin >> n;\n    counter++;\n    t_beto = 0;\n    t_aldo = 0;\n  }\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/bapostas.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, num, total=0;\n\n\tcin >> n;\n\n\twhile (n) {\n\n\t\tfor (i = 0; i < n; i++) {\n\t\t\tcin >> num;\n\t\t}\n\n\t\tcin >> n;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/spoj-br/bit.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n#include <string>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\t\n\tint total, test=1;\n\tcin >> total;\n\n\twhile (total != 0) {\n\n\t\tint num = 4;;\n\t\tvector<int> v;\n\n\t\twhile (num--) {\n\t\t\tv.push_back(0);\n\t\t}\n\n\t\twhile (total > 0) {\n\t\t\tif (total >= 50) {\n\t\t\t\ttotal -= 50;\n\t\t\t\tv[0]++;\n\t\t\t} else if (total >= 10) {\n\t\t\t\ttotal -= 10;\n\t\t\t\tv[1]++;\n\t\t\t} else if (total >= 5) {\n\t\t\t\ttotal -= 5;\n\t\t\t\tv[2]++;\n\t\t\t} else {\n\t\t\t\ttotal -= 1;\n\t\t\t\tv[3]++;\n\t\t\t}\n\t\t}\n\n\t\tcout << \"Teste \" << test << endl;\n\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\tcout << v[i] << \" \";\n\t\t}\n\n\t\tcout << endl << endl;\n\n\t\ttest++;\n\t\tcin >> total;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/spoj-br/calcula.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int n, total=0, test=1;\n  cin >> n;\n\n  while (n != 0) {\n\n    for (int i = 0; i < n; i++) {\n      int temp;\n      cin >> temp;\n      total += temp;\n    }\n\n    cout << \"Teste \" << test << endl;\n    cout << total << endl << endl;\n\n    test++;\n    cin >> n;\n    total = 0;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/calculadora.cpp",
    "content": "// CALCU11\n\n#include <iostream>\n#include <iomanip>\nusing namespace std;\n\nint main() {\n\n\tint n, result;\n\tlong double number, total=1;\n\tchar op;\n\n\tcin >> n;\n\n\twhile (n--) {\n\n\t\tcin >> number;\n\t\tcin >> op;\n\n\t\tif (op == '*')\n\t\t\ttotal *= number;\n\t\telse\n\t\t\ttotal /= number;\n\t}\n\n\tcout << fixed << setprecision(0) << total;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/dentista.cpp",
    "content": "// JDENTIST\n\n#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main() {\n\n  int n, x, y, counter=0, status=1;\n  vector<int> consult;\n  vector< vector<int> > memo;\n\n  cin >> n;\n\n  while (n--) {\n\n    cin >> x;\n    cin >> y;\n\n    if (!memo.empty()) {\n      for (int i = 0; i < memo.size(); i++) {\n        if ((x < memo[i][0] && y <= memo[i][0]) || (x >= memo[i][1] && y > memo[i][1])) {\n        } else {\n          status = 0;\n        }\n      }\n    }\n\n    if (status) {\n      counter++;\n      consult.push_back(x);\n      consult.push_back(y);\n      memo.push_back(consult);\n    }\n\n    status = 1;\n    consult.clear();\n  }\n\n  for(int i = 0; i < memo.size(); i++) {\n    cout << memo[i][0] << \" - \" << memo[i][1] << endl;\n  }\n\n  cout << counter;\n\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/desculpa.cpp",
    "content": "#include <stdio.h>\n#include <iostream>\n\nusing namespace std;\n \nint max(int a, int b) { \n  return (a > b)? a : b; \n}\n \nint knapsack(int W, int wt[], int val[], int n) {\n  int i, w;\n  int K[n+1][W+1];\n \n  for (i = 0; i <= n; i++) {\n    for (w = 0; w <= W; w++) {\n      if (i==0 || w==0) K[i][w] = 0;\n      else if (wt[i-1] <= w) K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]],  K[i-1][w]);\n      else K[i][w] = K[i-1][w];\n    }\n  }\n \n  return K[n][W];\n}\n \nint main() {  \n  int W, n, test=1; \n\n  cin >> W >> n;\n \n  while (W + n != 0) {\n \n    int wt[n], val[n];\n \n    for (int i = 0; i < n; i++) {\n      int x, y;\n      cin >> x >> y;\n      wt[i] = x;\n      val[i] = y;\n    }\n \n    cout << \"Teste \" << test << endl;\n    printf(\"%d\", knapsack(W, wt, val, n));\n    cout << endl << endl;\n \n    cin >> W >> n;\n    test++;\n  }  \n  \n  return 0;\n}"
  },
  {
    "path": "competitive-programming/spoj-br/eleicoes1.cpp",
    "content": "#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <map>\n\nusing namespace std;\n\nint main() {\n\n\tint votos, i, num, maior, contagem, candidato;\n\tmap<int, int> mapa;\n\tmap<int,int>::iterator it;\n\n\twhile(scanf(\"%d\", &num) != EOF) {\n\t  mapa.erase ( mapa.begin(), mapa.end());\n\t  maior = candidato = -1;\n\t  contagem = 0;\n\t\n\t\tfor (i = 0; i < num; i++){\n\t\t\tscanf(\"%d\", &votos);\n\t\t\tif (mapa.find(votos) == mapa.end()) mapa[votos] = 1;\n\t\t\telse mapa[votos]++;\n\t\t}\n\n\t\tfor ( it=mapa.begin(); it != mapa.end(); it++ ){\n\t\t\tif ((*it).second > maior) {\n\t\t\t\tmaior = (*it).second;\n\t\t\t\tcandidato = (*it).first;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcout << \"\\n\" << candidato << \"\\n\";\n\t}\n\t\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/spoj-br/eleicoes2.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, temp;\n\tvector<int> v;\t\n\t\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> temp;\n\t\tv.push_back(temp);\n\t}\n\n\tsort(v.begin(), v.end());\n\n\tvector< pair<int, int> > vetorzin;\n\tvetorzin.push_back(make_pair(1, v[0]));\n\n\tfor (int i = 1; i < v.size(); i++) {\n\t\tint found = 0;\n\n\t\tfor (int j = 0; j < vetorzin.size(); j++) {\n\t\t\tif (vetorzin[j].second == v[i]) {\n\t\t\t\tvetorzin[j].first++;\n\t\t\t\tfound = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!found) vetorzin.push_back(make_pair(1, v[i]));\n\t}\n\n\tsort(vetorzin.begin(), vetorzin.end());\n\n\tcout << vetorzin.back().second << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/spoj-br/estagio.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\n\tint n, test=1;\n\tcin >> n;\n\n\twhile (n != 0) {\n\t\tvector< pair<int, int> > v;\n\n\t\twhile (n--) {\n\t\t\tint cod, media;\n\t\t\tcin >> cod >> media;\n\t\t\tv.push_back(make_pair(cod, media));\n\t\t}\n\n\t\tint max = 0;\n\n\t\tfor (int i = 0; i < v.size(); i++)\n\t\t\tif (v[i].second > max) max = v[i].second;\n\n\t\tcout << \"Turma \" << test << endl;\n\n\t\tfor (int i = 0; i < v.size(); i++)\n\t\t\tif (v[i].second == max) cout << v[i].first << \" \";\n\n\t\tcout << endl << endl;\n\n\t\tcin >> n;\n\t\ttest++;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/spoj-br/fatorial.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <stdio.h>\n\nusing namespace std;\n\nint custom_factorial(int n) {\n\n\tint temp, result, flag;\n\t\t\t\n\tvector<int> v(1000000);\n\tv[0] = 1;\n\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (n < 4) v[i] = v[i - 1] * i;\n\t\telse {\n\t\t\tresult = v[i - 1] * i;\n\t\t\tflag = 1;\n\t\t\twhile (flag) {\n\t\t\t\ttemp = result % 10;\n\t\t\t\tif (temp != 0) {\n\t\t\t\t\tv[i] = temp;\n\t\t\t\t\tflag = 0;\n\t\t\t\t} else {\n\t\t\t\t\tresult /= 10;\n\t\t\t\t}\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\n\treturn v[n];\n}\n\nint main() {\n\n\tint n, instance=1;\n\t\n\twhile (scanf(\"%i\", &n) != 0) {\n\n\t\tint result = custom_factorial(n);\t\t\n\n\t\tcout << \"Instancia \" << instance << endl;\n\t\tcout << result << endl;\n\t\tinstance++;\n\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/spoj-br/feyman.cpp",
    "content": "// FEYNMAN\n\n#include <iostream>\nusing namespace std;\n\nint quad(int n) {\n\n  if (n == 1)\n    return 1;\n\n  return ((n * n) + quad(n-1));\n}\n\nint main() {\n\n\tint n;\n\tcin >> n;\n\n\twhile(n != 0) {\n\t\tcout << quad(n) << endl;\n\t\tcin >> n;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/fliperam.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\n  int n1, n2, temp;\n  vector<int> v;\n\n  cin >> n1 >> n2;\n\n  int n = n1;\n\n  while (n--) {\n    cin >> temp;\n    v.push_back(temp);\n  }\n\n  sort(v.begin(), v.end(), greater<int>());\n\n  for (int i = 0; i < n2; i++) {\n    cout << v[i] << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/gangorra.cpp",
    "content": "// JGANGO14\n\n#include <iostream>\nusing namespace std;\n\nint main() {\n\n\tint p1, p2, c1, c2;\n\n\tcin >> p1;\n\tcin >> c1;\n\tcin >> p2;\n\tcin >> c2;\n\n\tif(p1 * c1 == p2 * c2) {\n\t\tcout << 0;\n\t} else if(p1 * c1 > p2 * c2) {\n\t\tcout << -1;\n\t} else {\n\t\tcout << 1;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/guardacosta.cpp",
    "content": "// GUARDCOS\n\n#include <iostream>\n#include <cmath>\nusing namespace std;\n\nint main() {\n\n  float d, f, g, n, distancia_perpendicular = 12;\n\n  while(scanf(\"%f %f %f\", &d, &f, &g) != EOF) {\n    n = sqrt((144 + d*d));\n\n    if ((12 / f) < (n / g))\n      cout << 'N' << endl;\n    else\n      cout << 'S' << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/impedido.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nint main() {\n\t\n\tint n, m, temp1, temp2;\n\tchar result;\n\tvector<int> atacantes;\n\tvector<int> defensores;\n\t\n\tcin >> n;\n\tcin >> m;\n\t\n\twhile (n + m != 0) {\n\t\t\n\t\tfor(int i = 0; i < n; i++) {\n\t\t\tcin >> temp1;\n\t\t\tatacantes.push_back(temp1);\n\t\t}\n\t\t\n\t\tfor(int j = 0; j < m; j++) {\n\t\t\tcin >> temp2;\n\t\t\tdefensores.push_back(temp2);\n\t\t}\n\t\t\n\t\tsort(atacantes.begin(), atacantes.end());\n\t\tsort(defensores.begin(), defensores.end());\n\t\t\n\t\t\n\t\tif (atacantes[0] < defensores[1])\n\t\t\tcout << \"Y\" << endl;\n\t\telse\n\t\t\tcout << \"N\" << endl;\n\t\t\n\t\tcin >> n;\n\t\tcin >> m;\n\t\tatacantes.clear();\n\t\tdefensores.clear();\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/letra.cpp",
    "content": "// LETRA14\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <iomanip>\nusing namespace std;\n\nint main() {\n\n\tint end, start=0, n=0;\n\tfloat total;\n\tstring frase, letra, last;\n\tvector<string> palavras;\n\n\tgetline(cin, letra);\n\tgetline(cin, frase);\n\n\tistringstream iss(frase);\n\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(palavras));\n\n\tfor(int i = 0; i < palavras.size(); i++) {\n\t\tif(palavras[i].find(letra) != string::npos)\n\t\t\tn++;\n\t}\n\n\ttotal = palavras.size();\n\n\tcout << fixed << setprecision(1) << (n / total) * 100;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/loopmusi.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, picos=0, temp;\n\tvector<int>\tloop;\n\n\tcin >> n;\n\n\twhile (n != 0) {\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> temp;\n\t\t\tloop.push_back(temp);\n\t\t}\n\n\t\tloop.push_back(loop[0]);\n\t\tloop.push_back(loop[1]);\n\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tif ((loop[i] > loop[i-1] && loop[i] > loop[i+1]) || (loop[i] < loop[i-1] && loop[i] < loop[i+1])) picos++;\n\t\t}\n\n\t\tcout << picos << endl;\n\n\t\tpicos = 0;\n\t\tloop.clear();\n\t\tcin >> n;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/spoj-br/lua.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\n\tint n1, n2, test=1;\n\tcin >> n1 >> n2;\t\n\n\twhile (n1 + n2 != 0) {\n\n\t\tvector<int> v;\n\n\t\tfor (int i = 0; i < n1; i++) {\n\t\t\tint temp;\n\t\t\tcin >> temp;\n\t\t\tv.push_back(temp);\n\t\t}\n\n\t\tint total = 0;\n\n\t\tfor (int i = 0; i < n2; i++)\n\t\t\ttotal += v[i];\n\n\t\tint max = (total / n2);\n\t\tint min = (total / n2);\n\n\t\tfor (int i = n2; i < n1; i++) {\n\t\t\ttotal -= v[i-n2];\n\t\t\ttotal += v[i];\n\n\t\t\tint media = total / n2;\n\n\t\t\tif (media > max) max = media;\n\t\t\tif (media < min) min = media;\n\t\t}\n\n\t\tcout << \"Teste \" << test << endl;\n\t\tcout << min << \" \" << max << endl << endl;\n\n\t\ttest++;\n\t\tcin >> n1 >> n2;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/spoj-br/macaco.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\n\tint n, test=1;\n\tcin >> n;\n\n\twhile (n) {\n\n\t\tvector< vector<int> > retangulos;\t\t\n\t\tint temp;\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\n\t\t\tvector<int> points;\n\t\t\tint time = 4;\n\t\t\t\n\t\t\twhile (time--) {\n\t\t\t\tcin >> temp;\n\t\t\t\tpoints.push_back(temp);\n\t\t\t}\n\n\t\t\tretangulos.push_back(points);\n\t\t}\n\n\t\tint point1x=-10001, point1y=10001, point2x=10001, point2y=-10001;\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (retangulos[i][0] > point1x && retangulos[i][1] < point1y) {\n\t\t\t\tpoint1x = retangulos[i][0];\n\t\t\t\tpoint1y = retangulos[i][1];\t\t\t\t\n\t\t\t}\n\n\t\t\tif (retangulos[i][1] < point2x && retangulos[i][3] > point2y) {\t\t\t\t\n\t\t\t\tpoint2x = retangulos[i][2];\n\t\t\t\tpoint2y = retangulos[i][3];\n\t\t\t}\n\t\t}\n\n\t\tcout << \"Teste \" << test << endl;\n\n\t\tint correct=0;\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (point1x >= retangulos[i][0] && point1y <= retangulos[i][1] && point2x <= retangulos[i][2] && point2y >= retangulos[i][3]) correct++;\n\t\t}\n\n\t\tif (correct != n) cout << \"nenhum\" << endl << endl;\n\t\telse cout << point1x << \" \" << point1y << \" \" << point2x << \" \" << point2y << endl << endl;\n\n\t\tcin >> n;\n\t\ttest++;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/spoj-br/minhoca.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\n\tint n1, n2;\n\tcin >> n1 >> n2;\n\n\tvector< vector<int> > matrix;\n\n\tfor (int i = 0; i < n1; i++) {\n\t\tvector<int> v;\n\n\t\tfor (int j = 0; j < n2; j++) {\n\t\t\tint temp;\n\t\t\tcin >> temp;\n\t\t\tv.push_back(temp);\n\t\t}\n\n\t\tmatrix.push_back(v);\n\t}\n\n\tint max = 0;\n\n\tfor (int i = 0; i < n1; i++) {\n\t\tint total = 0;\n\n\t\tfor (int j = 0; j < n2; j++) {\n\t\t\ttotal += matrix[i][j];\n\t\t}\n\n\t\tif (total > max) max = total;\n\t}\n\n\tfor (int j = 0; j < n2; j++) {\n\t\tint total = 0;\n\n\t\tfor (int i = 0; i < n1; i++) {\n\t\t\ttotal += matrix[i][j];\n\t\t}\n\n\t\tif (total > max) max = total;\n\t}\n\n\tcout << max << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/spoj-br/miojo.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\n  int t, n1, n2, result;\n  cin >> t >> n1 >> n2;\n\n  while (1) {\n\n    if (n1 - n2 == t) {\n      result = n1;\n      break;\n    }\n\n    if (n2 - n1 == t) {\n      result = n2;\n      break;\n    }\n\n    if (n1 < n2) n1 += n1;\n    else n2 += n2;\n\n  }\n\n  cout << result << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/obi.cpp",
    "content": "// OBI8\n\n#include <iostream>\nusing namespace std;\n\nint main() {\n\n\tint competidores, pontos, p1, p2, count=0;\n\n\tcin >> competidores;\n\tcin >> pontos;\n\n\twhile (competidores--) {\n\t\tcin >> p1;\n\t\tcin >> p2;\n\n\t\tif (p1 + p2 >= pontos)\n\t\t\tcount++;\n\t}\n\n\tcout << count;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/obihanoi.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <math.h>\n\nusing namespace std;\n\nint main() {\n\n  int n, test=1;\n  cin >> n;\n\n  while (n != 0) {\n\n    long long int times = pow(2, n) - 1;\n\n    cout << \"Teste \" << test << endl;\n    cout << times << endl << endl;\n\n    times=0;\n    test++;\n    cin >> n;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/parprox.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <math.h>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\tvector< pair<int, int> > vec;\n\tvector<double> v;\n\n\tcin >> n;\n\n\tif (n <= 1) {\n\t\tcout << 0 << endl;\n\t\treturn 0;\n\t}\n\n\twhile (n--) {\n\t\tint n1, n2;\n\t\tcin >> n1 >> n2;\n\t\tvec.push_back(make_pair(n1, n2));\n\t}\n\n\tfor (int i = 0; i < vec.size()-1; i++) {\n\t\tfor (int j = i + 1; j < vec.size(); j++) {\n\t\t\tint x = vec[i].first - vec[j].first;\n\t\t\tint y = vec[i].second - vec[j].second;\n\n\t\t\tif (x < 0) x *= (-1);\n\t\t\tif (y < 0) y *= (-1);\n\n\t\t\tdouble result = hypot(x, y);\n\t\t\tv.push_back(result);\n\t\t}\n\t}\n\n\tsort(v.begin(), v.end());\n\n\tcout.precision(3);\n\tcout << fixed << v[0] << endl;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/peca.cpp",
    "content": "// PECA7\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\n\tint time, result, temp;\n\tvector<int> numbers;\n\n\tcin >> time;\n\tresult = time;\n\n\tfor(int i = 0; i < time-1; i++) {\n\t\tcin >> temp;\n\t\tnumbers.push_back(temp);\n\t}\n\n\tsort(numbers.begin(), numbers.end());\n\n\tfor(int j = 0; j < numbers.size(); j++) {\n\t\tif (j+1 != numbers[j]) {\n\t\t\tresult = j+1;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tcout << result;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/primo.cpp",
    "content": "// br.spoj.com/problems/PRIMO/\n\n#include <iostream>\n#include <math.h>\n\nusing namespace std;\n\nlong long int is_prime(int num) {\n  int number = num;\n  int total_divisivel = 0;\n\n  if (num < 0) number = -(number);\n\n  if (number == 0 || number == 1) return 0;\n  else if (number == 2) return 1;\n  else if (number % 2 == 0) return 0;\n\n  int s = sqrt(number);\n\n  for (int i = 3; i <= s; i += 2)\n    if (number % i == 0) return 0;\n\n  return 1;\n}\n\nint main() {\n\n  long long int n;\n\n  cin >> n;\n\n  if (is_prime(n)) cout << \"sim\" << endl;\n  else cout << \"nao\" << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/rumo9s.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int n;\n  cin >> n;\n\n  while (n != 0) {\n\n\n\n    cin >> n;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/saldo.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\n  int n, test=1;\n  cin >> n;\n\n  while (n != 0) {\n\n    for (int i = 0; i < n; i++) {\n\n    }\n\n\n    cout << \"Teste \" + test << endl;\n\n    cin >> n;\n    test++;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/saldo13.cpp",
    "content": "// SALDO13\n\n#include <iostream>\nusing namespace std;\n\nint main() {\n\n\tint n, s, menor_saldo, total, temp;\n\n\tcin >> n;\n\tcin >> s;\n\tmenor_saldo = s;\n\ttotal = s;\n\n\twhile(n--) {\n\t\tcin >> temp;\n\t\ttotal += temp;\n\t\tif (total < menor_saldo)\n\t\t\tmenor_saldo = total;\n\t}\n\n\tcout << menor_saldo;\n\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/sorvete.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\t\n\tint test=1, s, p;\n\tvector< pair<int, int> > vetorzin;\n\tvector< pair<int, int> > v;\n\n\tcin >> p >> s;\n\n\twhile (s + p != 0) {\n\n\t\tfor (int i = 0; i < s; i++) {\n\t\t\tint n1, n2;\n\t\t\tcin >> n1 >> n2;\n\t\t\tvetorzin.push_back(make_pair(n1, n2));\t\t\t\n\t\t}\n\n\t\tsort(vetorzin.begin(), vetorzin.end());\n\n\t\tv.push_back(make_pair(vetorzin[0].first, vetorzin[0].second));\n\n\t\tfor (int i = 1; i < s; i++) {\n\t\t\tif (v.back().second < vetorzin[i].first) v.push_back(make_pair(vetorzin[i].first, vetorzin[i].second));\n\t\t\telse if (v.back().second < vetorzin[i].second) v.back().second = vetorzin[i].second;\n\t\t}\n\n\t\tcout << \"Teste \" << test << endl;\n\n\t\tfor (int i = 0; i < v.size(); i++) {\n\t\t\tcout << v[i].first << \" \" << v[i].second << endl;\n\t\t}\n\n\t\tcout << endl;\n\t\tv.clear();\n\t\tvetorzin.clear();\n\t\ttest++;\n\t\tcin >> p >> s;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/spoj-br/sudoku.cpp",
    "content": "// SPOJ Problem Set (seletivas) - SUDOIME\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstring correct_sudoku(vector< vector<int> > matrix) {\n\n\tvector<int> vetorzin_1;\n\tvector<int> vetorzin_2;\n\n\tfor (int i = 0; i < 9; i++) {\n\t\tfor (int j = 0; j < 9; j++) {\n\t\t\tvetorzin_1.push_back(matrix[i][j]);\n\t\t\tvetorzin_2.push_back(matrix[j][i]);\n\t\t}\n\n\t\tsort(vetorzin_1.begin(), vetorzin_1.end());\n\t\tsort(vetorzin_2.begin(), vetorzin_2.end());\n\n\t\tfor (int j = 0; j < 9; j++) {\n\t\t\tif ((vetorzin_1[j] != j+1) || (vetorzin_2[j] != j+1))\n\t\t\t\treturn \"NAO\";\n\t\t}\n\n\t\tvetorzin_1.clear();\n\t\tvetorzin_2.clear();\n\t}\n\n}\n\nint main() {\n\n\tint n, counter=1, temp;\n\tstring result=\"SIM\";\n\tvector<int> vetor;\n\tvector< vector<int> > matrix;\n\n\tcin >> n;\n\n\twhile(n--) {\n\n\t\tfor (int i = 0; i < 9; i++) {\n\t\t\tfor (int j = 0; j < 9; j++) {\n\t\t\t\tcin >> temp;\n\t\t\t\tvetor.push_back(temp);\n\t\t\t}\n\t\t\tmatrix.push_back(vetor);\n\t\t\tvetor.clear();\n\t\t}\n\n\t\tresult = correct_sudoku(matrix);\n\n\t\tcout << \"Instancia \" << counter << endl;\n\t\tcout << result << endl;\n\t\tresult=\"SIM\";\n\t\tmatrix.clear();\n\t\tcounter++;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/telefone.cpp",
    "content": "// TEL8\n\n#include <iostream>\n#include <string>\nusing namespace std;\n\nint main() {\n\n\tstring number, result=\"\";\n\n\tcin >> number;\n\n\tfor(int i = 0; i < number.length(); i++)\n\t\tif (number[i] == 'A' || number[i] == 'B' || number[i] == 'C')\n\t\t\tresult += \"2\";\n\t\telse if (number[i] == 'D' || number[i] == 'E' || number[i] == 'F')\n\t\t\tresult += \"3\";\n\t\telse if (number[i] == 'G' || number[i] == 'H' || number[i] == 'I')\n\t\t\tresult += \"4\";\n\t\telse if (number[i] == 'J' || number[i] == 'K' || number[i] == 'L')\n\t\t\tresult += \"5\";\n\t\telse if (number[i] == 'M' || number[i] == 'N' || number[i] == 'O')\n\t\t\tresult += \"6\";\n\t\telse if (number[i] == 'P' || number[i] == 'Q' || number[i] == 'R' || number[i] == 'S')\n\t\t\tresult += \"7\";\n\t\telse if (number[i] == 'T' || number[i] == 'U' || number[i] == 'V')\n\t\t\tresult += \"8\";\n\t\telse if (number[i] == 'W' || number[i] == 'X' || number[i] == 'Y' || number[i] == 'Z')\n\t\t\tresult += \"9\";\n\t\telse\n\t\t\tresult += number[i];\n\n\t\tcout << result;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/transporte.cpp",
    "content": "// TRANSP11\n\n#include <iostream>\nusing namespace std;\n\nint main() {\n\n\tint a, b, c, x, y, z;\n\n\tcin >> a >> b >> c >> x >> y >> z;\n\n\tif ((a > x) || (b > y) || (c > z))\n\t\tcout << 0;\n\telse {\n\t\tcout << ((x/a) * (y/b) * (z/c));\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/spoj-br/troco13.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\n\tint n1, n2;\n\tcin >> n1 >> n2;\n\n\tint total = 0;\n\n\twhile (n2--) {\n\t\tint n;\n\t\tcin >> n;\n\n\t\tif (total + n <= n1) total += n;\n\t}\n\n\tif (total == n1) cout << \"S\" << endl;\n\telse cout << \"N\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/spoj-br/vivo.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\n\tint n1, n2, test=1;\n\tscanf(\"%d %d\", &n1, &n2);\n\n\twhile (n1 + n2 != 0) {\n\n\t\tint temp;\n\t\tvector<int> v;\n\n\t\tfor (int i = 0; i < n1; i++) {\n\t\t\tscanf(\"%d\", &temp);\n\t\t\tv.push_back(temp);\n\t\t}\n\n\t\twhile (n2--) {\n\t\t\tint n, j, erasing=0;\n\t\t\tscanf(\"%d %d\", &n, &j);\n\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\tint t;\n\t\t\t\tscanf(\"%d\", &t);\n\t\t\t\t\n\t\t\t\tif (t != j) {\n\t\t\t\t\tv.erase(v.begin() + i - erasing);\n\t\t\t\t\terasing++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcout << \"Teste \" << test << endl;\n\t\tcout << v[0] << endl << endl;\t\t\n\n\t\ttest++;\n\t\tscanf(\"%d %d\", &n1, &n2);\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/spoj-br/wcw.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvector<int> merge(vector<int>& vec, const vector<int>& left, const vector<int>& right) {\n\n  vector<int> result;\n  unsigned left_it = 0, right_it = 0;\n\n  while (left_it < left.size() && right_it < right.size()) {\n    if (left[left_it] < right[right_it]) {\n      result.push_back(left[left_it]);\n      left_it++;\n    } else {\n      result.push_back(right[right_it]);\n      right_it++;\n    }\n  }\n\n  while (left_it < left.size()) {\n    result.push_back(left[left_it]);\n    left_it++;\n  }\n\n  while (right_it < right.size()) {\n    result.push_back(right[right_it]);\n    right_it++;\n  }\n\n  vec = result;\n  return vec;\n}\n\nvector<int> merge_sort(vector<int>& vec) {\n\n  if (vec.size() == 1)\n    return vec;\n\n  vector<int>::iterator middle = vec.begin() + (vec.size() / 2);\n\n  vector<int> left(vec.begin(), middle);\n  vector<int> right(middle, vec.end());\n\n  left = merge_sort(left);\n  right = merge_sort(right);\n\n  return merge(vec, left, right);\n}\n\nint main() {\n\n\tint n;\n\tcin >> n;\n\n\twhile (n--) {\n\t\tint x, temp;\n\t\tcin >> x;\n\n\t\tvector<int> v;\n\n\t\twhile (x--) {\n\t\t\tcin >> temp;\n\t\t\tv.push_back(temp);\n\t\t}\n\n\t\tcout << merge_sort(v) << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/timus/a+b_problem.cpp",
    "content": "// http://acm.timus.ru/problem.aspx?space=1&num=1000\n\n#include<iostream>\n\nusing namespace std;\n\nint main() {\n  int n1, n2;\n  cin >> n1 >> n2;\n  cout << n1 + n2 << endl;\n}\n"
  },
  {
    "path": "competitive-programming/ucoder/armstrong_numbers.cpp",
    "content": "#include <stdio.h>\n#include <math.h>\n#include <string>\n#include <vector>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\n    long int n;\n    scanf(\"%li\", &n);\n    vector<int> vetor;\n\n    while (n != 0) {\n\n        int total = 0, temp = n, teste, result=0;\n\n        while (temp != 0) {\n            teste = temp % 10;\n            vetor.push_back(teste);\n            temp = temp / 10;\n        }\n\n        for (int i = 2; i < 10; i++) {\n            total = 0;\n            for (int j = 0; j < vetor.size(); j++) {\n                total += pow(vetor[j], i);\n            }\n\n            if (total == n) {\n                result = i;\n                break;\n            }\n        }\n\n        if (result)\n            cout << result << endl;\n        else\n            cout << \"N\" << endl;\n\n    \tscanf(\"%li\", &n);\n        vetor.clear();\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "competitive-programming/ucoder/historico_de_comandos.cpp",
    "content": "#include <iostream>\n#include <map>\n#include <vector>\nusing namespace std;\n\nint main() {\n\n    int n, x;\n\n    while (cin >> n && n != 0) {\n        int total = 0;\n        map<int, int> m;\n        vector<int> v;\n        int aux;\n\n        for (int i = 0; i < n; ++i) {\n            cin >> x;\n            v.push_back(x);\n            m[x] = x;\n        }\n\n        map<int, int>::iterator it;\n\n        for (int i = 0; i < n; ++i) {\n            aux = v[i];\n            total += m[aux];\n            for (it = m.begin(); it != m.end(); ++it) {\n                it->second++;\n            }\n            m[aux] = 1;\n        }\n\n        cout << total << endl;\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "competitive-programming/ucoder/imperador_cassius.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main() {\n\n    int n1, n2, n=1;\n\n    while (cin >> n1 && n1 != 0) {\n        cin >> n2;\n        cout << \"Instancia \" << n << endl;\n\n        if (n1 == 1 && n2 == 2) cout << \"segundo\" << endl;\n        else if (n1 == 1 && n2 == 3) cout << \"primeiro\" << endl;\n        else if (n1 == 2 && n2 == 1) cout << \"primeiro\" << endl;\n        else if (n1 == 2 && n2 == 3) cout << \"segundo\" << endl;\n        else if (n1 == 3 && n2 == 1) cout << \"segundo\" << endl;\n        else if (n1 == 3 && n2 == 2) cout << \"primeiro\" << endl;\n        else cout << \"empate\" << endl;\n        cout << endl;\n        n++;\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "competitive-programming/ucoder/matriz_esparsa.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, x, total, zeros, medium;\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> x;\n\t\ttotal = x * x;\n\t\tzeros = total - (3 * x - 2);\n\t\tmedium = total / 2;\n\t\tif (zeros > medium) cout << \"S \" << zeros << endl;\n\t\telse cout << \"N \" << zeros << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/ucoder/obi.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main() {\n\n    int n, n1, n2, total, counter = 0;\n\n    cin >> n >> total;\n\n    while (n--) {\n        cin >> n1 >> n2;\n        if (n1 + n2 >= total) counter++;\n    }\n\n    cout << counter << endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "competitive-programming/ucoder/tsetse.cpp",
    "content": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main() {\n\t\n\tint n1, n2, x, instance = 1;\n\tcin >> n1 >> n2;\n\t\n\twhile (n1 + n2 != 0) {\n\t\tif (n1 == 0 || n2 == 0) {\n\t\t\tcout << \"Instancia \" << instance << endl;\n\t\t\tcout << \"sim\" << endl;\n\t\t} else {\n\t\t\tvector<int> v;\n\t\t\tvector< vector<int> > matrix;\n\t\t\t\n\t\t\tfor (int i = 0; i < n1; ++i) {\n\t\t\t\tfor (int j = 0; j < n2; ++j) {\n\t\t\t\t\tcin >> x;\n\t\t\t\t\tv.push_back(x);\n\t\t\t\t}\n\t\t\t\tmatrix.push_back(v);\n\t\t\t\tv.clear();\n\t\t\t}\n\t\t\t\n\t\t\tint n, i = 0, j = 0, counter = 1;\n\t\t\t\n\t\t\twhile (true) {\n\t\t\t\tn = matrix[i][j];\n\t\t\t\t\n\t\t\t\tif (n == 1) {\n\t\t\t\t\tif (i == 0) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmatrix[i][j] = 0;\n\t\t\t\t\t\ti--;\n\t\t\t\t\t}\n\t\t\t\t} else if (n == 2) {\n\t\t\t\t\tif (i == 0 || j == n2-1) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmatrix[i][j] = 0;\n\t\t\t\t\t\ti--;\n\t\t\t\t\t\tj++;\n\t\t\t\t\t}\n\t\t\t\t} else if (n == 3) {\n\t\t\t\t\tif (j == n2-1) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmatrix[i][j] = 0;\n\t\t\t\t\t\tj++;\n\t\t\t\t\t}\n\t\t\t\t} else if (n == 4) {\n\t\t\t\t\tif (j == n2-1 || i == n1-1) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmatrix[i][j] = 0;\n\t\t\t\t\t\tj++;\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t} else if (n == 5) {\n\t\t\t\t\tif (i == n1-1) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmatrix[i][j] = 0;\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t} else if (n == 6) {\n\t\t\t\t\tif (j == 0 || i == n1-1) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmatrix[i][j] = 0;\n\t\t\t\t\t\tj--;\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t} else if (n == 7) {\n\t\t\t\t\tif (j == 0) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmatrix[i][j] = 0;\n\t\t\t\t\t\tj--;\n\t\t\t\t\t}\n\t\t\t\t} else if (n == 8) {\n\t\t\t\t\tif (j == 0 || i == 0) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmatrix[i][j] = 0;\n\t\t\t\t\t\tj--;\n\t\t\t\t\t\ti--;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcounter++;\n\t\t\t\tif (matrix[i][j] == 0) break;\n\t\t\t}\n\t\t\t\n\t\t\tcout << \"Instancia \" << instance << endl;\n\t\t\t\n\t\t\tif (counter == n1 * n2) cout << \"sim\" << endl;\n\t\t\telse cout << \"nao\" << endl;\n\t\t}\n\n\t\tcin >> n1 >> n2;\n\t\tif (n1 + n2 != 0) cout << endl;\n\t\tinstance++;\n\t}\n\t\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/3d_virtual_museum.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2548\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n  int N, M, num, total;\n  vector<int> V;\n\n  while (cin >> N >> M) {\n    total = 0;\n\n    while (N--) {\n      cin >> num;\n      V.push_back(num);\n    }\n\n    sort(V.begin(), V.end(), greater<int>());\n\n    for (int i = 0; V.size() > 0 && i < M; i++) total += V[i];\n    cout << total << endl;\n    V.clear();\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/a_long_time_ago.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1962\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\tcin >> n;\n\n\tlong long int n1;\n\n\twhile (n--) {\n\n\t\tcin >> n1;\n\n\t\tif (n1 >= 2015) {\n\t\t\tcout << n1 - 2014 << \" A.C.\" << endl;\n\t\t} else {\n\t\t\tcout << 2015 - n1 << \" D.C.\" << endl;\n\t\t}\n\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/above_average.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1214\n\n#include <iostream>\n#include <vector>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  int n;\n  cin >> n;\n\n  while (n--) {\n    int x, temp;\n    double total = 0;\n    cin >> x;\n    vector<int> v;\n\n    for (int i = 0; i < x; i++) {\n      cin >> temp;\n      v.push_back(temp);\n      total += temp;\n    }\n\n    double average = total / x;\n    double counter = 0;\n\n    for (int i = 0; i < x; i++) if (v[i] > average) counter++;\n\n    cout << fixed << setprecision(3) << (counter / x) * 100.00 << \"%\" << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/above_secundary_diagonal.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1185\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  vector< vector<double> > v1;\n  double n, total=0;\n  string operation;\n\n  cin >> operation;\n\n  for (int i = 0; i < 12; i++) {\n    vector<double> v;\n\n    for (int j = 0; j < 12; j++) {\n      cin >> n;\n      v.push_back(n);\n    }\n\n    v1.push_back(v);\n  }\n\n  int counter = 11, count = 0;\n\n  for (int i = 0; i < 11; i++) {\n    for (int j = 0; j < counter; j++) {\n      total += v1[i][j];\n      count++;\n    }\n\n    counter--;\n  }\n\n  if (operation == \"S\") cout << fixed << setprecision(1) << total << endl;\n  else cout << fixed << setprecision(1) << total / count << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/above_the_main_diagonal.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1183\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  vector< vector<double> > v1;\n  double n, total=0;\n  string operation;\n\n  cin >> operation;\n\n  for (int i = 0; i < 12; i++) {\n    vector<double> v;\n\n    for (int j = 0; j < 12; j++) {\n      cin >> n;\n      v.push_back(n);\n    }\n\n    v1.push_back(v);\n  }\n\n  int counter = 1, count = 0;\n\n  for (int i = 0; i < 12; i++) {\n    for (int j = counter; j < 12; j++) {\n      total += v1[i][j];\n      count++;\n    }\n\n    counter++;\n  }\n\n  if (operation == \"S\") cout << fixed << setprecision(1) << total << endl;\n  else cout << fixed << setprecision(1) << total / count << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/abracadabra.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2484\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n  string s;\n\n  while (getline(cin, s)) {\n    for (int i = 0; i < s.size(); i++) {\n      for (int j = 0; j < i; j++) cout << \" \";\n\n      for (int j = 0; j < s.size()-i; j++) {\n        if (j == 0) cout << s[j];\n        else cout << \" \" << s[j];\n      }\n      cout << endl;\n    }\n    cout << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/advancing_letters.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main() {\n  string s1 = \"abcdefghiz\", s2 = \"aaaaaaaaaa\";\n\n  int counter = 0, counter1 = 0, counter2 = 0, counterz = 0;\n\n  for (int i = 0; i < s1.size(); i++) counterz += 'z';\n  for (int i = 0; i < s1.size(); i++) counter1 += s1[i];\n  for (int i = 0; i < s2.size(); i++) counter2 += s2[i];\n\n  cout << counterz - counter1 + counter1 - counter2 << endl;\n  cout << counterz << endl;\n  cout << counter1 << endl;\n  cout << counter2 << endl;\n\n  for (int i = 0; i < s1.size(); i++) {\n    counter += (s2[i] - s1[i]);\n  }\n\n  //cout << counter << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/age_in_day.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1020\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint time, year=0, month=0, day=0;\n\n\tcin >> time;\n\n\twhile (time >= 365) {\n\t\ttime -= 365;\n\t\tyear++;\n\t}\n\n\twhile (time >= 30) {\n\t\ttime -= 30;\n\t\tmonth++;\n\t}\n\n\twhile (time >= 1) {\n\t\ttime -= 1;\n\t\tday++;\n\t}\n\n\tcout << year << \" ano(s)\" << endl;\n\tcout << month << \" mes(es)\" << endl;\n\tcout << day << \" dia(s)\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/ages.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1154\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  int n, number=0;\n  double total=0;\n\n  cin >> n;\n\n  while (n >= 0) {\n    total += n;\n    number++;\n    cin >> n;\n  }\n\n  cout << fixed << setprecision(2) << total / number << endl;\n\n  return 0;\n}\n\n"
  },
  {
    "path": "competitive-programming/uri/alarm_clock.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1103\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int h1, m1, h2, m2, minutes=0;\n\n  cin >> h1 >> m1 >> h2 >> m2;\n\n  while (h1 + m1 + h2 + m2 != 0) {\n\n    if (h1 == h2 && m1 == m2) {\n      minutes = 1440;\n    } else {\n      if (h1 > h2) {\n        if (m2 > m1) {\n          minutes = 1440 - (h1 - h2) * 60 + (m2 - m1);\n        } else if (m1 > m2) {\n          minutes = 1440 - (h1 - h2) * 60 + (m2 - m1);\n        } else {\n          minutes = 1440 - (h1 - h2) * 60;\n        }\n      } else if (h2 > h1) {\n        if (m1 > m2) {\n          minutes = (h2 - h1) * 60 + m2 - m1;\n        } else if (m2 > m1) {\n          minutes = (h2 - h1) * 60 + m2 - m1;\n        } else {\n          minutes = (h2 - h1) * 60;\n        }\n      } else {\n        if (m2 > m1) {\n          minutes = m2 - m1;\n        } else {\n          minutes = 1440 + m2 - m1;\n        }\n      }\n    }\n\n    cout << minutes << endl;\n    cin >> h1 >> m1 >> h2 >> m2;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/alliteration.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1263\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nvoid split_by_space(vector<string> &words, string phrase) {\n  int index_start=0, length;\n  string aux;\n  for (int i = 0; i < phrase.size(); i++) {\n    if (phrase[i] == ' ') {\n      length = i - index_start;\n      aux = phrase.substr(index_start, length);\n      words.push_back(aux);\n      index_start = i + 1;\n    } else if (i == phrase.size()-1) {\n      length = i - index_start + 1;\n      aux = phrase.substr(index_start, length);\n      words.push_back(aux);\n    }\n  }\n}\n\nint main() {\n\n  string phrase;\n  string alphabet = \"ABCDEFGHIJKLMNOPQRSTUVXWYZabcdefghijklmnopqrstuvxwyzABCDEFGHIJKLMNOPQRSTUVXWYZ\";\n  vector<string> words;\n\n  while (getline(cin, phrase)) {\n    vector<int> alli;\n    alli.push_back(0);\n    split_by_space(words, phrase);\n    char current_letter = words[0][0]; // first letter of the first word\n\n    if (words.size() > 1) {\n      for (int i = 1; i < words.size(); i++) {\n        int letter_pos = alphabet.find(words[i][0]);\n        if (current_letter == alphabet[letter_pos] || current_letter == alphabet[letter_pos + 26]) {\n          alli.back()++;\n        } else {\n          alli.push_back(0);\n        }\n\n        current_letter = words[i][0];\n      }\n\n      int counter = 0;\n\n      for (int i = 0; i < alli.size(); i++) if (alli[i] > 0) counter++;\n\n      cout << counter << endl;\n\n    } else {\n      cout << 0 << endl;\n    }\n\n    words.clear();\n    alli.clear();\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/andys_first_dictionary.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1215\n\n#include <iostream>\n#include <string>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nvector<string> parseString(string word) {\n  vector<string> v;\n  int len = 0, base = 0, ascChar;\n\n  for (int i = 0; i < word.size(); i++) {\n    ascChar = word[i];\n    if (ascChar < 65 || (ascChar > 90 && ascChar < 97) || ascChar > 122) {\n      v.push_back(word.substr(base, len));\n      base = i+1;\n      len = -1;\n    }\n\n    len++;\n  }\n\n  v.push_back(word.substr(base, len));\n\n  return v;\n}\n\nstring lowerCase(string word) {\n  string lowerCaseWord = \"\";\n  char charac;\n  int ascChar;\n\n  for (int i = 0; i < word.size(); i++) {\n    ascChar = word[i];\n    if (ascChar >= 65 && ascChar <= 90) {\n      charac = ascChar + 32;\n      lowerCaseWord += charac;\n    } else {\n      lowerCaseWord += word[i];\n    }\n  }\n\n  return lowerCaseWord;\n}\n\nint main() {\n  string word, parsedWord;\n  set<string> s;\n  vector<string> v;\n\n  while (cin >> word) {\n    v = parseString(word);\n    for (int i = 0; i < v.size(); i++) {\n      parsedWord = lowerCase(v[i]);\n      if (parsedWord != \"\" && parsedWord != \" \") s.insert(parsedWord);\n    }\n  }\n\n  for (set<string>::iterator it = s.begin(); it != s.end(); ++it)\n    cout << *it << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/angry_ducks.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1163\n\n#include <stdio.h>\n#include <math.h>\n\n#define PI      3.14159\n#define g       9.80665\n\ndouble rad(double angle) {\n  return (angle / 180.0) * PI;\n}\n\nint main() {\n  double h, alfa, v, t, Vx, Vy, x, aux1, aux2, p1, p2;\n  int n;\n  char character;\n\n  while (scanf(\"%lf %lf %lf %d\", &h, &p1, &p2, &n) > 0) {\n    aux1 = (2*h)/g;\n\n    for (; n > 0; n--) {\n      scanf(\"%lf %lf\", &alfa, &v);\n\n      Vx = v * cosf(rad(alfa));\n      Vy = v * sinf(rad(alfa));\n\n      aux2 = Vy/g;\n\n      t = sqrtf(aux1 + powf(aux2, 2)) + aux2;\n\n      x = Vx * t;\n\n      character = (x >= p1 && x <= p2) ? 'D': 'N';\n\n      printf(\"%.5lf -> %cUCK\\n\", x, character);\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/animal.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1049\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n\tstring s1, s2, s3;\n\n\tcin >> s1 >> s2 >> s3;\n\n\tif (s1 == \"vertebrado\") {\n\t\tif (s2 == \"ave\") {\n\t\t\tif (s3 == \"carnivoro\") {\n\t\t\t\tcout << \"aguia\" << endl;\n\t\t\t} else {\n\t\t\t\tcout << \"pomba\" << endl;\n\t\t\t}\n\t\t} else {\n\t\t\tif (s3 == \"onivoro\") {\n\t\t\t\tcout << \"homem\" << endl;\n\t\t\t} else {\n\t\t\t\tcout << \"vaca\" << endl;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (s2 == \"inseto\") {\n\t\t\tif (s3 == \"hematofago\") {\n\t\t\t\tcout << \"pulga\" << endl;\n\t\t\t} else {\n\t\t\t\tcout << \"lagarta\" << endl;\n\t\t\t}\n\t\t} else {\n\t\t\tif (s3 == \"hematofago\") {\n\t\t\t\tcout << \"sanguessuga\" << endl;\n\t\t\t} else {\n\t\t\t\tcout << \"minhoca\" << endl;\n\t\t\t}\n\t\t}\t\t\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/approximate_number_of_primes.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2159\n\n#include <iostream>\n#include <math.h>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\tlong long int n;\n\tlong double min, max;\n\tcin >> n;\n\tmin = n / log(n);\n\tmax = min * 1.25506;\n\tcout << fixed << setprecision(1) << min << \" \" << max << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/area.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1012\n\n#include <iostream>\n#include <math.h>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n\tconst double PI = 3.14159;\n\tfloat n1, n2, n3;\n\tcin >> n1 >> n2 >> n3;\n\n\tcout << fixed << setprecision(3) << \"TRIANGULO: \" << n1 * n3 / 2 << endl;\n\tcout << fixed << setprecision(3) << \"CIRCULO: \" << PI * pow(n3, 2) << endl;\n\tcout << fixed << setprecision(3) << \"TRAPEZIO: \" << (n1 + n2) * n3 / 2 << endl;\n\tcout << fixed << setprecision(3) << \"QUADRADO: \" << n2 * n2 << endl;\n\tcout << fixed << setprecision(3) << \"RETANGULO: \" << n1 * n2 << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/area_of_circle.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1002\n\n#include <iostream>\n#include <iomanip>\n#include <math.h>\n\nusing namespace std;\n\nint main() {\n\n  const double PI = 3.14159;\n  double r;\n  cin >> r;\n\n  cout << fixed << setprecision(4) << \"A=\" << PI * pow(r, 2) << endl;\n\n  return 0;\n}\n\n"
  },
  {
    "path": "competitive-programming/uri/arranging_tasks.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1704\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nstruct task {\n  int V, T;\n};\n\nbool sortByTime(task &ta1, task &ta2) {\n  if (ta1.V >= ta2.V) return true;\n  else if (ta1.V < ta2.V) return false;\n  else return ta1.T <= ta2.T;\n}\n\nint main() {\n\tint N, H, V, T;\n\n\twhile (cin >> N >> H) {\n    vector<task> tasks;\n\n    while (N--) {\n      cin >> V >> T;\n      task ta;\n      ta.V = V;\n      ta.T = T;\n      tasks.push_back(ta);\n    }\n\n    sort(tasks.begin(), tasks.end(), sortByTime);\n\n    int value = 0;\n\n    for (int i = 0; i < H && i < 10; i++) {\n      if (tasks[i].T <= H) value += tasks[i].V;\n    }\n\n    cout << value << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/array_123.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1534\n\n#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\tint n, one, two;\n\n\twhile (cin >> n) {\n\t\tvector<string> numbers;\n\t\tstring num;\n\t\tone = 0;\n\t\ttwo = n-1;\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tnum = \"\";\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tif (one == j && one == two) num += \"2\";\n\t\t\t\telse if (one == j) num += \"1\";\n\t\t\t\telse if (two == j) num += \"2\";\n\t\t\t\telse num += \"3\";\n\t\t\t}\n\n\t\t\tone++;\n\t\t\ttwo--;\n\t\t\tnumbers.push_back(num);\n\t\t}\n\n\t\tfor (int i = 0; i < numbers.size(); i++) {\n\t\t\tcout << numbers[i] << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/array_change_1.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1175\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\n\tvector<int> v1;\n\tvector<int> v2;\n\tint n, x;\n\n\tfor (int i = 0; i < 20; i++) {\n\t\tcin >> n;\n\t\tv1.push_back(n);\n\t}\n\n\tfor (int i = 19; i >= 0; i--) {\t\t\n\t\tx = v1[i];\n\t\tv2.push_back(x);\n\t}\n\n\tfor (int i = 0; i < 20; i++) cout << \"N[\" << i << \"] = \" << v2[i] << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/array_fill_1.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1173\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\n\tint n, count;\n\tcin >> n;\n\n\tvector<int> v;\n\n\twhile (count < 10) {\n\t\tv.push_back(n);\n\t\tn *= 2;\n\t\tcount++;\n\t}\n\n\tfor (int i = 0; i < 10; i++) {\n\t\tcout << \"N[\" << i << \"] = \" << v[i] << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/array_fill_2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1177\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\n\tint n, counter=0;\n\tcin >> n;\n\n\tvector<int> v;\n\n\tfor (int i = 0; i < 1000; i++) {\n\t\tv.push_back(counter);\n\t\tif (counter == n-1) counter = 0;\n\t\telse counter++;\n\t}\n\n\tfor (int i = 0; i < 1000; i++) {\n\t\tcout << \"N[\" << i << \"] = \" << v[i] << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/array_fill_3.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1178\n\n#include <iostream>\n#include <vector>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n\tdouble n;\n\tcin >> n;\n\n\tvector<double> v;\n\n\tfor (int i = 0; i < 100; i++) {\n\t\tv.push_back(n);\n\t\tn /= 2;\n\t}\n\n\tfor (int i = 0; i < 100; i++) {\n\t\tcout << fixed << setprecision(4) << \"N[\" << i << \"] = \" << v[i] << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/array_fill_4.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1179\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nbool is_full(vector<int> &v) {\n  if (v.size() == 5) return true;\n  return false;\n}\n\nint main() {\n\n  vector<int> even;\n  vector<int> odd;\n  int num;\n\n  for (int i = 0; i < 15; i++) {\n\n    cin >> num;\n    if (num % 2 == 0) even.push_back(num);\n    else odd.push_back(num);\n\n    if (is_full(odd)) {\n      for (int j = 0; j < 5; j++) cout << \"impar[\" << j << \"] = \" << odd[j] << endl;\n      odd.clear();\n    }\n\n    if (is_full(even)) {\n      for (int j = 0; j < 5; j++) cout << \"par[\" << j << \"] = \" << even[j] << endl;\n      even.clear();\n    }\n\n  }\n\n  for (int o_index = 0; o_index < odd.size(); o_index++) cout << \"impar[\" << o_index << \"] = \" << odd[o_index] << endl;\n\n  for (int e_index = 0; e_index < even.size(); e_index++) cout << \"par[\" << e_index << \"] = \" << even[e_index] << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/array_hash.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1257\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, m;\n\tcin >> n;\n\n\tstring alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n\twhile (n--) {\t\t\n\t\tcin >> m;\n\t\tint total = 0;\n\t\tstring code;\n\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tcin >> code;\n\t\t\tfor (int j = 0; j < code.size(); j++) total += alphabet.find(code[j]) + i + j;\t\t\t\n\t\t}\n\n\t\tcout << total << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/array_replacement_1.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1172\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\n\tvector<int> v;\n\n\tfor (int i = 0; i < 10; i++) {\n\t\tcin >> n;\n\n\t\tif (n <= 0) v.push_back(1);\n\t\telse v.push_back(n);\n\t}\n\n\tfor (int i = 0; i < 10; i++) {\n\t\tcout << \"X[\" << i << \"] = \" << v[i] << endl;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/array_selection_1.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1174\n\n#include <iostream>\n#include <vector>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n\tdouble n;\n\tvector<double> v;\n\n\tfor (int i = 0; i < 100; i++) {\n\t\tcin >> n;\n\t\tv.push_back(n);\n\t}\n\n\tfor (int i = 0; i < 100; i++) if (v[i] <= 10) cout << fixed << setprecision(1) << \"A[\" << i << \"] = \" << v[i] << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/as_abas_de_pericles.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2061\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n1, n2;\n\tstring s;\n\tcin >> n1 >> n2;\n\n\tfor (int i = 0; i < n2; i++) {\n\t\tcin >> s;\n\t\tif (s == \"fechou\") n1++;\n\t\telse n1--;\n\t}\n\n\tcout << n1 << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/ascending_and_descending.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1113\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n1, n2;\n\tcin >> n1 >> n2;\n\n\twhile(n1 != n2) {\n\n\t\tif (n1 > n2) {\n\t\t\tcout << \"Decrescente\" << endl;\n\t\t} else {\n\t\t\tcout << \"Crescente\" << endl;\n\t\t}\n\n\t\tcin >> n1 >> n2;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/assigning_teams.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2345\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\tint n;\n\tvector<int> v;\n\n\tfor (int i = 0; i < 4; i++)\t{\n\t\tcin >> n;\n\t\tv.push_back(n);\n\t}\n\n\tsort(v.begin(), v.end());\n\n\tint diff1, diff2;\n\tdiff1 = v[3] + v[0];\n\tdiff2 = v[2] + v[1];\n\n\tif (diff1 > diff2) cout << diff1 - diff2 << endl;\n\telse cout << diff2 - diff1 << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/automated_checking_machine.cpp",
    "content": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main() {\n\tint n;\n\tvector<int> v;\n\tchar result = 'Y';\n\t\n\tfor (int i = 0; i < 5; i++) {\n\t\tcin >> n;\n\t\tv.push_back(n);\n\t}\n\t\n\tfor (int i = 0; i < 5; i++) {\n\t\tcin >> n;\n\t\tif (n == v[i]) {\n\t\t\tresult = 'N';\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tcout << result << endl;\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/average_1.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1005\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  double a, b;\n  cin >> a >> b;\n\n  cout << fixed << setprecision(5) << \"MEDIA = \" << (a * 3.5 + b * 7.5) / 11 << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/average_2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1006\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  double a, b, c;\n  cin >> a >> b >> c;\n\n  cout << fixed << setprecision(1) << \"MEDIA = \" << (a * 2 + b * 3 + c * 5) / 10 << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/average_3.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1040\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n\t// weights 2, 3, 4 e 1\n\tdouble n1, n2, n3, n4, n5;\n\n\tcin >> n1 >> n2 >> n3 >> n4;\n\n\tdouble final = (n1 * 2 + n2 * 3 + n3 * 4 + n4) / 10;\n\n\tcout << fixed << setprecision(1) << \"Media: \" << final << endl;\n\n\tif (final >= 7.0) {\n\t\tcout << \"Aluno aprovado.\" << endl;\n\t} else if (final >= 5.0) {\n\t\tcin >> n5;\n\t\tcout << \"Aluno em exame.\" << endl;\n\t\tcout << \"Nota do exame: \" << n5 << endl;\n\n\t\tfinal = (final + n5) / 2;\n\n\t\tif (final >= 5.0) {\n\t\t\tcout << \"Aluno aprovado.\" << endl;\n\t\t} else {\n\t\t\tcout << \"Aluno reprovado.\" << endl;\n\t\t}\n\n\t\tcout << fixed << setprecision(1) << \"Media final: \" << final << endl;\n\t} else {\n\t\tcout << \"Aluno reprovado.\" << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/average_speed.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1304\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\t\n\t\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/back_to_high_school_physics.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1197\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int n1, n2;\n\n  while (scanf(\"%d %d\", &n1, &n2) != EOF) cout << n1 * n2 * 2 << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/bacteria_1.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2356\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n  string s1, s2;\n\n  while (getline(cin, s1) && getline(cin, s2)) {\n    if (s1.find(s2) == string::npos) cout << \"Nao resistente\" << endl;\n    else cout << \"Resistente\" << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/banknotes.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1018\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n1;\n\n\tcin >> n1;\n\n\tcout << n1 << endl;\n\n\tint total = n1;\n\tint cem=0, cinquenta=0, vinte=0, dez=0, cinco=0, dois=0, um=0;\n\n\twhile (total >= 100) {\n\t\ttotal -= 100;\n\t\tcem++;\n\t}\n\n\twhile (total >= 50) {\n\t\ttotal -= 50;\n\t\tcinquenta++;\n\t}\n\n\twhile (total >= 20) {\n\t\ttotal -= 20;\n\t\tvinte++;\n\t}\n\n\twhile (total >= 10) {\n\t\ttotal -= 10;\n\t\tdez++;\n\t}\n\n\twhile (total >= 5) {\n\t\ttotal -= 5;\n\t\tcinco++;\n\t}\n\n\twhile (total >= 2) {\n\t\ttotal -= 2;\n\t\tdois++;\n\t}\n\n\twhile (total >= 1) {\n\t\ttotal -= 1;\n\t\tum++;\n\t}\n\n\tcout << cem << \" nota(s) de R$ 100,00\" << endl;\n\tcout << cinquenta << \" nota(s) de R$ 50,00\" << endl;\n\tcout << vinte << \" nota(s) de R$ 20,00\" << endl;\n\tcout << dez << \" nota(s) de R$ 10,00\" << endl;\n\tcout << cinco << \" nota(s) de R$ 5,00\" << endl;\n\tcout << dois << \" nota(s) de R$ 2,00\" << endl;\n\tcout << um << \" nota(s) de R$ 1,00\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/banknotes_and_coins.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1021\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tfloat total;\n\tint cem=0, cinquenta=0, vinte=0, dez=0, cinco=0, dois=0, um=0;\n\tint cinquenta_centavos=0, vinte_e_cinco_centavos=0, dez_centavos=0, cinco_centavos=0, um_centavos=0;\n\n\tcin >> total;\n\n\twhile (total >= 100) {\n\t\ttotal -= 100;\n\t\tcem++;\n\t}\n\n\twhile (total >= 50) {\n\t\ttotal -= 50;\n\t\tcinquenta++;\n\t}\n\n\twhile (total >= 20) {\n\t\ttotal -= 20;\n\t\tvinte++;\n\t}\n\n\twhile (total >= 10) {\n\t\ttotal -= 10;\n\t\tdez++;\n\t}\n\n\twhile (total >= 5) {\n\t\ttotal -= 5;\n\t\tcinco++;\n\t}\n\n\twhile (total >= 2) {\n\t\ttotal -= 2;\n\t\tdois++;\n\t}\n\n\twhile (total >= 1) {\n\t\ttotal -= 1;\n\t\tum++;\n\t}\n\n\twhile (total >= 0.5) {\n\t\ttotal -= 0.50;\n\t\tcinquenta_centavos++;\n\t}\n\n\twhile (total >= 0.25) {\n\t\ttotal -= 0.25;\n\t\tvinte_e_cinco_centavos++;\n\t}\n\n\twhile (total >= 0.10) {\n\t\ttotal -= 0.10;\n\t\tdez_centavos++;\n\t}\n\n\twhile (total >= 0.05) {\n\t\ttotal -= 0.05;\n\t\tcinco_centavos++;\n\t}\n\n\twhile (total >= 0.01) {\n\t\ttotal -= 0.01;\n\t\tum_centavos++;\n\t}\n\n\tcout << \"NOTAS:\" << endl;\n\tcout << cem << \" nota(s) de R$ 100.00\" << endl;\n\tcout << cinquenta << \" nota(s) de R$ 50.00\" << endl;\n\tcout << vinte << \" nota(s) de R$ 20.00\" << endl;\n\tcout << dez << \" nota(s) de R$ 10.00\" << endl;\n\tcout << cinco << \" nota(s) de R$ 5.00\" << endl;\n\tcout << dois << \" nota(s) de R$ 2.00\" << endl;\n\n\tcout << \"MOEDAS:\" << endl;\n\tcout << um << \" moeda(s) de R$ 1.00\" << endl;\n\tcout << cinco_centavos << \" moeda(s) de R$ 0.50\" << endl;\n\tcout << vinte_e_cinco_centavos << \" moeda(s) de R$ 0.25\" << endl;\n\tcout << dez_centavos << \" moeda(s) de R$ 0.10\" << endl;\n\tcout << cinco_centavos << \" moeda(s) de R$ 0.05\" << endl;\n\tcout << um_centavos << \" moeda(s) de R$ 0.01\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/baskharas_formula.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1036\n\n#include <iostream>\n#include <math.h>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n\tdouble a, b, c;\n\n\tcin >> a >> b >> c;\n\n\tdouble delta = pow(b, 2) - 4 * a * c;\n\n\tif (delta > 0 && a != 0) {\n\t\tcout << fixed << setprecision(5) << \"R1 = \" << ((-1) * b + sqrt(delta)) / (2 * a) << endl;\n\t\tcout << fixed << setprecision(5) << \"R2 = \" << ((-1) * b - sqrt(delta)) / (2 * a) << endl;\n\t} else {\n\t\tcout << \"Impossivel calcular\" << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/batmain.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2510\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n  int N;\n  string name;\n  cin >> N;\n\n  while (N--) {\n    cin.ignore();\n    getline(cin, name);\n    if (name != \"Batmain\") cout << \"Y\" << endl;\n    else cout << \"N\" << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/bazinga.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1828\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\tcin >> n;\n\n\tstring player1, player2;\n\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> player1 >> player2;\n\t\tcout << \"Caso #\" << i << \": \";\n\n\t\tif (player1 == player2) {\n\t\t\tcout << \"De novo!\" << endl;\n\t\t}\telse {\n\t\t\tif (player1 == \"tesoura\") {\n\t\t\t\tif (player2 == \"papel\" || player2 == \"lagarto\") cout << \"Bazinga!\" << endl;\n\t\t\t\telse cout << \"Raj trapaceou!\" << endl;\n\t\t\t} else if (player1 == \"papel\") {\n\t\t\t\tif (player2 == \"pedra\" || player2 == \"Spock\") cout << \"Bazinga!\" << endl;\n\t\t\t\telse cout << \"Raj trapaceou!\" << endl;\n\t\t\t} else if (player1 == \"pedra\") {\n\t\t\t\tif (player2 == \"lagarto\" || player2 == \"tesoura\") cout << \"Bazinga!\" << endl;\n\t\t\t\telse cout << \"Raj trapaceou!\" << endl;\n\t\t\t} else if (player1 == \"lagarto\") {\n\t\t\t\tif (player2 == \"Spock\" || player2 == \"papel\") cout << \"Bazinga!\" << endl;\n\t\t\t\telse cout << \"Raj trapaceou!\" << endl;\n\t\t\t} else if (player1 == \"Spock\") {\n\t\t\t\tif (player2 == \"tesoura\" || player2 == \"pedra\") cout << \"Bazinga!\" << endl;\n\t\t\t\telse cout << \"Raj trapaceou!\" << endl;\n\t\t\t}\n\t\t}\n\t}\t\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/below_the_main_diagonal.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1184\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  vector< vector<double> > v1;\n  double n, total=0;\n  string operation;\n\n  cin >> operation;\n\n  for (int i = 0; i < 12; i++) {\n    vector<double> v;\n\n    for (int j = 0; j < 12; j++) {\n      cin >> n;\n      v.push_back(n);\n    }\n\n    v1.push_back(v);\n  }\n\n  int counter = 1, count = 0;\n\n  for (int i = 1; i < 12; i++) {\n    for (int j = 0; j < counter; j++) {\n      total += v1[i][j];\n      count++;\n    }\n\n    counter++;\n  }\n\n  if (operation == \"S\") cout << fixed << setprecision(1) << total << endl;\n  else cout << fixed << setprecision(1) << total / count << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/below_the_secundary_diagonal.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1186\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  vector< vector<double> > v1;\n  double n, total=0;\n  string operation;\n\n  cin >> operation;\n\n  for (int i = 0; i < 12; i++) {\n    vector<double> v;\n\n    for (int j = 0; j < 12; j++) {\n      cin >> n;\n      v.push_back(n);\n    }\n\n    v1.push_back(v);\n  }\n\n  int counter = 11, count = 0;\n\n  for (int i = 1; i < 12; i++) {\n    for (int j = counter; j < 12; j++) {\n      total += v1[i][j];\n      count++;\n    }\n\n    counter--;\n  }\n\n  if (operation == \"S\") cout << fixed << setprecision(1) << total << endl;\n  else cout << fixed << setprecision(1) << total / count << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/bill.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1866\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int n;\n  cin >> n;\n\n  while (n--) {\n    int x;\n    cin >> x;\n\n    if (x % 2 == 0) cout << 0 << endl;\n    else cout << 1 << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/bingo.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1136\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n\nusing namespace std;\n\nbool isPossible(const set<int> s, int n) {\n\tint i = 0;\n\n\tif (n > *s.rbegin()) return false;\n\n\tfor (set<int>::iterator it = s.begin(); it != s.end(); it++) {\n\t\tif (*it != i) return false;\n\t\ti++;\n\t}\n\n\treturn true;\n}\n\nint main() {\n\tint n, b, x;\n\n\twhile (cin >> n && cin >> b && n + b != 0) {\n\t\tvector<int> v;\n\t\tset<int> s;\n\n\t\tfor (int i = 0; i < b; i++) {\n\t\t\tcin >> x;\n\t\t\tv.push_back(x);\n\t\t}\n\n\t\tsort(v.begin(), v.end());\n\n\t\tfor (int i = v.size()-1; i >= 0; i--) {\n\t\t\tfor (int j = i; j >= 0; j--) {\n\t\t\t\ts.insert(v[i] - v[j]);\n\t\t\t}\n\t\t}\n\n\t\tif (isPossible(s, n)) cout << \"Y\" << endl;\n\t\telse cout << \"N\" << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/bla.cpp",
    "content": "//\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n  string \"QWERTYUIOP[]-ASDFGHJKL;'ZXCVBNM,./\";\n\n  string phrase;\n  cin >> phrase;\n\n  for (int i = 0; i < phrase.size(); i++) {\n    if ()\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/blobs.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1170\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int n;\n  double x;\n  cin >> n;\n\n  while (n--) {\n    cin >> x;\n    int counter = 0;\n\n    while (x > 1) {\n      x /= 2;\n      counter++;\n    }\n\n    cout << counter << \" dias\" << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/bloggo_shotcuts.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1239\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nstring edit_italic(char charac, bool is_start) {\n\tif (is_start) return \"<i>\";\n\telse return \"</i>\";\n}\n\nstring edit_bold(char charac, bool is_start) {\n\tif (is_start) return \"<b>\";\n\telse return \"</b>\";\n}\n\nint main() {\n\n\tint n;\n\tstring line;\n\t\n\twhile (getline(cin, line)) {\n\t\tstring new_line = \"\";\n\t\tbool italic_start = true;\n\t\tbool bold_start = true;\n\t\tfor (int i = 0; i < line.size(); i++) {\n\t\t\tif (line[i] == '*') {\n\t\t\t\tnew_line += edit_bold(line[i], italic_start);\n\t\t\t\titalic_start = !italic_start;\n\t\t\t} else if (line[i] == '_') {\n\t\t\t\tnew_line += edit_italic(line[i], bold_start);\n\t\t\t\tbold_start = !bold_start;\n\t\t\t} else {\n\t\t\t\tnew_line += line[i];\n\t\t\t}\n\t\t}\n\t\t\n\t\tcout << new_line << endl;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/bob_conduit.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1589\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\tlong long int n1, n2;\n\n\tcin >> n;\n\n\twhile (n--) {\n\n\t\tcin >> n1 >> n2;\n\n\t\tcout << n1 + n2 << endl;\n\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/bodybuilder.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2144\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\tint n1, n2, n3, counter = 0;\n\tfloat total, e = 0;\n\n\twhile (cin >> n1 >> n2 >> n3 && n1 + n2 + n3 != 0) {\n\t\ttotal = (n1 + n2) * (1 + n3 / 30.00) / 2;\n\t\tif (total >= 1 && total < 13) cout << \"Nao vai da nao\" << endl;\n\t\telse if (total >= 13 && total < 14) cout << \"E 13\" << endl;\n\t\telse if (total >= 14 && total < 40) cout << \"Bora, hora do show! BIIR!\" << endl;\n\t\telse if (total >= 40 && total <= 60) cout << \"Ta saindo da jaula o monstro!\" << endl;\n\t\telse cout << \"AQUI E BODYBUILDER!!\" << endl;\n\n\t\te += total;\n\t\tcounter++;\n\t}\n\n\tcout << endl;\n\n\tif (e / counter > 40) cout << \"Aqui nois constroi fibra rapaz! Nao e agua com musculo!\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/brazil_world_cup.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1564\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int n;\n\n  while (scanf(\"%d\", &n) != EOF) {\n    if (n == 0) {\n      cout << \"vai ter copa!\" << endl;\n    } else {\n      cout << \"vai ter duas!\" << endl;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/brazilian_economy.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1796\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, x, yes=0, no=0;\n\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> x;\n\t\tif (x) no++;\n\t\telse yes++;\n\t}\n\n\tif (no >= yes) cout << \"N\" << endl;\n\telse cout << \"Y\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/brick_game.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1436 \n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\n\tint t, casi=1;\n\tcin >> t;\n\t\n\twhile (t--) {\n\t\tvector<int> v;\n\t\tint n, temp;\n\t\tcin >> n;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> temp;\n\t\t\tv.push_back(temp);\n\t\t}\n\t\t\n\t\tsort(v.begin(), v.end());\n\t\t\n\t\tcout << \"Case \" << casi << \": \" << v[n/2] << endl;\n\t\tcasi++;\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/bubbles_and_bucket.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1088\n\n#include <iostream>\n#include <stdio.h>\n\nusing namespace std;\n\nint main() {\n    int N, vetor[100001], aux, count;\n    scanf(\"%d\", &N);\n\n    while (N > 0) {\n        count = 0;\n\n        for (int i = 1; i <= N; i++) {\n            scanf(\"%d\", &vetor[i]);\n        }\n\n        for (int i = 1; i <= N; i++) {\n            while(vetor[i] != i) {\n                aux = vetor[i];\n                vetor[i] = vetor[aux];\n                vetor[aux] = aux;\n                count++;\n            }\n        }\n\n        if (count % 2 == 0) printf(\"Carlos\\n\");\n        else printf(\"Marcelo\\n\");\n\n        scanf(\"%d\", &N);\n    }\n\n  return 0;\n}"
  },
  {
    "path": "competitive-programming/uri/bubbles_and_bucket_2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1088\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n\nusing namespace std;\n\nint numberOfSwaps;\n\nbool countNumberOfSwaps(int n1, int n2) {\n\tif (n1 < n2) numberOfSwaps++;\n\treturn n1 < n2;\n}\n\nint main() {\n  int n, x;\n\n  while (cin >> n && n != 0) {\n    numberOfSwaps = 0;\n    vector<int> v;\n    \n    while (n--) {\n    \tcin >> x;\n    \tv.push_back(x);\n    }\n    \n\tsort(v.begin(), v.end(), countNumberOfSwaps);\n\tif (numberOfSwaps % 2 == 0) cout << \"Carlos\" << endl;\n    else cout << \"Marcelo\" << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/building_houses.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1541\n\n#include <iostream>\n#include <math.h>\n\nusing namespace std;\n\nint main() {\n\n\tint l1, l2, p;\n\n\tcin >> l1 >> l2 >> p;\n\n\twhile (l1 != 0) {\n\n\t\tint area = l1 * l2;\n\n\t\tint land_size = sqrt(area * 100 / p);\n\n\t\tcout << land_size << endl;\n\n\t\tcin >> l1 >> l2 >> p;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/building_walls.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2650\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <math.h>\n\nusing namespace std;\n\nvector<string> split(string s) {\n  vector<string> V;\n  int startIndex = 0;\n\n  for (int i = 1; i < s.size(); i++) {\n    if (s[i] == ' ') {\n      V.push_back(s.substr(startIndex, i+1));\n      startIndex = i+1;\n    }\n\n    V.push_back(startIndex, s.size() - startIndex);\n  }\n\n  return V;\n}\n\nint to_digit(string height) {\n  int digit = 0;\n  for (int i = 0; i < height.size(); i++) {\n    digit += (height[i] - '0') * pow(10, height.size() - 1 - i);\n  }\n\n  return digit;\n}\n\nint main() {\n  int N, W, H;\n  string titan, name, line, height;\n  vector<string> V;\n\n  cin >> N >> W;\n  cin.ignore();\n\n  while (N--) {\n    getline(cin, line);\n    V = split(line);\n    height = V.pop_back();\n    H = to_digit(height);\n\n    if (H > W) {\n      for (int i = 0; i < V.size()-1; i++) cout << V[i] << \" \";\n      cout << V[i] << endl;\n    }\n\n    V.clear();\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/buttlerflies.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1901\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint new_specie(vector<int> &v, int n) {\n\tint found = 0;\n\n\tfor (int i = 0; i < v.size(); i++) if (v[i] == n) found = 1;\n\n\tif (found) return 0;\n\telse return 1;\n}\n\nint main() {\n\n\tint n;\n\tvector< vector<int> > m;\n\tvector<int> species;\n\n\tcin >> n;\n\n\tfor (int i = 0; i < n; i++) {\n\t\tvector<int> v;\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tint temp;\n\t\t\tcin >> temp;\n\t\t\tv.push_back(temp);\n\t\t}\n\n\t\tm.push_back(v);\n\t}\n\n\tn = n * 2;\n\tint n1, n2;\n\tcin >> n1 >> n2;\n\tn1 -= 1;\n\tn2 -= 1;\n\tspecies.push_back(m[n1][n2]);\n\n\twhile (n--) {\t\t\n\t\tif (new_specie(species, m[n1][n2])) species.push_back(m[n1][n2]);\n\n\t\tcin >> n1 >> n2;\n\t\tn1 -= 1;\n\t\tn2 -= 1;\n\t}\n\n\tcout << species.size() << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/c_mais_ou_menos.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2486\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint get_vitamine_c(string fruit) {\n  if (fruit == \"suco de laranja\") return 120;\n  else if (fruit == \"morango fresco\") return 85;\n  else if (fruit == \"mamao\") return 85;\n  else if (fruit == \"goiaba vermelha\") return 70;\n  else if (fruit == \"manga\") return 56;\n  else if (fruit == \"laranja\") return\t50;\n  else return 34;\n}\n\nint main() {\n  int N, num, total_vitamine;\n  string fruit;\n\n  cin >> N;\n\n  while (N != 0) {\n    total_vitamine = 0;\n\n    while (N--) {\n      cin >> num;\n      cin.ignore();\n      getline(cin, fruit);\n      total_vitamine += num * get_vitamine_c(fruit);\n    }\n\n    if (total_vitamine < 110) cout << \"Mais \" << 110 - total_vitamine << \" mg\" << endl;\n    else if (total_vitamine > 130) cout << \"Menos \" << total_vitamine - 130 << \" mg\" << endl;\n    else cout << total_vitamine << \" mg\" << endl;\n\n    cin >> N;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/caeser_cipher.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1253\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nstring shift(string str, int n) {\n\tstring new_str = \"\";\n\tstring alphabet = \"ZYXWVUTSRQPONMLKJIHGFEDCBAZYXWVUTSRQPONMLKJIHGFEDCBA\";\n\tint index;\n\n\tfor (int i = 0; i < str.size(); i++) {\n\t\tindex = alphabet.find(str[i]);\n\t\tindex += n;\n\t\tnew_str += alphabet[index];\n\t}\n\n\treturn new_str;\n}\n\nint main() {\n\t\n\tint n, shift_n;\n\tcin >> n;\n\n\tstring str;\n\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> str;\n\t\tcin >> shift_n;\n\t\tif (shift_n) str = shift(str, shift_n);\n\t\tcout << str << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/cannon.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/1288\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nstruct missile {\n  int power, weight;\n};\n\nbool compare(missile m1, missile m2) {\n  if (m1.weight < m2.weight) return true;\n  else if (m1.weight > m2.weight) return false;\n  else return m1.power <= m2.power;\n}\n\nint max(int a, int b) {\n  return a >= b ? a : b;\n}\n\nint main() {\n  int C, N, X, Y, K, R;\n\n  cin >> C;\n\n  while (C--) {\n    cin >> N;\n    vector<missile> missiles;\n\n    for (int i = 0; i < N; i++) {\n      cin >> X >> Y;\n      missile m;\n      m.power = X;\n      m.weight = Y;\n      missiles.push_back(m);\n    }\n\n    cin >> K >> R;\n    int dp[N][K+1];\n    sort(missiles.begin(), missiles.end(), compare);\n\n    for (int i = 0; i <= K; i++) {\n      if (i < missiles[0].weight) dp[0][i] = 0;\n      else dp[0][i] = missiles[0].power;\n    }\n\n    for (int i = 1; i < N; i++) {\n      for (int j = 0; j <= K; j++) {\n        if (j < missiles[i].weight) dp[i][j] = dp[i-1][j];\n        else dp[i][j] = max(dp[i-1][j], dp[i-1][j-missiles[i].weight] + missiles[i].power);\n      }\n    }    \n\n    if (dp[N-1][K] >= R) cout << \"Missao completada com sucesso\" << endl;\n    else cout << \"Falha na missao\" << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/canteen_queue.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1548\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\tint n, x, k;\n\tcin >> n;\n\n\twhile (n--) {\n\t\tvector<int> v, c;\n\t\tcin >> k;\n\t\twhile (k--) {\n\t\t\tcin >> x;\n\t\t\tv.push_back(x);\n\t\t\tc.push_back(x);\n\t\t}\n\n\t\tsort(v.begin(), v.end());\n\n\t\tint counter = 0;\n\n\t\tfor (int i = 0; i < v.size(); i++) if (v[i] == c[i]) counter++;\n\t\tcout << counter << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/cash_roial.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2595\n\n#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nint enemies_counter(vector<string> &V, int cx, int cy, int N, int M) {\n  int counter = 0;\n\n  if (cx-1 >= 0 && cy-1 >= 0 && V[cx-1][cy-1] == 'T') counter++;\n  if (cy-1 >= 0 && V[cx][cy-1] == 'T') counter++;\n  if (cx+1 < N && cy-1 >= 0 && V[cx+1][cy-1] == 'T') counter++;\n  if (cx-1 >= 0 && V[cx-1][cy] == 'T') counter++;\n  if (cx+1 < N && V[cx+1][cy] == 'T') counter++;\n  if (cx-1 >= 0 && cy+1 < M && V[cx-1][cy+1] == 'T') counter++;\n  if (cy+1 < M && V[cx][cy+1] == 'T') counter++;\n  if (cx+1 < N && cy+1 < M && V[cx+1][cy+1] == 'T') counter++;\n\n  return counter;\n}\n\nint main() {\n  int num, N, M, P, X, Y, cx, cy;\n  vector<string> V;\n  string line;\n\n  cin >> num;\n\n  while (num--) {\n    cin >> N >> M >> P;\n    cin.ignore();\n\n    for (int i = 0; i < N; i++) {\n      cin >> line;\n      V.push_back(line);\n    }\n\n    while (P--) {\n      cin >> cx >> cy;\n      if (enemies_counter(V, cx-1, cy-1, N, M) >= 5) cout << \"GRRR\" << endl;\n      else cout << \"GG IZI\" << endl;\n    }\n\n    V.clear();\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/chinese_whispers.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1448\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n  int n, instance=1;\n  string s, s1, s2;\n\n  cin >> n;\n  cin.ignore();\n\n  while (getline(cin, s)) {\n    getline(cin, s1);\n    getline(cin, s2);\n\n    int points_1=0, points_2=0;\n    bool not_found = true;\n    int winner = 0;\n\n    for (int i = 0; i < s.size(); i++) {\n      if (s[i] == s1[i]) points_1++;\n      if (s[i] == s2[i]) points_2++;\n      if (not_found) {\n        if (s[i] == s1[i] && s[i] != s2[i]) {\n          not_found = false;\n          winner = 1;\n        } else if (s[i] != s1[i] && s[i] == s2[i]) {\n          not_found = false;\n          winner = 2;\n        }\n      }\n    }\n\n    cout << \"Instancia \" << instance << endl;\n    instance++;\n\n    if (points_1 == points_2) {\n      if (winner == 0) cout << \"empate\" << endl;\n      else if (winner == 1) cout << \"time 1\" << endl;\n      else if (winner == 2) cout << \"time 2\" << endl;\n    } else if (points_1 > points_2) {\n      cout << \"time 1\" << endl;\n    } else if (points_1 < points_2) {\n      cout << \"time 2\" << endl;\n    }\n\n    cout << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/chirrin_chirrion.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2583\n\n#include <iostream>\n#include <string>\n#include <map>\n\nusing namespace std;\n\nint main() {\n  int N, num;\n  string s1, s2;\n  cin >> N;\n\n  while (N--) {\n    map<string, int> M;\n    cin >> num;\n\n    while (num--) {\n      cin >> s1 >> s2;\n\n      if (M.find(s1) == M.end() && s2 == \"chirrin\") M[s1] = 1;\n      else if (M.find(s1) != M.end() && s2 == \"chirrion\") M[s1] = 0;\n    }\n\n    cout << \"TOTAL\" << endl;\n\n    for (map<string, int>::iterator it = M.begin(); it != M.end(); it++) {\n      if (it->second == 1) cout << it->first << endl;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/chocolate_factory.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1573\n\n#include <iostream>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\n\n  int n1, n2, n3;\n\n  while (cin >> n1 >> n2 >> n3 && n1 + n2 + n3 != 0) {\n    int total = n1 * n2 * n3;\n    int cubic_root = cbrt(total);\n    cout << cubic_root << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/christmas_decoration.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1761\n\n#include <iostream>\n#include <math.h>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\t\n\tdouble angle, distance, height;\n\n\twhile (cin >> angle >> distance >> height) {\n\t\tcout << fixed << setprecision(2) << (tan(angle * 3.141592654 / 180.0) * distance + height) * 5 << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/christmas_olympic.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2018\n\n#include <iostream>\n#include <vector>\n#include <map>\n#include <algorithm>\n\nusing namespace std;\n\nstruct country {\n\tstring name;\n\tint gold;\n\tint silver;\n\tint bronze;\n};\n\nbool compareByMedals(const country &c1, const country &c2) {\n\tif (c1.gold > c2.gold) return true;\n\telse if (c1.gold == c2.gold) {\n\t\tif (c1.silver > c2.silver) return true;\n\t\telse if (c1.silver == c2.silver) {\n\t\t\tif (c1.bronze > c2.bronze) return true;\n\t\t\telse if (c1.bronze == c2.bronze) return c1.name < c2.name;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nint main() {\n\tint index, counter = 0;\n\tstring game, first, second, third;\n\tmap<string, int> m;\n\tvector<country> countries;\n\n\twhile (getline(cin, game)) {\n\t\tgetline(cin, first);\n\t\tgetline(cin, second);\n\t\tgetline(cin, third);\t\t\n\n\t\tif (m.find(first) != m.end()) {\n\t\t\tindex = m[first];\n\t\t\tcountries[index].gold++;\n\t\t} else {\n\t\t\tm[first] = counter;\n\t\t\tcountry c;\n\t\t\tc.name = first;\n\t\t\tc.gold = 1;\n\t\t\tc.silver = 0;\n\t\t\tc.bronze = 0;\n\t\t\tcountries.push_back(c);\n\t\t\tcounter++;\n\t\t}\t\t\n\n\t\tif (m.find(second) != m.end()) {\n\t\t\tindex = m[second];\n\t\t\tcountries[index].silver++;\n\t\t} else {\n\t\t\tm[second] = counter;\n\t\t\tcountry c;\n\t\t\tc.name = second;\n\t\t\tc.gold = 0;\n\t\t\tc.silver = 1;\n\t\t\tc.bronze = 0;\n\t\t\tcountries.push_back(c);\n\t\t\tcounter++;\n\t\t}\t\t\n\n\t\tif (m.find(third) != m.end()) {\n\t\t\tindex = m[third];\n\t\t\tcountries[index].bronze++;\n\t\t} else {\n\t\t\tm[third] = counter;\n\t\t\tcountry c;\n\t\t\tc.name = third;\n\t\t\tc.gold = 0;\n\t\t\tc.silver = 0;\n\t\t\tc.bronze = 1;\n\t\t\tcountries.push_back(c);\n\t\t\tcounter++;\n\t\t}\n\t}\n\n\tsort(countries.begin(), countries.end(), compareByMedals);\n\tcout << \"Quadro de Medalhas\" << endl;\n\n\tfor (int i = 0; i < countries.size(); i++) {\n\t\tcout << countries[i].name << \" \" << countries[i].gold << \" \" << countries[i].silver << \" \" << countries[i].bronze << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/christmas_trapeziums.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1765\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, num;\n\tfloat n1, n2, h = 5.0;\n\n\twhile (cin >> n && n != 0) {\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tcout << \"Size #\" << i << \":\" << endl;\n\t\t\tcin >> num >> n1 >> n2;\n\t\t\tcout << fixed << setprecision(2) << \"Ice Cream Used: \" << num * (n1 + n2) * h / 2.0 << \" cm2\" << endl;\n\t\t}\n\n\t\tcout << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/christmas_tree.cpp",
    "content": "\t// https://www.urionlinejudge.com.br/judge/en/problems/view/1768\n\n\t#include <iostream>\n\t#include <string>\n\n\tusing namespace std;\n\n\tint main() {\n\t\t\n\t\tint n, mid, start, end;\n\n\t\twhile (cin >> n) {\n\t\t\tmid = n / 2;\n\t\t\tstart = mid;\n\t\t\tend = mid;\n\n\t\t\tfor (int i = 0; i < mid + 1; i++) {\n\t\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\t\tif (j >= start && j <= end) cout << \"*\";\n\t\t\t\t\telse if (j > end) break;\n\t\t\t\t\telse cout << \" \";\n\t\t\t\t}\n\n\t\t\t\tcout << endl;\n\t\t\t\tstart--;\n\t\t\t\tend++;\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\tif (i == mid) cout << \"*\";\n\t\t\t\telse if (i > mid) break;\n\t\t\t\telse cout << \" \";\n\t\t\t}\n\n\t\t\tcout << endl;\n\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\tif (i == mid || i == mid-1 || i == mid+1) cout << \"*\";\n\t\t\t\telse if (i > mid+1) break;\n\t\t\t\telse cout << \" \";\n\t\t\t}\n\n\t\t\tcout << endl << endl;\n\t\t}\n\n\t\treturn 0;\n\t}"
  },
  {
    "path": "competitive-programming/uri/close_the_doors.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1371\n\n#include <iostream>\n#include <math.h>\n\nusing namespace std;\nint main() {\n\tlong long n = 0, k;\n\t\n\twhile(cin >> k) {\n\t\tlong long i = 0;\n\t\tif (k == 0) break;\n\t\tfor (n = 0; i < (int)sqrt(k); i++) {\n\t\t\tn += 2 * i + 1;\n\t\t\tif (i + 1 >= (int)sqrt(k)) cout << n;\n\t\t\telse cout << n << \" \";\n\t\t}\n\t\t\n\t\tcout << endl;\n\t}\n}\n"
  },
  {
    "path": "competitive-programming/uri/coast_guard.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1247\n\n#include <iostream>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\n\n  float d, f, g, n, distancia_perpendicular = 12;\n\n  while(scanf(\"%f %f %f\", &d, &f, &g) != EOF) {\n    n = sqrt((144 + d*d));\n\n    if ((12 / f) < (n / g))\n      cout << 'N' << endl;\n    else\n      cout << 'S' << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/coffee_machine.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int N1, N2, N3;\n\n  cin >> N1 >> N2 >> N3;\n\n  int one = N2 * 2 + N3 * 4,\n      two = N1 * 2 + N3 * 2,\n      three = N1 * 4 + N2 * 2;\n\n  if (one <= two && one <= three) cout << one << endl;\n  else if (two <= three) cout << two << endl;\n  else cout << three << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/colision.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1618\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, ax, ay, bx, by, cx, cy, dx, dy, x, y;\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> ax >> ay >> bx >> by >> cx >> cy >> dx >> dy >> x >> y;\n\t\tif (x >= ax && x <= bx && y >= ay && y <= dy) cout << 1 << endl;\n\t\telse cout << 0 << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/collectable_cards.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1028\n\n#include <iostream>\nusing namespace std;\n\nint mcd(int n1, int n2) {\n\tif (n2 == 0) return n1;\n\treturn mcd(n2, n1 % n2);\n}\n\nint main() {\n\t\n\tint n, n1, n2;\n\tcin >> n;\n\t\n\twhile (n--) {\n\t\tcin >> n1 >> n2;\n\t\tif (n1 > n2) cout << mcd(n1, n2) << endl;\n\t\telse cout << mcd(n2, n1) << endl;\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/colourful_flowers.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1419\n\n#include <iostream>\n#include <iomanip>\n#include <math.h>\n\nusing namespace std;\n\ndouble get_greater_radius(int a, int b, int c) {\n\tdouble bottom = sqrt((a + b + c) * (b + c - a) * (c + a - b) * (a + b - c));\n\treturn (a * b * c) / (bottom);\n}\n\ndouble get_triangle_area(int l1, int l2, int l3) {\n\tdouble perim = (l1 + l2 + l3) / 2.0;\n\tdouble part1 = perim - l1;\n\tdouble part2 = perim - l2;\n\tdouble part3 = perim - l3;\n\tdouble area = sqrt(perim * part1 * part2 * part3);\n\treturn area;\n}\n\ndouble get_smaller_circunference_radius(double triangle_area, double triangle_perimeter) {\n\treturn 2 * triangle_area / triangle_perimeter;\n}\n\nint main() {\n\t\n\tdouble l1, l2, l3;\n\tconst double PI = 3.1415926535897;\n\t\n\twhile (scanf(\"%lf %lf %lf\", &l1, &l2, & l3) != EOF) {\n\t\tdouble radius = get_greater_radius(l1, l2, l3);\n\t\tdouble circunference_area = PI * radius * radius;\n\t\tdouble triangle_area = get_triangle_area(l1, l2, l3);\n\t\tdouble smaller_circunference_radius = get_smaller_circunference_radius(triangle_area, l1+l2+l3);\n\t\tdouble smaller_circunference_area = PI * smaller_circunference_radius * smaller_circunference_radius;\n\t\tcout << fixed << setprecision(4) << circunference_area - triangle_area << \" \" << triangle_area - smaller_circunference_area << \" \" << smaller_circunference_area << endl;\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/column_in_array.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1182\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n\tint column;\n\tdouble n;\n\tcin >> column;\n\n\tstring t;\n\tcin >> t;\n\n\tvector< vector<double> > v1;\t\n\n\tfor (int i = 0; i < 12; i++) {\n\t\tvector<double> v2;\n\n\t\tfor (int j = 0; j < 12; j++) {\n\t\t\tcin >> n;\n\t\t\tv2.push_back(n);\n\t\t}\n\n\t\tv1.push_back(v2);\n\t}\n\n\tif (t == \"S\") {\n\t\tdouble sum = 0;\n\t\tfor (int i = 0; i < 12; i++) sum += v1[i][column];\n\t\tcout << fixed << setprecision(1) << sum << endl;\n\t} else if (t == \"M\") {\n\t\tdouble average = 0;\n\t\tfor (int i = 0; i < 12; i++) average += v1[i][column];\n\t\tcout << fixed << setprecision(1) << average / 12 << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/combiner.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1238\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n  int n;\n  cin >> n;\n\n  string s1, s2;\n\n  while (n--) {\n    cin >> s1 >> s2;\n    string result = \"\";\n\n    if (s1.size() >= s2.size()) {\n      for (int i = 0; i < s2.size(); i++) {\n        result += s1[i];\n        result += s2[i];\n      }\n      result += s1.substr(s2.size(), s1.size() - 1);\n    } else {\n      for (int i = 0; i < s1.size(); i++) {\n        result += s1[i];\n        result += s2[i];\n      }\n      result += s2.substr(s1.size(), s2.size() - 1);\n    }\n\n    cout << result << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/compare_substring.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1237\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint searchSubstring(string s) {\n\tfor (int i = s.size(); i > 0; i--) {\n\t\t\n\t}\n}\n\nint main() {\n\t\n\tstring s1, s2;\n\t\n\twhile(getline(cin, s1)) {\n\t\tgetline(cin, s2);\n\n\t\tif (s1.size() < s2.size()) {\n\t\t\tsearchSubstring(s1);\n\t\t} else {\n\t\t\tsearchSubstring(s2);\n\t\t}\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/complete_sequence.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1551\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nbool find_letter(char c) {\n  string alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n  if (alphabet.find(c) != -1) return true;\n  return false;\n}\n\nbool not_in_phrase(char c, string phrase) {\n  if (phrase.find(c) == -1) return true;\n  return false;\n}\n\nint main() {\n  int n;\n  cin >> n;\n  cin.ignore();\n  string phrase;\n\n  while (n--) {\n    getline(cin, phrase);\n    string letters_on_phrase = \"\";\n\n    for (int i = 0; i < phrase.size(); i++) {\n      if (find_letter(phrase[i]) && not_in_phrase(phrase[i], letters_on_phrase)) letters_on_phrase += phrase[i];\n    }\n\n    if (letters_on_phrase.size() == 26) cout << \"frase completa\" << endl;\n    else if (letters_on_phrase.size() >= 13) cout << \"frase quase completa\" << endl;\n    else cout << \"frase mal elaborada\" << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/consumption.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1014\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  int n1, n2;\n\n  cin >> n1 >> n2;\n\n  cout << fixed << setprecision(3) << n1 / n2 << \" km/l\" << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/contando_ciclos.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2497\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int N, counter = 1;\n\n  while (cin >> N && N != -1) {\n    cout << \"Experiment \" << counter << \": \" << N / 2 << \" full cycle(s)\" << endl;\n    counter++;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/contest.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1514\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n1, n2, x;\n\tcin >> n1 >> n2;\t\n\n\twhile (n1 + n2 != 0) {\n\t\tvector< vector<int> > matrix;\n\t\tvector<int> v;\n\t\tint num_problems = 0, solved;\n\t\tbool nobody_solved_all_problems = true;\n\t\tbool solved_by_one_person = true;\n\t\tbool no_problem_solved_by_everyone = true;\n\t\tbool solved_one_problem = true;\n\n\t\tfor (int i = 0; i < n1; i++) {\n\t\t\tfor (int j = 0; j < n2; j++) {\n\t\t\t\tcin >> x;\n\t\t\t\tv.push_back(x);\n\t\t\t}\n\n\t\t\tmatrix.push_back(v);\n\t\t\tv.clear();\n\t\t}\n\n\t\tfor (int i = 0; i < n1; i++) {\n\t\t\tsolved = 0;\n\t\t\tfor (int j = 0; j < n2; j++) if (matrix[i][j] == 1) solved++;\n\t\t\tif (solved == n2) nobody_solved_all_problems = false;\n\t\t\tif (solved == 0) solved_one_problem = false;\n\t\t}\n\n\t\tfor (int i = 0; i < n2; i++) {\n\t\t\tsolved = 0;\n\t\t\tfor (int j = 0; j < n1; j++) if (matrix[j][i] == 1) solved++;\n\t\t\tif (solved == n1) no_problem_solved_by_everyone = false;\n\t\t\tif (solved == 0) solved_by_one_person = false;\n\t\t}\n\n\t\tif (nobody_solved_all_problems) num_problems++;\n\t\tif (solved_by_one_person) num_problems++;\n\t\tif (no_problem_solved_by_everyone) num_problems++;\n\t\tif (solved_one_problem) num_problems++;\n\n\t\tcout << num_problems << endl;\n\n\t\tcin >> n1 >> n2;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/contract_revision.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1120\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n  string error_num, contract_num, result = \"\";\n\n  cin >> error_num >> contract_num;\n\n  while (error_num != \"0\" || contract_num != \"0\") {\n\n    for (int i = 0; i < contract_num.size(); i++) {\n      if (error_num[0] != contract_num[i]) {\n        if (result.size() > 0) result += contract_num[i];\n        else if (contract_num[i] != '0') result += contract_num[i];\n      }\n    }\n\n    if (result.size() > 0) cout << result << endl;\n    else cout << 0 << endl;\n\n    result.clear();\n    cin >> error_num >> contract_num;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/converting_to_hexadecimal.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1957\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\n// 1 2 3 4 5 6 7 8 9 A B C D E F 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20\n\nstring reverseString(string hex) {\n  string newHex = \"\";\n  for (int i = hex.size()-1; i >= 0; i--) newHex += hex[i];\n  return newHex;\n}\n\nint main() {\n  string hex = \"0123456789ABCDEF\", result = \"\";\n  int n, stringIndex;\n  cin >> n;\n\n  while (n > 0) {\n    stringIndex = n % 16;\n    n /= 16;\n    result += hex[stringIndex];\n  }\n\n  cout << reverseString(result) << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/coordinates_of_a_point.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1041\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tdouble x, y;\n\n\tcin >> x >> y;\n\n\tif (x > 0 && y > 0) {\n\t\tcout << \"Q1\" << endl;\n\t} else if (x < 0 && y > 0) {\n\t\tcout << \"Q2\" << endl;\n\t} else if (x < 0 && y < 0) {\n\t\tcout << \"Q3\" << endl;\n\t} else if (x > 0 && y < 0) {\n\t\tcout << \"Q4\" << endl;\n\t} else if (x == 0 && y == 0) {\n\t\tcout << \"Origem\" << endl;\n\t} else if (x == 0 && y != 0) {\n\t\tcout << \"Eixo Y\" << endl;\n\t} else if (x != 0 && y == 0) {\n\t\tcout << \"Eixo X\" << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/correct_colourful_flower.cpp",
    "content": "#include <iostream>\n#include <iomanip>\n#include <cmath>\n\nusing namespace std;\n\nint main(){\n    double a, b, c;\n    double violets, roses, girrassois;\n\n    while(cin >> a >> b >> c){\n        double p = (a+b+c) / 2.0;\n        double triangulo, circ_p, circ_g;\n\n        triangulo = sqrt(p*(p-a)*(p-b)*(p-c));\n        circ_p = pow(triangulo/p,2)*(M_PI);\n        circ_g = pow((a*b*c)/(4*triangulo),2)*(M_PI);\n\n        violets = triangulo - circ_p;\n        girrassois = circ_g - triangulo;\n        roses = circ_p;\n\n        cout << fixed << setprecision(4);\n\n        cout << girrassois << \" \" << violets << \" \" << roses << endl;\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/corrida.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2516\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n  double S, VA, VB;\n\n  while (cin >> S >> VA >> VB) {\n    if (VB >= VA) cout << \"impossivel\" << endl;\n    else {\n      cout << fixed << setprecision(2) << S / (VA - VB) << endl;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/counting_crow.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1848\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n  int scream_counter = 0, blink_counter = 0;\n  string s;\n\n  while (scream_counter < 3) {\n    cin >> s;\n    if (s == \"caw\") {\n      scream_counter++;\n      cin >> s;\n      cout << blink_counter << endl;\n      blink_counter = 0;\n    } else {\n      for (int i = 0; i < 3; i++) {\n        if (s[i] == '*') {\n          if (i == 0) blink_counter+= 4;\n          else if (i == 1) blink_counter+= 2;\n          else if (i == 2) blink_counter+= 1;\n        }\n      }\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/counting_sheeps.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1609\n\n#include <iostream>\n#include <set>\n\nusing namespace std;\n\nint main() {\n\n  int n, x, temp;\n  cin >> n;\n\n  while (n--) {\n    cin >> x;\n    set<int> s;\n    for (int i = 0; i < x; i++) {\n      cin >> temp;\n      s.insert(temp);\n    }\n\n    cout << s.size() << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/cutoff_rounder.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1305\n\n#include <iostream>\n#include <string>\n#include <math.h>\n\nusing namespace std;\n\nstring get_integer_part(string n) {\n\tint length;\n\tfor (int i = 0; i < n.size(); i++) if (n[i] == '.') length = i;\t\n\treturn n.substr(0, length);\n}\n\nstring get_decimal_part(string n) {\n\tint initial;\n\tfor (int i = 0; i < n.size(); i++) if (n[i] == '.') initial = i+1;\n\treturn n.substr(initial, n.size() - initial);\t\n}\n\nint to_int(string num) {\n\tint number=0, num_digit;\n\tfor (int i = 0; i < num.size(); i++) {\n\t\tnum_digit = num[i] - '0';\n\t\tnumber += num_digit * pow(10, num.size()-i-1);\n\t}\n\n\treturn number;\n}\n\ndouble to_double(string num) {\n\tint num_digit;\n\tdouble number=0;\n\tfor (int i = 0; i < num.size(); i++) {\n\t\tnum_digit = num[i] - '0';\n\t\tnumber += num_digit / pow(10, i+1);\n\t}\n\n\tcout << \"*\" << number << endl;\n\treturn number;\n}\n\nbool is_num_decimal_greater_than_or_equal_to_cutoff_decimal(string num, string cutoff) {\n\tint limit, num_digit, cutoff_digit;\n\tif (num.size() > cutoff.size()) limit = cutoff.size();\n\telse limit = num.size();\n\n\tif (num == cutoff) {\n\t\treturn true;\n\t} else {\n\t\tfor (int i = 0; i < limit; i++) {\n\t\t\tnum_digit = num[i] - '0';\n\t\t\tcutoff_digit = cutoff[i] - '0';\n\t\t\tif (num_digit > cutoff_digit) return true;\n\t\t}\n\n\t\treturn false;\n\t}\t\n}\n\nbool has_period(string n) {\n\tfor (int i = 0; i < n.size(); i++) if (n[i] == '.') return true;\n\treturn false;\n}\n\nint main() {\n\t\n\tstring num, cutoff;\n\n\twhile (cin >> num >> cutoff) {\n\t\tif (has_period(num)) {\n\t\t\tstring integer_part = get_integer_part(num);\n\t\t\tstring num_decimal_part = get_decimal_part(num);\n\t\t\tstring cutoff_decimal_part = get_decimal_part(cutoff);\n\t\t\tif (is_num_decimal_greater_than_or_equal_to_cutoff_decimal(num_decimal_part, cutoff_decimal_part)) cout << to_int(integer_part)+1 << endl;\n\t\t\telse cout << to_int(integer_part) << endl;\n\t\t} else {\n\t\t\tcout << num << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/cutoff_rounder_2.cpp",
    "content": "// http://www.urionlinejudge.com.br/judge/en/problems/view/1305\n\n#include <iostream>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\n\n  long double num, cutoff, fractional;\n  int intnum;\n\n  while (cin >> num >> cutoff) {\n    intnum = num;\n    fractional = num - intnum;\n\n    if (fractional >= cutoff) cout << ((int) num + 1) << endl;\n    else cout << ((int) num) << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/dancing_sentence.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1234\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nchar to_uppercase(char charac) {\n\tstring alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\tint index = alphabet.find(charac) - 26;\n\treturn alphabet[index];\n}\n\nchar to_lowercase(char charac) {\n\tstring alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\tint index = alphabet.find(charac) + 26;\n\treturn alphabet[index];\n}\n\nbool is_uppercase(char charac) {\n\tstring alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\tif (alphabet.find(charac) <= 25) return true;\n\telse return false;\n}\n\nint main() {\n\t\n\tstring s;\n\tstring alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n\twhile (getline(cin, s)) {\n\t\tstring result = \"\";\n\t\tbool uppercase = true;\n\t\tfor (int i = 0; i < s.size(); i++) {\n\t\t\tif (s[i] == ' ') {\n\t\t\t\tresult += s[i];\n\t\t\t} else {\n\t\t\t\tif (uppercase) {\n\t\t\t\t\tif (is_uppercase(s[i])) result += s[i];\n\t\t\t\t\telse result += to_uppercase(s[i]);\n\t\t\t\t\tuppercase = !uppercase;\n\t\t\t\t} else {\n\t\t\t\t\tif (is_uppercase(s[i])) result += to_lowercase(s[i]);\n\t\t\t\t\telse result += s[i];\n\t\t\t\t\tuppercase = !uppercase;\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\n\t\tcout << result << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/dangerous_dive.cpp",
    "content": "#include <iostream>\n#include <map>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n1, n2, x;\n\t\n\twhile (cin >> n1 >> n2) {\n\t\tmap<int, int> m;\n\t\tvector<int> v;\n\t\t\n\t\tfor (int i = 1; i <= n2; i++) {\n\t\t\tcin >> x;\n\t\t\tm[x] = x;\n\t\t}\n\t\t\n\t\tfor (int i = 1; i <= n1; i++) {\n\t\t\tif (m.find(i) == m.end()) v.push_back(i);\n\t\t}\n\t\n\t\tif (v.empty()) {\n\t\t\tcout << \"*\";\n\t\t} else {\n\t\t\tfor (int i = 0; i < v.size(); i++) {\n\t\t\t\tcout << v[i] << \" \";\n\t\t\t}\n\t\t}\n\n\t\tcout << endl;\n\t\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/dating_online.cpp",
    "content": "#include <iostream>\n#include <cmath>\n#include <cstdio>\n\n#include <vector>\n#include <algorithm>\n\n#define FOR(i, a) for(int i = 0; i < a; i++)\n#define POW(a) ((a) * (a))\n\nusing namespace std;\n\nint N;\nint v[100001];\n\nint main() {\n\n\twhile(scanf(\"%d\", &N) != EOF) {\n\t\tFOR(i, N) scanf(\"%d\", &v[i]);\n\t\tsort(v, v+N);\n\n\t\tdouble sin_ang = sin(2 * M_PI / N);\n\t\tdouble area = 0.0;\n\t\tdouble lado1 = v[N-1], lado_temp = v[N-2];\n\n\t\tarea += lado1 * lado_temp * sin_ang / 2;\n\n\t\tfor (int i = N - 3; i >= 0; i--) {\n\t\t\tarea += v[i] * v[i+2] * sin_ang / 2;\n\t\t}\n\n\t\tarea += v[0] * v[1] * sin_ang / 2;\n\t\tprintf(\"%.3lf\\n\", area);\n\t}\n\n\treturn 0;\n}\n\n"
  },
  {
    "path": "competitive-programming/uri/deciphering_the_encrypted_card.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2502\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nstring to_lowercase(string a) {\n  string alphabet = \"ABCDEFGHIJKLMNOPQRSTUVXWYZabcdefghijklmnopqrstuvxwyz\";\n  string result = \"\";\n\n  for (int i = 0; i < a.size(); i++) {\n    if (alphabet.find(a[i]) <= 25) result += alphabet[alphabet.find(a[i])+26];\n    else result += a[i];\n  }\n\n  return result;\n}\n\nstring decipher(string phrase, string f, string s) {\n  string deciphered = \"\";\n\n  for (int i = 0; i < phrase.size(); i++) {\n    if (f.find(phrase[i]) != string::npos) deciphered += s[f.find(phrase[i])];\n    else deciphered += phrase[i];\n  }\n\n  return deciphered;\n}\n\nint main() {\n  int N, C;\n  string f, s, phrase;\n\n  while (cin >> N >> C) {\n    cin >> s >> f;\n    s = to_lowercase(s);\n    f = to_lowercase(f);\n\n    while (C--) {\n      cin.ignore();\n      getline(cin, phrase);\n      cout << decipher(phrase, f, s) << endl;\n    }\n    cout << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/delaunay_triangulation.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1620\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\tlong double l, i, x;\n\n\twhile (cin >> l && l != 0) {\n\t\ti = l + l - 3;\n\t\tx = (i - l) / l;\n\t\tcout << fixed << setprecision(6) << x << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/desafio_de_bino.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2060\n\n#include <iostream>\n#include <map>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, x;\n\tmap<int, int> m;\n\tcin >> n;\n\n\tfor(int i = 2; i < 6; i++) m[i] = 0;\n\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> x;\n\t\tif (x % 2 == 0) m[2]++;\n\t\tif (x % 3 == 0) m[3]++;\n\t\tif (x % 4 == 0) m[4]++;\n\t\tif (x % 5 == 0) m[5]++;\n\t}\n\n\tmap<int, int>::iterator it;\n\n\tfor (it = m.begin(); it != m.end(); it++) {\n\t\tcout << it->second << \" Multiplo(s) de \" << it->first << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/detective_watson_1.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1533\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, x;\n\n\twhile (cin >> n && n != 0) {\n\t\tint index, first, second, index_first = 1;\n\t\tcin >> x;\n\t\tfirst = x;\n\n\t\tfor (int i = 2; i <= n; i++) {\n\t\t\tcin >> x;\n\t\t\tif (x > first) {\n\t\t\t\tsecond = first;\n\t\t\t\tfirst = x;\n\t\t\t\tindex = index_first;\n\t\t\t\tindex_first = i;\n\t\t\t} else if (x > second) {\n\t\t\t\tsecond = x;\n\t\t\t\tindex = i;\n\t\t\t}\n\t\t}\n\n\t\tcout << index << endl;\n\t}\n\t\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/detective_watson_2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1533\n\n#include <iostream>\n#include <map>\n#include <algorithm>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, x;\n\n\twhile (cin >> n && n != 0) {\t\t\n\t\tmap<int, int> m;\n\t\tvector<int> v;\n\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tcin >> x;\n\t\t\tm[x] = i;\n\t\t\tv.push_back(x);\n\t\t}\n\n\t\tsort(v.begin(), v.end(), greater<int>());\n\t\tint key = v[1];\n\n\t\tcout << m[key] << endl;\n\t}\n\t\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/diamonds_and_sand.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1069\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\tstring s;\n\tint n, d, open;\n\tcin >> n;\n\n\twhile (n--) {\n\t\td=0, open=0;\n\t\tcin >> s;\n\n\t\tfor(int i = 0; i < s.size(); i++) {\n\t\t\tif (s[i] == '<') {\n\t\t\t\topen++;\n\t\t\t} else if (s[i] == '>') {\n\t\t\t\tif (open > 0) {\n\t\t\t\t\topen--;\n\t\t\t\t\td++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcout << d << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/diet_plan.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1248\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\tstring diet, breakfest, lunch;\n\n\tcin >> n;\n\tcin.ignore();\n\n\twhile (n--) {\n\t\tvector< pair<char, bool> > valid_chars;\n\t\tbool is_cheating = false;\n\t\tgetline(cin, diet);\n\t\tgetline(cin, breakfest);\n\t\tgetline(cin, lunch);\n\n\t\tfor (int i = 0; i < diet.size(); i++) valid_chars.push_back(make_pair(diet[i], true));\n\n\t\tint find_char;\n\n\t\tfor (int i = 0; i < breakfest.size(); i++) {\n\t\t\tfind_char = diet.find(breakfest[i]);\n\t\t\tif (find_char == -1) {\n\t\t\t\tis_cheating = true;\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\tfor (int j = 0; j < valid_chars.size(); j++) if (valid_chars[j].first == breakfest[i]) valid_chars[j].second = false;\n\t\t\t}\n\t\t}\n\n\t\tif (!is_cheating) {\n\t\t\tfor (int i = 0; i < lunch.size(); i++) {\n\t\t\t\tfind_char = diet.find(lunch[i]);\n\t\t\t\tif (find_char == -1) {\n\t\t\t\t\tis_cheating = true;\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tfor (int j = 0; j < valid_chars.size(); j++) if (valid_chars[j].first == lunch[i]) valid_chars[j].second = false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (is_cheating) cout << \"CHEATER\" << endl;\n\t\t\telse {\n\t\t\t\tstring result = \"\";\n\t\t\t\tfor (int index = 0; index < valid_chars.size(); index++) if (valid_chars[index].second) result += valid_chars[index].first;\n\t\t\t\tsort(result.begin(), result.end());\n\t\t\t\tcout << result << endl;\n\t\t\t}\n\t\t} else {\n\t\t\tcout << \"CHEATER\" << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/difference.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1007\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int n1, n2, n3, n4;\n\n  cin >> n1 >> n2 >> n3 >> n4;\n\n  cout << \"DIFERENCA = \" << n1 * n2 - n3 * n4 << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/different_digits.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1285\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint different_digits(int n) {\n  vector<int> v;\n\n  while (n > 0) {\n    v.push_back(n % 10);\n    n /= 10;\n  }\n\n  int different = 1;\n\n  for (int i = 0; i < v.size(); i++) {\n    for (int j = i + 1; j < v.size(); j++) {\n      if (v[i] == v[j]) {\n        different = 0;\n        break;\n      }\n    }\n  }\n\n  return different;\n}\n\nint main() {\n  int n1, n2;\n\n  while (scanf(\"%d %d\", &n1, &n2) != EOF) {\n    int counter=0;\n    for (int i = n1; i <= n2; i++) if (different_digits(i)) counter++;\n    cout << counter << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/difn.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2518\n\n#include <iostream>\n#include <iomanip>\n#include <math.h>\n\nusing namespace std;\n\nint main() {\n  double N, H, C, L, result;\n\n  while (cin >> N ) {\n    cin >> H >> C >> L;\n    result = N * L * (sqrt(H * H + C * C)) / 10000;\n    cout << fixed << setprecision(4) << result << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/dijkstra.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2653\n\n#include <iostream>\n#include <set>\n#include <string>\n\nusing namespace std;\n\nint main() {\n  string s;\n  set<string> ss;\n\n  while (cin >> s) {\n    ss.insert(s);\n  }\n\n  cout << ss.size() << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/discovering_password.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2252\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <sstream>\n\nusing namespace std;\n\nstruct oil {\n\tfloat key;\n\tint value;\n};\n\nstring intToString(int passwordPart) {\n\tostringstream ss;\n\tss << passwordPart;\n\treturn ss.str();\n}\n\nbool compareOiliness(const oil &oil1, const oil &oil2) {\n\tif (oil1.key == oil2.key) return oil1.value < oil2.value;\n\treturn oil1.key > oil2.key;\n}\n\nint main() {\n\tint n, casy = 1;\n\tfloat f;\n\n\twhile (cin >> n) {\n\t\tvector<oil> oils;\n\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tcin >> f;\n\t\t\toil o;\n\t\t\to.key = f;\n\t\t\to.value = i;\n\t\t\toils.push_back(o);\n\t\t}\n\n\t\tsort(oils.begin(), oils.end(), compareOiliness);\n\n\t\tint passwordPart;\n\t\tstring password = \"\";\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tpasswordPart = oils[i].value;\n\t\t\tpassword += intToString(passwordPart);\n\t\t}\n\n\t\tcout << \"Caso \" << casy << \": \" << password << endl;\n\t\tcasy++;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/distance.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1016\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint distance;\n\n\tcin >> distance;\n\n\tcout << distance * 2 << \" minutos\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/distance_between_two_points.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1015\n\n#include <iostream>\n#include <math.h>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\t\n\tfloat x1, y1, x2, y2;\n\n\tcin >> x1 >> y1 >> x2 >> y2;\n\n\tcout << fixed << setprecision(4) << sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)) << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/dividers.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\tint a, b, c, d, result = -1;\n\tcin >> a >> b >> c >> d;\n\tvector<int> divisors;\n\t\n\tfor (int i = 1; i * i < c; i++) {\n\t\tif (c % i == 0) {\n\t\t\tdivisors.push_back(i);\n\t\t\tdivisors.push_back(c / i);\n\t\t}\n\t}\n\t\n\tsort(divisors.begin(), divisors.end());\n\n\tfor (int i = 0; i < divisors.size(); i++) {\n\t\tif (divisors[i] % a == 0 && divisors[i] % b != 0 && d % divisors[i] != 0) {\n\t\t\tresult = divisors[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tcout << result << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/dividing_x_by_y.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1116\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  int n;\n  double x, y;\n\n  cin >> n >> x >> y;\n\n  while (n--) {\n\n    if (y != 0) {\n      cout << fixed << setprecision(1) << x / y << endl;\n    } else {\n      cout << \"divisao impossivel\" << endl;\n    }\n\n    cin >> x >> y;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/diving.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2311\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\tint n;\n\tcin >> n;\n\tstring name;\n\tfloat level, rate;\n\n\twhile (n--) {\n\t\tcin >> name;\n\t\tvector<float> rates;\n\n\t\tcin >> level;\n\n\t\tfor (int i = 1; i <= 7; i++) {\n\t\t\tcin >> rate;\n\t\t\trates.push_back(rate);\n\t\t}\n\n\t\tsort(rates.begin(), rates.end());\n\t\tfloat total = 0;\n\t\tfor (int i = 1; i < 6; i++) total += rates[i];\n\t\tcout << setprecision(2) << fixed << name << \" \" << total * level << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/division_of_nlogonia.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main() {\n\t\n\tint k, m, n, x, y;\n\t\n\tcin >> k;\n\t\n\twhile(k != 0) {\n\t\n\t\tcin >> m;\n\t\tcin >> n;\n\t\t\n\t\twhile(k--) {\n\t\t\tcin >> x;\n\t\t\tcin >> y;\n\t\t\t\n\t\t\tif ((x < m) && (y < n))\n\t\t\t\tcout << \"SO\" << endl;\n\t\t\telse if ((x > m) && (y < n))\n\t\t\t\tcout << \"SE\" << endl;\n\t\t\telse if ((x < m) && (y > n))\n\t\t\t\tcout << \"NO\" << endl;\n\t\t\telse if ((x > m) && (y > n))\n\t\t\t\tcout << \"NE\" << endl;\n\t\t\telse\n\t\t\t\tcout << \"divisa\" << endl;\n\t\t\t\n\t\t}\n\t\n\t\tcin >> k;\n\t}\n\t\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/divisors_1.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1157\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\n\tcin >> n;\n\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (n % i == 0) cout << i << endl;\n\t}\n\n}"
  },
  {
    "path": "competitive-programming/uri/dracarys.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1849\n\n#include <iostream>\n#include <math.h>\n\nusing namespace std;\n\nunsigned long long int get_result1(int d1, int d2, int v1, int v2) {\n\tunsigned long long int x, y;\n\n\tif (d1 <= v1) x = d1;\n\telse x = v1;\n\n\ty = d2 + v2;\n\n\tif (x <= y) return x;\n\telse return y;\n}\n\nunsigned long long int get_result2(int d1, int d2, int v1, int v2) {\n\tunsigned long long int x, y;\n\n\tif (d2 <= v2) x = d2;\n\telse x = v2;\n\n\ty = d1 + v1;\n\n\tif (x <= y) return x;\n\telse return y;\n}\n\nunsigned long long int get_result3(int d1, int d2, int v1, int v2) {\n\tunsigned long long int x, y;\n\n\tif (d1 + v2 <= d2 + v1) {\n\t\tx = d1 + v2;\n\t\tif (d2 <= v1) y = d2;\n\t\telse y = v1;\n\t} else {\n\t\tx = d2 + v1;\n\t\tif (d1 <= v2) y = d1;\n\t\telse y = v2;\n\t}\n\n\tif (x <= y) return x;\n\telse return y;\n}\n\nint main() {\n\tint d1, d2, v1, v2, x, y;\t\n\tunsigned long long int result1, result2, result3, result;\n\n\tcin >> d1 >> d2 >> v1 >> v2;\n\n\tresult1 = get_result1(d1, d2, v1, v2);\n\tresult2 = get_result2(d1, d2, v1, v2);\n\tresult3 = get_result3(d1, d2, v1, v2);\n\n\tif (result1 >= result2 && result1 >= result3) result = pow(result1, 2);\n\telse if (result2 >= result3) result = pow(result2, 2);\n\telse result = pow(result3, 2);\n\n\tcout << result << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/drought.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1023\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n\nusing namespace std;\n\nstruct city {\n\tint comsumption;\n\tint inhabitants;\n};\n\nbool compareCities(const city &a, const city &b) {\n\treturn a.comsumption < b.comsumption;\n}\n\nvector<city> groupByMediumComsumption(vector<city> &cities) {\n\tvector<city> v;\n\tint n = cities[0].inhabitants, coms = cities[0].comsumption;\n\tfor (int i = 1; i < cities.size(); i++) {\n\t\tif (coms == cities[i].comsumption) n += cities[i].inhabitants;\n\t\telse {\n\t\t\tcity ci;\n\t\t\tci.inhabitants = n;\n\t\t\tci.comsumption = coms;\n\t\t\tv.push_back(ci);\n\t\t\tn = cities[i].inhabitants;\n\t\t\tcoms = cities[i].comsumption;\n\t\t}\n\t}\n\t\n\tcity ci;\n\tci.inhabitants = n;\n\tci.comsumption = coms;\n\tv.push_back(ci);\n\treturn v;\n}\n\nint main() {\n\tint n, c=1, hab, litres;\n\tvector<city> cities;\n\tcin >> n;\n\t\n\twhile (n != 0) {\n\t\tfloat totalLitres = 0, totalInhabitants = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> hab >> litres;\n\t\t\ttotalInhabitants += hab;\n\t\t\ttotalLitres += litres;\n\t\t\tcity ci;\n\t\t\tci.comsumption = litres / hab;\n\t\t\tci.inhabitants = hab;\n\t\t\tcities.push_back(ci);\n\t\t}\n\t\t\n\t\tsort(cities.begin(), cities.end(), compareCities);\n\t\tvector<city> nCities = groupByMediumComsumption(cities);\n\t\t\n\t\tcout << \"Cidade# \" << c << \":\" << endl;\n\t\tcout << nCities[0].inhabitants << \"-\" << nCities[0].comsumption;\n\t\t\n\t\tfor (int i = 1; i < nCities.size(); i++) cout << \" \" << nCities[i].inhabitants << \"-\" << nCities[i].comsumption;\n\t\tcout << endl;\n\t\t\n\t\tcout << fixed << setprecision(2) << \"Consumo medio: \" << (totalLitres / totalInhabitants) - 0.0049999999 << \" m3.\" << endl;\n\t\tcin >> n;\n\t\tif (n) cout << endl;\n\t\tc++;\n\t\tcities.clear();\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/easy_difference_dates.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2315\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\tint dates[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n\tint day1, day2, month1, month2, totalDays;\n\n\tcin >> day1 >> month1 >> day2 >> month2;\t\n\n\tif (month2 > month1) {\n\t\ttotalDays = dates[month1-1] - day1 + day2;\n\t\tfor (int i = month1; i < month2 - 1; i++) totalDays += dates[i];\n\t} else {\n\t\ttotalDays = day2 - day1;\n\t}\n\n\tcout << totalDays << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/easy_fibonacci.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1151\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, n1=0, n2=1, x;\n\tcin >> n;\n\n\tif (n == 1) {\n\t\tcout << n1 << endl;\n\t} else if (n == 2) {\n\t\tcout << n1 << \" \" << n2 << endl;\n\t} else if (n > 2){\n\t\tcout << n1 << \" \" << n2 << \" \";\n\t\tn -= 2;\n\t\twhile (n > 0) {\n\t\t\tx = n2;\n\t\t\tn2 += n1;\n\t\t\tn1 = x;\n\t\t\tcout << n2;\n\n\t\t\tif (n == 1) {\n\t\t\t\tcout << endl;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcout << \" \";\n\t\t\tn--;\n\t\t}\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/easy_problem_from_rujia_liu_1.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1424\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint getKthOccurrence(vector<unsigned long long int> &ar, int k, unsigned long long int v) {\n\tint counter = 0;\n\tfor (int i = 0; i < ar.size(); i++) {\n\t\tif (ar[i] == v) {\n\t\t\tcounter++;\n\t\t\tif (counter == k) return i+1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint main() {\n\tint n, m, k, x;\n\tunsigned long long int v;\t\n\t\n\twhile (cin >> n >> m) {\n\t\tvector<unsigned long long int> ar;\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> x;\n\t\t\tar.push_back(x);\n\t\t}\n\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tcin >> k >> v;\n\t\t\tcout << getKthOccurrence(ar, k, v) << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/easy_problem_from_rujia_liu_2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1424\n\n#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nint getKthOccurrence(map< int, vector<int> > &hash, int k, int v) {\n\tint counter = 0;\t\n\n\tfor (int i = 0; i < hash[v].size(); i++) {\t\t\n\t\tcounter++;\n\t\tif (counter == k) return hash[v][i];\n\t}\n\n\treturn 0;\n}\n\nint main() {\n\tint n, m, k, v, x;\n\t\n\twhile (cin >> n >> m) {\n\t\tmap< int, vector<int> > hash;\n\t\tvector<int> ar;\n\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tcin >> x;\n\t\t\tif (hash.find(x) != hash.end()) hash[x].push_back(i);\n\t\t\telse {\n\t\t\t\tar.push_back(i);\n\t\t\t\thash[x] = ar;\n\t\t\t\tar.clear();\n\t\t\t}\n\t\t}\n\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tcin >> k >> v;\n\t\t\tcout << getKthOccurrence(hash, k, v) << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/eletrical_outlet.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1930\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int t1, t2, t3, t4;\n\n  cin >> t1 >> t2 >> t3 >> t4;\n\n  cout << t1 + t2 + t3 + t4 - 3 << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/encryption.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1024\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint get_index(char letter) {\n\tstring ascii = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ.]^_`abcdefghijklmnopqrstuvwxyz{-}\";\n\tif (letter == '/') letter = '.';\n\treturn ascii.find(letter);\n}\n\nint get_element(char index) {\n\tstring ascii = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ.]^_`abcdefghijklmnopqrstuvwxyz{-}\";\n\tchar element = ascii[index];\n\tif (element == '.') element = '/';\n\treturn element;\n}\n\nint is_number(char letter) {\n\tstring numbers = \"012345678910\";\n\tif (numbers.find(letter) != -1) return 1;\n\treturn 0;\n}\n\nstring shift_to_the_right(string old_string) {\n\tstring new_string = \"\";\n\tstring ascii = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ.]^_`abcdefghijklmnopqrstuvwxyz{-}\";\n\n\tfor (int i = 0; i < old_string.size(); i++) {\n\t\tif (is_number(old_string[i]) || old_string[i] == ' ' || ascii.find(old_string[i]) == -1) {\n\t\t\tnew_string += old_string[i];\n\t\t} else {\n\t\t\tint index = get_index(old_string[i]);\n\t\t\tindex += 3;\n\t\t\tnew_string += get_element(index);\n\t\t}\n\t}\n\n\treturn new_string;\n}\n\nstring shift_to_the_left(string old_string) {\n\tstring new_string = \"\";\n\tstring ascii = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ.]^_`abcdefghijklmnopqrstuvwxyz{-}\";\n\n\tfor (int i = 0; i < old_string.size(); i++) {\n\t\tif (is_number(old_string[i]) || old_string[i] == ' ' || ascii.find(old_string[i]) == -1) {\n\t\t\tnew_string += old_string[i];\n\t\t} else {\n\t\t\tint index = get_index(old_string[i]);\n\t\t\tindex--;\n\t\t\tnew_string += get_element(index);\n\t\t}\n\t}\n\n\treturn new_string;\t\n}\n\nstring reverse(string password) {\n\tstring reversed_string = \"\";\n\tfor (int i = password.size()-1; i >= 0; i--) reversed_string += password[i];\n\treturn reversed_string;\n}\n\nint main() {\t\n\tint n;\n\tcin >> n;\n\tcin.ignore();\n\n\twhile (n--) {\n\t\tstring password, encrypted_password;\n\t\tgetline(cin, password);\n\n\t\t// first step: shift to the right\n\t\tencrypted_password = shift_to_the_right(password);\n\n\t\t// second step: reverse string\n\t\tencrypted_password = reverse(encrypted_password);\n\n\t\t// third step: shift to the left\n\t\tencrypted_password = shift_to_the_left(encrypted_password);\n\n\t\tcout << encrypted_password << endl;\n\t}\n\n\treturn 0;\n}\n\n// Texto #3 --> 3# rvzgV\n// abcABC1 --> 1FECedc\n// vxpdylY .ph --> ks. \\n{frzx\n// vv.xwfxo.fd --> gi.r{hyz-xx\n\n// qvzgV\n// 3B\n// 1EDCedc\n// /n{frzx"
  },
  {
    "path": "competitive-programming/uri/engine_failure.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2167\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int n, current, x, result = 0;\n  cin >> n >> current;\n\n  for (int i = 2; i <= n; i++) {\n    cin >> x;\n    if (x < current) {\n      result = i;\n      break;\n    } else {\n      current = x;\n    }\n  }\n\n  cout << result << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/erasing_and_winning.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/1084\n\n#include <cstdio>\n\n#define MAX 100100\n\nint main(){\n\tchar stack[MAX], num;\n\tint top, n, d, number_of_cleaned;\n\n\twhile (scanf(\"%d%d\", &n, &d) && (n + d)) {\n\t\tnumber_of_cleaned = 0;\n\t\ttop = -1;\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tscanf(\" %c\", &num);\n\n\t\t\twhile (top > -1 && number_of_cleaned < d && num > stack[top]) {\n\t\t\t\ttop--;\n\t\t\t\tnumber_of_cleaned++;\n\t\t\t}\n\n\t\t\tif (top + 1 < n - d) stack[++top] = num;\n\t\t}\n\n\t\tstack[++top] = '\\0';\n\t\tprintf(\"%s\\n\", stack);\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/estimating_the_mean.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint maximum_subsequence_sum(vector<int> &v) {\n\tint max_seq = 0, result = 0, greater = v[0];\n\t\n\tfor (int i = 1; i < v.size(); i++) if (v[i] > greater) greater = v[i];\n\t\n\tfor (int i = 0; i < v.size(); i++) {\n\t    if (v[i] == greater) max_seq++;\n\t    else max_seq = 0;\n\t    if (max_seq > result) result = max_seq;\n\t}\n\t\n\treturn result;\n}\n\nint main() {\n\tint n, num, x, result, casy = 1;\n\tcin >> n;\n\t\n\twhile (n--) {\n\t\tcin >> num;\n\t\tvector<int> v;\n\t\t\n\t\twhile (num--) {\n\t\t\tcin >> x;\n\t\t\tv.push_back(x);\n\t\t}\n\n\t\tresult = maximum_subsequence_sum(v);\n\t\tcout << \"Caso #\" << casy << \": \" << result << endl;\n\t\tcasy++;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/etiquetas_de_noel.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2482\n\n#include <iostream>\n#include <string>\n#include <map>\n\nusing namespace std;\n\nint main() {\n  int N, M;\n  string language, merry, name;\n  map<string, string> languages;\n\n  cin >> N;\n\n  while (N--) {\n    cin >> language;\n    cin.ignore();\n    getline(cin, merry);\n    languages[language] = merry;\n  }\n\n  cin >> M;\n  cin.ignore();\n\n  while (M--) {\n    getline(cin, name);\n    cin >> language;\n    cout << name << endl << languages[language] << endl << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/even_and_odd.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1259\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\tvector<int> odds, evens;\n\tint n;\n\tcin >> n;\n\t\n\twhile (cin >> n) {\n\t\tif (n % 2 == 0) evens.push_back(n);\n\t\telse odds.push_back(n);\n\t}\n\t\n\tsort(evens.begin(), evens.end());\n\tsort(odds.begin(), odds.end(), greater<int>());\n\t\n\tfor (int i = 0; i < evens.size(); i++) cout << evens[i] << endl;\n\tfor (int i = 0; i < odds.size(); i++) cout << odds[i] << endl;\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/even_between_five_numbers.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1065\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint positives=0, negatives=0, even=0, odd=0;\n\n\tfor (int i = 0; i < 5; i++) {\n\t\tint n;\n\t\tcin >> n;\n\n\t\tif (n > 0) {\n\t\t\tpositives++;\n\t\t} else if (n < 0) {\n\t\t\tnegatives++;\n\t\t}\n\n\t\tif (n < 0) n = n * (-1);\n\t\tif (n % 2 == 0) {\n\t\t\teven++;\n\t\t} else {\n\t\t\todd++;\n\t\t}\n\t}\n\n\tcout << even << \" valor(es) par(es)\" << endl;\n\tcout << odd << \" valor(es) impar(es)\" << endl;\n\tcout << positives << \" valor(es) positivo(s)\" << endl;\n\tcout << negatives << \" valor(es) negativo(s)\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/even_numbers.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1059\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tfor (int i = 2; i <= 100; i++) {\n\t\tif (i % 2 == 0) cout << i << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/even_or_odd.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1074\n\n#include <iostream>\n#include <math.h>\n\nusing namespace std;\n\nint main() {\n\n\tlong long int x;\n\tint n;\n\n\tcin >> n;\n\n\twhile (n--) {\n\n\t\tcin >> x;\n\n\t\tif (x == 0) {\n\t\t\tcout << \"NULL\" << endl;\n\t\t} else if (x > 0) {\n\t\t\tif (x % 2 == 0) {\n\t\t\t\tcout << \"EVEN POSITIVE\" << endl;\n\t\t\t} else {\n\t\t\t\tcout << \"ODD POSITIVE\" << endl;\n\t\t\t}\n\t\t} else {\n\t\t\tif (x % 2 == 0) {\n\t\t\t\tcout << \"EVEN NEGATIVE\" << endl;\n\t\t\t} else {\n\t\t\t\tcout << \"ODD NEGATIVE\" << endl;\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/even_square.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1073\n\n#include <iostream>\n#include <math.h>\n\nusing namespace std;\n\nint main() {\n\n\tlong long int n;\n\tcin >> n;\n\n\tfor (long long int i = 2; i <= n; i += 2) {\n\t\tlong long int exp = pow(i, 2);\n\t\tcout << i << \"^2 = \" << exp << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/event.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2172\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\tlong long int n1, n2, total;\n\n\twhile (cin >> n1 >> n2 && n1 + n2 != 0) {\n\t\ttotal = n1 * n2;\n\t\tcout << total << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/event_time.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1061\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\t\n\tstring str1, str2, s3, s4, s5, s6;\n\tint d1, d2, h1, h2, m1, m2, s1, s2;\n\n\tcin >> str1 >> d1;\n\tcin >> h1 >> str2 >> m1 >> s3 >> s1;\n\n\tcin >> s4 >> d2;\n\tcin >> h2 >> s5 >> m2 >> s6 >> s2;\n\n\tint d, h, m, s;\n\n\tif (d2 >= d1) {\n\t\td = d2 - d1;\n\t}\n\n\tif (h2 >= h1) {\n\t\th = h2 - h1;\n\t} else {\n\t\th = 24 - h1 + h2;\n\t\td--;\n\t}\n\n\tif (m2 >= m1) {\n\t\tm = m2 - m1;\n\t} else {\n\t\tm = 60 - m1 + m2;\n\t\th--;\n\t}\t\n\n\tif (s2 >= s1) {\n\t\ts = s2 - s1;\n\t} else {\n\t\ts = 60 - s1 + s2;\n\t\tm--;\n\t}\n\n\tcout << d << \" dia(s)\" << endl;\n\tcout << h << \" hora(s)\" << endl;\n\tcout << m << \" minuto(s)\" << endl;\n\tcout << s << \" segundo(s)\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/exceeding_z.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1150\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int n, n1, n2, total=1;\n\n  cin >> n1 >> n2;\n\n  while (n2 <= n1) {\n    cin >> n2;\n  }\n\n  n = n1;\n\n  while (true) {\n\n    n += n1 + 1;\n    n1++;\n    total++;\n\n    if (n > n2) {\n      break;\n    }\n  }\n\n  cout << total << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/exchanging_cards.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1104\n\n#include <iostream>\n#include <map>\n\nusing namespace std;\n\nint main() {\n\t\n\tint a, b, temp;\n\tcin >> a >> b;\n\n\twhile (a + b != 0) {\n\t\tmap<int, int> alice;\n\t\tmap<int, int> betty;\n\n\t\tfor (int i = 0; i < a; i++) {\n\t\t\tcin >> temp;\n\t\t\tif (alice.find(temp) != alice.end()) alice[temp]++;\n\t\t\telse alice[temp] = 0;\n\t\t}\n\n\t\tfor (int i = 0; i < b; i++) {\n\t\t\tcin >> temp;\n\t\t\tif (betty.find(temp) != betty.end()) betty[temp]++;\n\t\t\telse betty[temp] = 0;\n\t\t}\n\n\t\tint alice_counter = 0, betty_counter = 0;\n\n\t\tfor (map<int, int>::iterator it = alice.begin(); it != alice.end(); it++) {\n\t\t\tif (betty.find(it->first) == betty.end()) alice_counter++;\n\t\t}\n\n\t\tfor (map<int, int>::iterator it = betty.begin(); it != betty.end(); it++) {\n\t\t\tif (alice.find(it->first) == alice.end()) betty_counter++;\n\t\t}\n\n\t\tif (alice_counter < betty_counter) cout << alice_counter << endl;\n\t\telse cout << betty_counter << endl;\n\n\t\tcin >> a >> b;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/experiments.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1094\n\n#include <iostream>\n#include <string>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n\tint c=0, r=0, s=0, n, x;\n\tstring animal;\n\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> x >> animal;\n\t\tif (animal == \"C\") {\n\t\t\tc += x;\n\t\t} else if (animal == \"R\") {\n\t\t\tr += x;\n\t\t} else if (animal == \"S\") {\n\t\t\ts += x;\n\t\t}\t\t\n\t}\n\n\tint total = c + r + s;\n\tdouble total_for_percentage = total;\n\n\tcout << \"Total: \" << total << \" cobaias\" << endl;\n\tcout << \"Total de coelhos: \" << c << endl;\n\tcout << \"Total de ratos: \" << r << endl;\n\tcout << \"Total de sapos: \" << s << endl;\n\tcout << fixed << setprecision(2) << \"Percentual de coelhos: \" << c / total_for_percentage * 100.00 << \" %\" << endl;\n\tcout << fixed << setprecision(2) << \"Percentual de ratos: \" << r / total_for_percentage * 100.00 << \" %\" << endl;\n\tcout << fixed << setprecision(2) << \"Percentual de sapos: \" << s / total_for_percentage * 100.00 << \" %\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/extremely_basic.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/runs/add/1001\n\n#include <iostream>\n \nusing namespace std;\n \nint main() {\n\tint a, b, x;\n\tcin >> a >> b;\n\tcout << \"X = \" << a + b << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/face_2015_free_gift.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1944\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\tint n, giftNumber = 0;\n\tbool opposite;\n\tstring word, lastWord;\n\tchar letter;\n\tcin >> n;\n\n\tvector<string> words;\n\twords.push_back(\"FACE\");\n\n\twhile (n--) {\n\t\tword = \"\";\n\t\topposite = true;\n\t\tlastWord = words.back();\n\n\t\tfor (int i = 3; i >= 0; i--) {\n\t\t\tcin >> letter;\n\t\t\tword += letter;\n\t\t\tif (lastWord[i] != letter) opposite = false;\n\t\t}\n\n\t\tif (opposite) {\n\t\t\tgiftNumber++;\n\t\t\twords.pop_back();\n\t\t\tif (words.empty()) words.push_back(\"FACE\");\n\t\t} else words.push_back(word);\n\t}\n\n\tcout << giftNumber << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/factorial.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1936\n\n#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nint main() {\n\tmap<int, int> factorial;\t\n\tint n, index = 1;\n\tcin >> n;\n\tfactorial[0] = 1;\n\tfactorial[1] = 1;\n\t\n\tfor (int i = 2; factorial[i-1] < n; i++) {\n\t\tif (factorial[i-1] * i > n) break;\n\t\tfactorial[i] = factorial[i-1] * i;\n\t\tindex = i;\n\t}\n\t\n\tint counter = 0;\n\t\n\tfor (int i = index; i > 0 && n > 0; i--) {\n\t\twhile (n >= factorial[i]) {\n\t\t\tn -= factorial[i];\n\t\t\tcounter++;\n\t\t}\n\t}\n\t\n\tcout << counter << endl;\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/factorial_again.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1429\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nlong long int factorial(int n) {\n\tif (n < 1) return 1;\n\treturn n * factorial(n - 1);\n}\n\nint main() {\n\t\n\tint n;\n\tcin >> n;\n\t\n\twhile (n != 0) {\n\t\tvector<int> v;\n\t\tlong long int total = 0;\n\t\t\n\t\twhile (n) {\n\t\t\tv.push_back(n % 10);\n\t\t\tn /= 10;\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < v.size(); i++) total += factorial(i+1) * v[i];\n\t\t\n\t\tcout << total << endl;\n\t\tcin >> n;\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/factorial_sum.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1161\n\n#include <iostream>\n\nusing namespace std;\n\nunsigned long long int factorial(int n) {\n\tif (n == 1) return 1;\n\treturn n * factorial(n - 1);\n}\n\nint main() {\n\n\tint n1, n2;\n\n\tunsigned long long int result1, result2;\n\n\twhile (scanf(\"%llu %llu\", &n1, &n2) != EOF) {\n\t\tresult1 = factorial(n1);\n\t\tresult2 = factorial(n2);\n\t\tcout << result1 + result2 << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/fake_tickets.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1318\n\n#include <iostream>\n#include <map>\n\nusing namespace std;\n\nint main() {\n\t\n\tmap<int, int> m;\n\t\n\tint n1, n2, x;\n\t\n\twhile (cin >> n1 >> n2 && n1 + n2 != 0) {\n\t\tfor (int i = 0; i < n2; i++) {\n\t\t\tcin >> x;\n\t\t\tif (m.find(x) == m.end()) m[x] = 1;\n\t\t\telse m[x]++;\n\t\t}\n\t\t\n\t\tmap<int, int>::iterator it;\n\t\t\n\t\tint counter = 0;\n\n\t\tfor (it = m.begin(); it != m.end(); it++) {\n\t\t\tif (it->second > 1) counter++;\n\t\t}\n\n\t\tcout << counter << endl;\n\t\tm.clear();\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/fans_and_ballons.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1870\n\n#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nint get_left_fan(vector< vector<int> > &matrix, int row, int column) {\n\twhile (true) {\n\t\tcolumn--;\n\t\tif (matrix[row][column] != 0) return matrix[row][column];\n\t}\n}\n\nint get_right_fan(vector< vector<int> > &matrix, int row, int column) {\n\twhile (true) {\n\t\tcolumn++;\n\t\tif (matrix[row][column] != 0) return matrix[row][column];\n\t}\n}\n\nint is_it_safe_for_left(vector< vector<int> > &matrix, int row, int column, int walk_num) {\n\tfor (int i = 1; i <= walk_num; i++) {\n\t\tif (matrix[row][column+i] != 0) return column+i;\n\t}\n\t\n\treturn -1;\n}\n\nint is_it_safe_for_right(vector< vector<int> > &matrix, int row, int column, int walk_num) {\n\tfor (int i = 1; i <= walk_num; i++) {\n\t\tif (matrix[row][column-i] != 0) return column-i;\n\t}\n\treturn -1;\n}\n\nint main() {\n\tint rows, columns, position, temp;\n\t\n\twhile (cin >> rows >> columns >> position && rows + columns + position != 0) {\n\t\tvector<int> v;\n\t\tvector< vector<int> > matrix;\n\n\t\tfor (int i = 0; i < rows; i++) {\n\t\t\tfor (int j = 0; j < columns; j++) {\n\t\t\t\tcin >> temp;\n\t\t\t\tv.push_back(temp);\n\t\t\t}\n\t\t\t\n\t\t\tmatrix.push_back(v);\n\t\t\tv.clear();\n\t\t}\n\t\t\n\t\tint result_row = -1, result_column = -1;\n\t\tposition--;\n\t\t\n\t\tfor (int i = 0; i < rows; i++) {\n\t\t\tif (matrix[i][position] != 0) {\n\t\t\t\tresult_column = position;\n\t\t\t\tresult_row = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tint left_fan = get_left_fan(matrix, i, position);\n\t\t\tint right_fan = get_right_fan(matrix, i, position);\n\t\t\t\t\n\t\t\tif (left_fan > right_fan) {\n\t\t\t\tresult_column = is_it_safe_for_left(matrix, i, position, left_fan - right_fan);\n\t\t\t\tresult_row = i;\n\t\t\t\tif (result_column != -1) break;\n\t\t\t\telse position += left_fan - right_fan;\n\t\t\t} else if (right_fan > left_fan) {\n\t\t\t\tresult_column = is_it_safe_for_right(matrix, i, position, right_fan - left_fan);\n\t\t\t\tresult_row = i;\n\t\t\t\tif (result_column != -1) break;\n\t\t\t\telse position -= right_fan - left_fan;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (result_column == -1) cout << \"OUT \" << position+1 << endl;\n\t\telse cout << \"BOOM \" << result_row+1 << \" \" << result_column+1 << endl;\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/farm_robot.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main (void) {\n\tint A, B, C;\n\n\tcin >> A >> B >> C;\n\n\tint N = 1;\n\tint M = 0;\n\n\tif (C == 1) M++;\n\n\tfor (int i = 0; i < B; i++) {\n\t\tint COMM;\n\n\t\tcin >> COMM;\n\t\n\t\tN += COMM;\n\n\t\tif (N == 0) N = A;\n\t\telse if (N > A) N = 1;\n\n\t\tif (N == C) M++;\n\t}\n\n\tcout << M << endl;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/fase.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n  int N, M, num;\n  vector<int> V;\n\n  cin >> N >> M;\n\n  while (N--) {\n    cin >> num;\n    V.push_back(num);\n  }\n\n  sort(V.begin(), V.end(), greater<int>());\n\n  int result = M;\n\n  for (int i = M; i < V.size(); i++) {\n    if (V[i] == V[i-1]) result++;\n    else break;\n  }\n\n  cout << result << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/fast_fibonacci.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2164\n\n#include <iostream>\n#include <iomanip>\n#include <math.h>\n\nusing namespace std;\n\nlong double fibonacci(int n) {\n  return (pow(((1 + sqrt(5)) / 2), n) - pow(((1 - sqrt(5)) / 2), n)) / sqrt(5);\n}\n\nint main() {\n  int n;\n  cin >> n;\n  cout << fixed << setprecision(1) << fibonacci(n) << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/fast_prime_number.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1221\n\n#include <iostream>\n#include <math.h>\n\nusing namespace std;\n\nint is_prime(int n) {\n\n  if (n == 2)\n    return 1;\n\n  if ((n % 2) == 0)\n    return 0;\n\n  int s = sqrt(n);\n\n  for (int i = 3; i <= s; i += 2) if (n % i == 0) return 0;\n\n  return 1;\n}\n\nint main() {\n\n  int n, x;\n\n  cin >> n;\n\n  while (n--) {\n    cin >> x;\n    if (is_prime(x)) cout << \"Prime\" << endl;\n    else cout << \"Not Prime\" << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/feedback.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1546\n\n#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, k, x;\n\tvector<string> team_members;\n\tteam_members.push_back(\"Rolien\");\n\tteam_members.push_back(\"Naej\");\n\tteam_members.push_back(\"Elehcim\");\n\tteam_members.push_back(\"Odranoel\");\n\t\n\tcin >> n;\n\t\n\twhile (n--) {\n\t\tcin >> k;\n\t\t\n\t\twhile (k--) {\n\t\t\tcin >> x;\n\t\t\tcout << team_members[x-1] << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/feyman.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1323\n\n#include <iostream>\n\nusing namespace std;\n\nint feyman(int n) {\n  if (n == 1) return 1;\n  return n * n + feyman(n - 1);\n}\n\nint main() {\n\n  int n;\n  cin >> n;\n\n  while (n != 0) {\n    cout << feyman(n) << endl;\n    cin >> n;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/fibonacci_again.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1531\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\n#define MOD 1000000007;\nlong long int a,b,c,d;\n\nvoid fast_fib(long long int n,long long int ans[]) {\n  if (n == 0) {\n    ans[0] = 0;\n    ans[1] = 1;\n    return;\n  }\n\n  fast_fib((n/2),ans);\n  a = ans[0];\n  b = ans[1];\n  c = 2 * b - a;\n  \n  if (c < 0) c += MOD;\n  \n  c = (a * c) % MOD;\n  d = (a*a + b*b) % MOD;\n\n  if (n % 2 == 0) {\n    ans[0] = c;\n    ans[1] = d;\n  } else {\n    ans[0] = d;\n    ans[1] = c+d;\n  }\n}\n\nint main() {\n\tlong long int n1;\n\tint n2;\t\n\t\n\twhile (scanf(\"%lli %i\", &n1, &n2) != EOF) {\n\t\tlong long int ans[2]={0};\n    fast_fib(n1, ans);\n    long long int res[2]={0};\n    fast_fib(ans[0], res);\n\t\tcout << res[0] % n2 << endl;\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/fibonacci_array.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1176\n\n#include <iostream>\n\nusing namespace std;\n\nlong long int fib(int n) {\n\n\tlong long int n1=0, n2=1, aux;\n\n\tif (n == 0) {\n\t\treturn 0;\n\t} else if (n == 1) {\n\t\treturn 1;\n\t} else {\n\t\tfor (int i = 1; i < n; i++) {\n\t\t\taux = n2;\n\t\t\tn2 += n1;\n\t\t\tn1 = aux;\n\t\t}\n\n\t\treturn n2;\n\t}\n\n}\n\nint main() {\n\n\tlong long int n;\n\tint x;\n\n\tcin >> n;\n\n\twhile (n--) {\n\n\t\tcin >> x;\n\n\t\tcout << \"Fib(\" << x << \") = \" << fib(x) << endl;\n\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/fila_do_supermercado.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nint getIndexOfSmallerTimeSpent(map<int, int> &m) {\n\tint smaller = 99999, index = 0;\n\tmap<int, int>::iterator it;\n\tfor (it = m.begin(); it != end(); it++) {\n\t\tif (it->second < smaller) {\n\t\t\tsmaller = it->second;\n\t\t\tindex = it->first;\n\t\t}\n\t}\n\n\treturn index;\n}\n\nint main() {\n\tint cashiers, clients, x;\n\tcin >> cashiers >> clients;\n\n\tvector<int> ca, cli;\n\n\tfor (int i = 0; i < cashiers; i++) {\n\t\tcin >> x;\n\t\tca.push_back(x);\n\t}\n\n\tfor (int i = 0; i < clients; i++) {\n\t\tcin >> x;\n\t\tcli.push_back(x);\n\t}\n\n\tmap<int, int> t_gastos;\n\n\tfor (int i = 0; i < cashiers; i++) {\n\t\tt_gastos[i] = cashiers[i] * clients[i];\n\t}\n\n\tint index = getIndexOfSmallerTimeSpent(m);\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/fire_flowers.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1039\n\n#include <iostream>\n#include <math.h>\n\nusing namespace std;\n\nint to_positive(int number) {\n  if (number < 0) return number * (-1);\n  return number;\n}\n\nint main() {\n\n  int r1, x1, y1, r2, x2, y2;\n\n  while (cin >> r1 >> x1 >> y1 >> r2 >> x2 >> y2) {\n    int distance_x = to_positive(x1 - x2);\n    int distance_y = to_positive(y1 - y2);\n    double total_distance = sqrt(pow(distance_x, 2) + pow(distance_y, 2));\n\n    if (r1 < r2) {\n      cout << \"MORTO\" << endl;\n    } else {\n      if (r1 >= r2 + total_distance) cout << \"RICO\" << endl;\n      else cout << \"MORTO\" << endl;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/fit_or_dont_fit_1.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1240\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint verify_number(unsigned long long int n1, unsigned long long int n2) {\n  vector<int> v1, v2;\n\n  while (n2 > 0) {\n    v1.push_back(n1 % 10);\n    v2.push_back(n2 % 10);\n    n1 /= 10;\n    n2 /= 10;\n  }\n\n  for (int j = 0; j < v2.size(); j++) if (v1[j] != v2[j]) return 0;\n  return 1;\n}\n\nint main() {\n  int n;\n  cin >> n;\n\n  while (n--) {\n    unsigned long long int n1, n2;\n    cin >> n1 >> n2;\n\n    if (n1 >= n2 && verify_number(n1, n2)) {\n      cout << \"encaixa\" << endl;\n    } else {\n      cout << \"nao encaixa\" << endl;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/fit_or_dont_fit_2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1241\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\tcin >> n;\n\tstring n1, n2;\n\n\twhile (n--) {\n\t\tcin >> n1 >> n2;\n\n\t\tif (n1.size() >= n2.size()) {\n\t\t\tint pos = n1.size() - n2.size();\n\t\t\tint length = n1.size() - pos;\n\n\t\t\tstring subs = n1.substr(pos, length);\n\n\t\t\tif (subs == n2) cout << \"encaixa\" << endl;\n\t\t\telse cout << \"nao encaixa\" << endl;\n\t\t} else {\n\t\t\tcout << \"nao encaixa\" << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/fixed_password.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1114\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\n\tcin >> n;\n\n\twhile (n != 2002) {\n\t\tcin >> n;\n\t\tcout << \"Senha Invalida\" << endl;\n\t}\n\n\tcout << \"Acesso Permitido\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/flavious_josephus_legend.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1030\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint verify_last_value(vector<int> &v) {\n\tint counter = 0;\n\tfor (int i = 0; i < v.size(); i++) if (v[i] == 1) counter++;\n\treturn counter;\n}\n\nint can_be_counted(vector<int> &v, int index, int n) {\n\twhile (v[index] == 0) {\n\t\tif (index == n - 1) index = 0;\n\t\telse index++;\n\t\tcout << index << \" \";\n\t}\n\tcout << endl;\n\treturn index;\n}\n\nint get_last_value_index(vector<int> &v) {\n\tfor (int i = 0; i < v.size(); i++) if (v[i] == 1) return i;\n}\n\nint main() {\n\t\n\tint nc, n, k, c = 1;\n\n\tcin >> nc;\n\n\twhile (nc--) {\n\t\tcin >> n >> k;\n\n\t\tvector<int> v;\n\t\tint i = 0, counter = 1;\n\n\t\tfor (int i = 0; i < n; i++) v.push_back(1);\n\n\t\twhile (verify_last_value(v)) {\n\t\t\ti = can_be_counted(v, i, n);\n\n\t\t\tif (counter == k) {\n\t\t\t\tv[i] = 0;\n\t\t\t\tcounter = 0;\n\t\t\t} else {\n\t\t\t\tcounter++;\n\t\t\t}\n\n\t\t\ti++;\n\t\t\tif (i == n - 1) i = 0;\n\t\t}\n\n\t\tcout << \"Case \" << c << \": \" << get_last_value_index(v) << endl;\n\t\tc++;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/flavious_josephus_legend2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1030\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint parse_index(int index, int size) {\n\twhile (index >= size) index -= size;\n\treturn index;\t\t\n}\n\nint main() {\n\t\n\tlong long int n, num1, num2;\n\tint casy = 1;\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> num1 >> num2;\n\t\tnum2--;\n\n\t\tvector<int> v;\n\t\tfor (int i = 1; i <= num1; i++) v.push_back(i);\n\t\tint index = 0;\n\n\t\twhile (v.size() > 1) {\n\t\t\tindex += num2;\n\t\t\tindex = parse_index(index, v.size());\n\t\t\tv.erase(v.begin() + index);\n\t\t}\n\n\t\tcout << \"Case \" << casy << \": \" << v[0] << endl;\n\t\tcasy++;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/flavious_josephus_legend3.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1030\n\n#include <iostream>\n\nusing namespace std;\n\nint josephus(int n, int k) {\n\tif (n == 1) return 0;\n\treturn (josephus(n-1, k) + k) % n;\n}\n\nint main() {\n\t\n\tint n, n1, n2, counter = 1;\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> n1 >> n2;\n\t\tcout << \"Case \" << counter << \": \" << josephus(n1, n2)+1 << endl;\n\t\tcounter++;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/flowers_flourish_from_france.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <sstream>\n#include <iterator>\nusing namespace std;\n\nint main() {\n\t\n\tstring frase;\n\tvector<string> palavras;\n\t\n\tgetline(cin, frase);\n\t\n\twhile(frase != \"*\") {\n\t\ttransform(frase.begin(), frase.end(), frase.begin(), ::tolower);\n\t\tistringstream iss(frase);\n\t\tcopy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(palavras));\n\t\t\n\t\tchar letra = frase[0];\n\t\tchar result = 'Y';\n\t\t\n\t\tfor(int i = 0; i < palavras.size(); i++) {\n\t\t\tif(palavras[i][0] != letra) {\n\t\t\t\tresult = 'N';\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcout << result << endl;\n\t\tgetline(cin, frase);\n\t\tpalavras.clear();\n\t}\n\t\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/football.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\t\n\tint matches, num_buy, goals1, goals2;\n\t\n\twhile (cin >> matches >> num_buy) {\n\t\tvector<int> pos, neg, zeros;\n\t\t\n\t\tfor (int i = 0; i < matches; i++) {\n\t\t\tcin >> goals1 >> goals2;\n\t\t\tif (goals1 - goals2 == 0) zeros.push_back(0);\n\t\t\telse if (goals1 - goals2 < 0) neg.push_back(goals1 - goals2);\n\t\t\telse pos.push_back(goals1 - goals2);\n\t\t}\n\t\t\n\t\tint counter = 0;\n\t\tcounter += pos.size() * 3;\n\n\t\t\tfor (int i = 0; i < zeros.size(); i++) {\n\t\t\t\tif (num_buy > 0) {\n\t\t\t\t\tzeros[i]++;\n\t\t\t\t\tnum_buy--;\n\t\t\t\t\tcounter += 3;\n\t\t\t\t} else {\n\t\t\t\t\tcounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tsort(neg.begin(), neg.end(), greater<int>());\n\n\t\t\tif (num_buy > 0) {\n\t\t\t\tint ind = 0;\n\t\t\t\twhile (ind < neg.size()) {\n\t\t\t\t\tif (num_buy <= 0) break;\n\t\t\t\t\tneg[ind]++;\n\t\t\t\t\tnum_buy--;\n\t\t\t\t\tif (neg[ind] > 0) ind++;\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\tfor (int i = 0; i < neg.size(); i++) {\n\t\t\tif (neg[i] == 0) counter++;\n\t\t\telse if (neg[i] > 0) counter += 3;\n\t\t}\n\t\t\n\t\tcout << counter << endl;\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/frequent_asked_questions.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1553\n\n#include <iostream>\n#include <map>\n\nusing namespace std;\n\nint main() {\n\n  int n, k, num;\n\n  while (cin >> n >> k && n + k != 0) {\n    map<int, int> m;\n    int counter = 0;\n\n    for (int i = 0; i < n; i++) {\n      cin >> num;\n      if (m.find(num) != m.end()) m[num]++;\n      else m[num] = 1;\n    }\n\n    map<int, int>::iterator it;\n\n    for (it = m.begin(); it != m.end(); it++) {\n      if (it->second >= k) counter++;\n    }\n\n    cout << counter << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/friends_of_habey.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2136\n\n#include <iostream>\n#include <set>\n#include <vector>\n#include <string>\n#include <algorithm>\n\nusing namespace std;\n\nbool compareByName(string name1, string name2) {\n\treturn name1.size() >= name2.size();\n}\n\nint main() {\n\tstring name, want;\n\tset<string> peopleThatWant;\n\tset<string> peopleThatDoNotWant;\n\tvector<string> v;\n\n\twhile (cin >> name && name != \"FIM\") {\n\t\tcin >> want;\n\t\tif (want == \"YES\") { \n\t\t\tpeopleThatWant.insert(name);\n\t\t\tv.push_back(name);\n\t\t} else peopleThatDoNotWant.insert(name);\n\t}\t\n\n\tfor (set<string>::iterator it = peopleThatWant.begin(); it != peopleThatWant.end(); it++) {\n\t\tcout << *it << endl;\n\t}\n\n\tfor (set<string>::iterator it = peopleThatDoNotWant.begin(); it != peopleThatDoNotWant.end(); it++) {\n\t\tcout << *it << endl;\n\t}\n\n\tcout << endl;\n\n\tsort(v.begin(), v.end(), compareByName);\n\n\tcout << \"Amigo do Habay:\" << endl << v[0] << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/fuel_spent.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1017\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n\tint time, velocity;\n\n\tcin >> time >> velocity;\n\n\tcout << fixed << setprecision(3) << time * velocity / 12.0 << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/functions.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1555\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int n, n1, n2;\n  cin >> n;\n\n  while (n--) {\n    cin >> n1 >> n2;\n    int rafa = (3 * n1) * (3 * n1) + n2 * n2;\n    int beto = 2 * (n1 * n1) + (5 * n2 * 5 * n2);\n    int carlos = (n2 * n2 * n2) - 100 * n1;\n\n    if (rafa > beto && rafa > carlos) cout << \"Rafael ganhou\" << endl;\n    else if (beto > carlos) cout << \"Beto ganhou\" << endl;\n    else cout << \"Carlos ganhou\" << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/galopeira.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2147\n\n#include <iostream>\n#include <string>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\tint n;\n\tfloat seconds;\n\tstring s;\n\tcin >> n;\n\n\twhile (n--)\t{\n\t\tcin >> s;\n\t\tseconds = s.size() / 100.00;\n\t\tcout << fixed << setprecision(2) << seconds << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/game_of_the_greatness.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1397\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n, n1, n2;\n\tcin >> n;\n\n\twhile (n) {\n\t\tint counter1=0, counter2=0;\n\t\twhile (n--) {\n\t\t\tcin >> n1 >> n2;\n\t\t\tif (n1 > n2) counter1++;\n\t\t\telse if (n2 > n1) counter2++;\t\t\t\n\t\t}\n\n\t\tcout << counter1 << \" \" << counter2 << endl;\n\t\tcin >> n;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/general_exam.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2534\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n  int N, Q, X;\n  vector<int> V, R;\n\n  while (cin >> N >> Q) {\n    while (N--) {\n      cin >> X;\n      V.push_back(X);\n    }\n\n    sort(V.begin(), V.end(), greater<int>());\n\n    while (Q--) {\n      cin >> X;\n      cout << V[X-1] << endl;\n    }\n\n    V.clear();\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/getline_fruits.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1217\n\n#include <iostream>\n#include <string>\n#include <iomanip>\n\nusing namespace std;\n\nint num_of_fruits(string fruits) {\n\tint num = 1;\n\tfor (int i = 0; i < fruits.size(); i++) if (fruits[i] == ' ') num++;\n\treturn num;\n}\n\nint main() {\n\tstring fruits;\n\tint n, day_kg = 0, day = 1;\n\tdouble total_kg = 0.0, total_money, money;\n\n\tcin >> n;\n\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> money;\n\t\ttotal_money += money;\n\n\t\tcin.ignore();\n\t\tgetline(cin, fruits);\n\n\t\tday_kg = num_of_fruits(fruits);\n\t\ttotal_kg += day_kg;\n\t\tcout << \"day \" << day << \": \" << day_kg << \" kg\" << endl;\n\t\tday++;\n\t}\n\n\tdouble kg_per_day = total_kg / n, money_per_day = total_money / day;\n\tcout << fixed << setprecision(2) << kg_per_day << \" kg by day\" << endl;\n\tcout << fixed << setprecision(2) << \"R$ \" << money_per_day << \" by day\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/getline_one.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1216\n\n#include <iostream>\n#include <string>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n\tstring s;\n\tint n, counter=0;\n\tdouble total=0;\n\n\twhile (getline(cin, s)) {\n\t\tcin >> n;\n\t\ttotal += n;\n\t\tcounter++;\n\t\tcin.ignore();\n\t}\n\n\tcout << fixed << setprecision(1) << total / counter << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/getline_three_shoes.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1218\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\tbool first = true, found;\n\tstring num, shoes, shoe_num = \"\";\n\tint casy = 1;\n\n\twhile (cin >> num) {\n\t\tint fem = 0, mas = 0, number_shoes = 0;\n\t\tcin.ignore();\n\t\tgetline(cin, shoes);\n\t\tfor (int i = 0; i < shoes.size(); i += 5) {\n\t\t\tint ind = i;\n\t\t\tif (shoes.substr(i, 2) == num) {\n\t\t\t\tind += 3;\n\t\t\t\tif (shoes[ind] == 'F') fem++;\n\t\t\t\telse mas++;\n\t\t\t\tnumber_shoes++;\n\t\t\t}\n\t\t}\n\n\t\tif (first) {\n\t\t\tcout << \"Caso \" << casy << \":\" << endl;\n\t\t\tfirst = false;\n\t\t} else {\n\t\t\tcout << endl << \"Caso \" << casy << \":\" << endl;\n\t\t}\n\n\t\tcout << \"Pares Iguais: \" << number_shoes << endl;\n\t\tcout << \"F: \" << fem << endl;\n\t\tcout << \"M: \" << mas << endl;\n\t\tcasy++;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/going_to_the_market.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1281\n\n#include <iostream>\n#include <map>\n#include <string>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n  string product;\n  int n, numOfPrices, numOfProducts, num;\n  float price, total;\n  cin >> n;\n\n  while (n--) {\n    total = 0;\n    map<string, float> m;\n    cin >> numOfPrices;\n    while (numOfPrices--) {\n      cin >> product >> price;\n      m[product] = price;\n    }\n\n    cin >> numOfProducts;\n    while (numOfProducts--) {\n      cin >> product >> num;\n      total += m[product] * num;\n    }\n\n    cout << fixed << setprecision(2) << \"R$ \" << total << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/grains_in_a_chess_board.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1169\n\n#include <iostream>\n#include <math.h>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, x;\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> x;\n\n\t\tif (x < 64) {\t\t\t\n\t\t\tunsigned long long int grains = 1;\n\t\t\twhile (x--) grains *= 2;\n\t\t\tunsigned long long int kl = (grains / 12) / 1000 ;\n\t\t\tcout << kl << \" kg\" << endl;\n\t\t} else {\n\t\t\tunsigned long long int grains = pow(2, 63) - 1;\n\t\t\tunsigned long long int kl = (grains / 6) / 1000 ;\n\t\t\tcout << kl << \" kg\" << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/grenais.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1131\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n1, n2, n, inter=0, gremio=0, empate=0, total=1;\n\n\tcin >> n1 >> n2;\n\n\tif (n1 > n2) {\n\t\tinter++;\n\t} else if (n2 > n1) {\n\t\tgremio++;\n\t} else {\n\t\tempate++;\n\t}\n\n\tcout << \"Novo grenal (1-sim 2-nao)\" << endl;\n\tcin >> n;\n\n\twhile (n == 1) {\n\n\t\tcin >> n1 >> n2;\n\n\t\tif (n1 > n2) {\n\t\t\tinter++;\n\t\t} else if (n2 > n1) {\n\t\t\tgremio++;\n\t\t} else {\n\t\t\tempate++;\n\t\t}\n\n\t\tcout << \"Novo grenal (1-sim 2-nao)\" << endl;\n\t\tcin >> n;\n\t\ttotal++;\n\t}\n\n\tcout << total << \" grenais\" << endl;\n\tcout << \"Inter:\" << inter << endl;\n\tcout << \"Gremio:\" << gremio << endl;\t\n\tcout << \"Empates:\" << empate << endl;\n\t\n\tif (inter > gremio) cout << \"Inter venceu mais\" << endl;\n\telse if (gremio > inter) cout << \"Gremio venceu mais\" << endl;\n\telse cout << \"Nao houve vencedor\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/growing_sequences.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1146\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint x;\n\n\tcin >> x;\n\n\twhile (x != 0) {\t\t\n\t\tfor (int i = 1; i <= x; i++) {\n\t\t\tcout << i;\n\t\t\tif (i == x) break;\n\t\t\tcout << \" \";\n\t\t}\n\t\t\n\t\tcout << endl;\n\t\tcin >> x;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/guess_what.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1547\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <stdlib.h>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n;\n\tcin >> n;\n\t\n\twhile (n--) {\n\t\tvector<int> v;\n\t\tint n1, n2, temp, result = -1;\n\t\tcin >> n1 >> n2;\n\t\t\n\t\tfor (int i = 0; i < n1; i++) {\n\t\t\tcin >> temp;\n\t\t\tv.push_back(temp);\n\t\t\tif (temp == n2 && result != -1) result = i+1;\n\t\t}\n\t\t\n\t\tif (result != -1) {\n\t\t\tcout << result << endl;\n\t\t} else {\n\t\t\t\n\t\t\tint min = 101;\n\t\t\tfor (int i = 0; i < v.size(); i++) {\n\t\t\t\tif (abs(n2 - v[i]) < min) {\n\t\t\t\t\tmin = abs(n2 - v[i]);\n\t\t\t\t\tresult = i+1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcout << result << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/guilherme_and_his_kites.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1921\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tlong long int n;\n\tcin >> n;\n\n\tcout << n * (n - 3) / 2 << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/guru_da_sorte.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2508\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint get_value_for(string name) {\n  int value = 0;\n  for (int i = 0; i < name.size(); i++) {\n    if (name[i] == 'A' || name[i] == 'a' || name[i] == 'j' || name[i] == 'J' || name[i] == 's' || name[i] == 'S') value++;\n    else if (name[i] == 'B' || name[i] == 'b' || name[i] == 'k' || name[i] == 'K' || name[i] == 't' || name[i] == 'T') value += 2;\n    else if (name[i] == 'C' || name[i] == 'c' || name[i] == 'l' || name[i] == 'L' || name[i] == 'u' || name[i] == 'U') value += 3;\n    else if (name[i] == 'D' || name[i] == 'd' || name[i] == 'm' || name[i] == 'M' || name[i] == 'v' || name[i] == 'V') value += 4;\n    else if (name[i] == 'E' || name[i] == 'e' || name[i] == 'n' || name[i] == 'N' || name[i] == 'w' || name[i] == 'W') value += 5;\n    else if (name[i] == 'F' || name[i] == 'f' || name[i] == 'o' || name[i] == 'O' || name[i] == 'x' || name[i] == 'X') value += 6;\n    else if (name[i] == 'G' || name[i] == 'g' || name[i] == 'p' || name[i] == 'P' || name[i] == 'y' || name[i] == 'Y') value += 7;\n    else if (name[i] == 'H' || name[i] == 'h' || name[i] == 'q' || name[i] == 'Q' || name[i] == 'z' || name[i] == 'Z') value += 8;\n    else if (name[i] == 'I' || name[i] == 'i' || name[i] == 'r' || name[i] == 'R') value += 9;\n  }\n  return value;\n}\n\nint get_result(int N) {\n  int num;\n\n  while (N >= 10) {\n    num = 0;\n\n    while (N > 0) {\n\t  \tnum += N % 10;\n\t  \tN /= 10;\n\t  }\n\n    N = num;\n  }\n\n  return N;\n}\n\nint main() {\n  int N, num;\n  string name;\n\n  while (getline(cin, name)) {\n    N = get_value_for(name);\n    cout << get_result(N) << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/hailstone_sequences.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1441\n\n#include <iostream>\n\nusing namespace std;\n\nint resolve(int h, int max) {\n\tif (h == 1) return max;\n\tcout << \"h: \" << h << \" max: \" << max << endl;\n\tif (h % 2 == 0) h = h / 2;\n\telse h = 3 * h + 1;\n\n\tif (h > max) max = h;\n\treturn resolve(h, max);\n}\n\nint main() {\n\t\n\tint n;\n\n\twhile (cin >> n && n) {\n\t\tcout << resolve(n, n) << endl;\n\t}\n\t\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/hall_of_murderers.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1861\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nbool find(string murder, vector<string> &people_killed) {\n\tfor (int j = 0; j < people_killed.size(); j++) {\n\t\tif (people_killed[j] == murder) return true;\n\t}\n\n\treturn false;\n}\n\nint main() {\n\tvector<string> people_killed;\n\tvector< pair<string, int> > murders;\n\tstring murder, killed;\n\n\twhile (cin >> murder >> killed) {\n\t\tbool found = false;\n\t\tfor (int i = 0; i < murders.size(); i++) {\n\t\t\tif (murders[i].first == murder) {\n\t\t\t\tfound = true;\n\t\t\t\tmurders[i].second++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (!found) murders.push_back(make_pair(murder, 0));\n\t\tpeople_killed.push_back(killed);\n\t}\n\n\tfor (int i = 0; i < people_killed.size(); i++) cout << people_killed[i] << \" \";\n\tcout << endl;\n\tfor (int i = 0; i < murders.size(); i++) cout << murders[i].first << \" \";\n\tcout << endl;\n\n\tint num_of_killed = 0;\n\n\tfor (int i = 0; i < murders.size(); i++) {\n\t\tif (find(murders[i].first, people_killed)) {\n\t\t\tmurders.erase(murders.begin() + i + 1 - num_of_killed);\n\t\t\tnum_of_killed++;\n\t\t}\n\t}\n\n\tsort(murders.begin(), murders.end());\n\n\tcout << \"HALL OF MURDERERS\" << endl;\n\n\tfor (int j = 0; j < murders.size(); j++) cout << murders[j].first << \" \" << murders[j].second << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/hall_of_murderers_2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1861\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nstruct person {\n  string name;\n  int kill;\n  bool killed;\n};\n\nint findPerson(vector<person> &people, string name) {\n  for (int i = 0; i < people.size(); i++) {\n    if (people[i].name == name) return i;\n  }\n  return -1;\n}\n\nbool compareByName(const person &a, const person &b) {\n  return a.name < b.name;\n}\n\nint main() {\n  int murderIndex, victimIndex;\n  string murder, victim;\n  vector<person> people;\n\n  while (cin >> murder >> victim) {\n    murderIndex = findPerson(people, murder);\n    if (murderIndex != -1) {\n      people[murderIndex].kill++;\n    } else {\n      person p;\n      p.kill = 1;\n      p.killed = false;\n      people.push_back(p);\n    }\n\n    victimIndex = findPerson(people, victim);\n    if (victimIndex != -1) people[victimIndex].killed = true;\n  }\n\n  cout << \"HALL OF MURDERERS\" << endl;\n\n  sort(people.begin(), people.end(), compareByName);\n\n  for (int i = 0; i < people.size(); i++) {\n    if (!people[i].killed) {\n      cout << people[i].name << \" \" << people[i].kill << endl;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/hall_of_murderers_3.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1861\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <map>\n#include <string>\n\nusing namespace std;\n\nint main() {\n  const int DEAD = -1;\n  int murderIndex, victimIndex;\n  string murder, victim;\n  map<string, int> people;\n\n  while (cin >> murder >> victim) {\n    if (people.find(murder) != people.end() && people[murder] != DEAD) people[murder]++;\n    else if (people.find(murder) == people.end()) people[murder] = 1;\n\n    if (people.find(victim) != people.end()) people[victim] = DEAD;\n    else if (people.find(victim) == people.end()) people[victim] = DEAD;\n  }\n\n  cout << \"HALL OF MURDERERS\" << endl;\n\n  for (map<string, int>::iterator it = people.begin(); it != people.end(); ++it) {\n    if (it->second != DEAD) cout << it->first << \" \" << it->second << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/hamekameka.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2591\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nstring ka(int as) {\n  string s = \"k\";\n  for (int i = 0; i < as; i++) s += \"a\";\n  return s;\n}\n\nint main() {\n  int N, as;\n  string s;\n\n  cin >> N;\n\n  while (N--) {\n    cin >> s;\n    as = (s.find(\"m\") - 1) * (s.size() - 3 - s.find(\"k\"));\n    cout << ka(as) << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/handball.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1715\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint players, matches, p;\n\n\twhile (cin >> players >> matches) {\n\t\tint counter = 0;\n\t\tfor (int i = 0; i < players; i++) {\n\t\t\tbool scored = true;\n\t\t\tfor (int j = 0; j < matches; j++) {\n\t\t\t\tcin >> p;\n\t\t\t\tif (p == 0) scored = false;\n\t\t\t}\n\n\t\t\tif (scored) counter++;\n\t\t}\n\n\t\tcout << counter << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/hardwood_species.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1260\n\n#include <iostream>\n#include <map>\n#include <string>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\tint n;\n\tfloat numberOfTrees;\n\tstring name;\n\n\tcin >> n;\n\tcin.ignore();\n\tgetline(cin, name);\n\n\twhile (n--) {\n\t\tmap<string, float> trees;\n\t\tnumberOfTrees = 0;\n\t\t\n\t\twhile (getline(cin, name)) {\n\t\t\tif (name != \"\") {\n\t\t\t\tif (trees.find(name) != trees.end()) trees[name]++;\n\t\t\t\telse trees[name] = 1;\n\t\t\t\tnumberOfTrees++;\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\t\t\t\n\t\t}\n\n\t\tmap<string, float>::iterator it;\t\t\n\n\t\tfor (it = trees.begin(); it != trees.end(); ++it) {\n\t\t\tcout << fixed << setprecision(4) << it->first << \" \" << (it->second / numberOfTrees) * 100.00 << endl;\n\t\t}\n\n\t\tif (n != 0) cout << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/hash_tables.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1256\n\n#include <iostream>\n#include <map>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\tint n, m, c, x, key;\n\tcin >> n;\n\t\n\tfor (int a = 0; a < n; a++) {\n\t\tmap<int, vector<int> > hash;\n\t\tvector<int> v;\n\t\tcin >> m >> c;\n\n\t\tfor (int i = 0; i < c; i++) {\n\t\t\tcin >> x;\n\t\t\tkey = x % m;\n\t\t\thash[key].push_back(x);\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tcout << i << \" -> \";\n\t\t\tfor (int j = 0; j < hash[i].size(); j++) cout << hash[i][j] << \" -> \";\n\t\t\tcout << \"\\\\\" << endl;\n\t\t}\n\t\t\n\t\tif (a < n-1) cout << endl;\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/hashmat_the_brave_warrior.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1198\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  long long int n1, n2;\n\n  while (scanf(\"%llu %llu\", &n1, &n2) != EOF) {\n    if (n1 > n2) cout << n1 - n2 << endl;\n    else cout << n2 - n1 << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/hay_points.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1261\n\n#include <iostream>\n#include <map>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\tint n1, n2, points;\n\tcin >> n1 >> n2;\n\tmap<string, int> wordPoints;\n\tstring word;\n\n\tfor (int i = 0; i < n1; i++) {\n\t\tcin >> word >> points;\n\t\twordPoints[word] = points;\n\t}\n\n\tint totalPoints;\n\tstring wordOfJobDescription;\n\n\twhile (n2--) {\n\t\ttotalPoints = 0;\n\n\t\twhile(cin >> wordOfJobDescription && wordOfJobDescription != \".\") {\n\t\t\tif (wordPoints.find(wordOfJobDescription) != wordPoints.end())\n\t\t\t\ttotalPoints += wordPoints[wordOfJobDescription];\n\t\t}\n\n\t\tcout << totalPoints << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/he_is_offside!.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1410\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nint main() {\n\t\n\tint n, m, temp1, temp2;\n\tchar result;\n\tvector<int> atacantes;\n\tvector<int> defensores;\n\t\n\tcin >> n;\n\tcin >> m;\n\t\n\twhile (n + m != 0) {\n\t\t\n\t\tfor(int i = 0; i < n; i++) {\n\t\t\tcin >> temp1;\n\t\t\tatacantes.push_back(temp1);\n\t\t}\n\t\t\n\t\tfor(int j = 0; j < m; j++) {\n\t\t\tcin >> temp2;\n\t\t\tdefensores.push_back(temp2);\n\t\t}\n\t\t\n\t\tsort(atacantes.begin(), atacantes.end());\n\t\tsort(defensores.begin(), defensores.end());\n\t\t\n\t\t\n\t\tif (atacantes[0] < defensores[1])\n\t\t\tcout << \"Y\" << endl;\n\t\telse\n\t\t\tcout << \"N\" << endl;\n\t\t\n\t\tcin >> n;\n\t\tcin >> m;\n\t\tatacantes.clear();\n\t\tdefensores.clear();\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/head_or_tails.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1329\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int mary=0, john=0;\n  int n, temp;\n  cin >> n;\n\n  while (n != 0) {\n    while (n--) {\n      cin >> temp;\n      if (temp) john++;\n      else mary++;\n    }\n\n    cout << \"Mary won \" << mary << \" times and John won \" << john << \" times\" << endl;\n    cin >> n;\n  }\n\n}\n"
  },
  {
    "path": "competitive-programming/uri/height.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1566\n\n#include <stdio.h>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n  int n, x, num;\n  scanf(\"%i\", &n);\n\n  while (n--) {\n    vector<int> v;\n    scanf(\"%i\", &num);\n    for (int i = 0; i < num; i++) {\n      scanf(\"%i\", &x);\n      v.push_back(x);\n    }\n    sort(v.begin(), v.end());\n    printf(\"%i\", v[0]);\n    for (int i = 1; i < num; i++) printf(\" %i\", v[i]);\n    printf(\"\\n\");\n  }\n\n  return 0;\n}\n\n"
  },
  {
    "path": "competitive-programming/uri/hello_galaxy.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1515\n\n#include <iostream>\n#include <string>\n#include <map>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, year, years;\n\tstring planet;\n\n\twhile (cin >> n && n != 0) {\n\t\tmap<int, string> m;\n\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tcin >> planet >> year >> years;\n\t\t\tm[year+years] = planet;\n\t\t}\n\n\t\tcout << m.begin()->second << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/help!.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1367\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nbool problem_incorrected(string problems, char problem) {\n\tif (problems.find(problem) != -1) return true;\n\treturn false;\n}\n\nbool problem_solved(string problems, char problem) {\n\tif (problems.find(problem) != -1) return true;\n\treturn false;\n}\n\nint incorrect_submission_counter(string problems, char problem) {\n\tint counter = 0;\n\tfor (int i = 0; i < problems.size(); i++) if (problems[i] == problem) counter++;\n\treturn counter;\n}\n\nint main() {\n\t\n\tint n;\n\tcin >> n;\n\tstring solved_problems = \"\";\n\tstring incorrect_problems = \"\";\n\n\twhile (n != 0) {\n\t\tint total_points = 0;\n\t\tchar problem;\n\t\tint point;\n\t\tstring status;\n\n\t\tfor (int i = 0; i < n; i++) {\t\t\t\n\t\t\tcin >> problem >> point >> status;\n\t\t\tif (status == \"correct\") {\n\t\t\t\tif (!problem_solved(solved_problems, problem)) {\n\t\t\t\t\tif (problem_incorrected(incorrect_problems, problem)) total_points += point + 20 * incorrect_submission_counter(incorrect_problems, problem);\n\t\t\t\t\telse total_points += point;\n\t\t\t\t\tsolved_problems += problem;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tincorrect_problems += problem;\n\t\t\t}\n\t\t}\t\t\n\n\t\tcout << solved_problems.size() << \" \" << total_points << endl;\n\t\tsolved_problems.clear();\n\t\tincorrect_problems.clear();\n\t\tcin >> n;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/help_girafales.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1911\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint get_index(vector< pair<string, string> > names, string name) {\n\tfor (int i = 0; i < names.size(); i++) {\n\t\tif (names[i].first == name) return i;\n\t}\n}\n\nint main() {\n\tvector< pair<string, string> > names;\n\tint n, m, counter = 0;\n\tstring name, signature;\n\n\tcin >> n;\n\n\twhile (n != 0) {\n\t\twhile (n--) {\n\t\t\tcin >> name >> signature;\n\t\t\tnames.push_back(make_pair(name, signature));\n\t\t}\n\n\t\tcin >> m;\n\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tcin >> name >> signature;\n\t\t\tbool falsy = false;\n\t\t\tint error_counter = 0;\n\n\t\t\tint ind = get_index(names, name);\n\n\t\t\tfor (int j = 0; j < signature.size(); j++) {\n\t\t\t\t//cout << names[i].second[j] << \" \" << signature[j] << endl;\n\t\t\t\tif (names[ind].second[j] != signature[j]) error_counter++;\n\t\t\t\tif (error_counter > 1) {\n\t\t\t\t\tfalsy = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (falsy) counter++;\n\t\t}\n\n\t\tcout << counter << endl;\n\t\tcounter = 0;\n\t\tcin >> n;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/help_seu_madruga.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1912\n\n#include <iostream>\n#include <vector>\n#include <iomanip>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\n\tint n, temp, a, total=0, counter=0, greater=0, result;\t\n\n\tcin >> n >> a;\n\n\twhile (n + a != 0) {\n\t\tvector<int> v;\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> temp;\n\t\t\ttotal += temp;\n\t\t\tv.push_back(temp);\n\n\t\t\tif (temp > greater) greater = temp;\n\t\t}\n\n\t\tresult = greater - 1;\n\n\t\tif (total == a) {\n\t\t\tcout << \":D\" << endl;\n\t\t} else {\n\t\t\tsort(v.begin(), v.end(), std::greater<int>());\n\n\t\t\twhile (true) {\n\t\t\t\tcounter = 0;\n\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\tif (v[i] - result > 0) counter += v[i] - result;\n\t\t\t\t\telse break;\n\t\t\t\t}\n\n\t\t\t\tif (counter >= a) break;\n\t\t\t\telse result--;\n\t\t\t}\n\n\t\t\tif (counter == a) {\n\t\t\t\tdouble bla = result;\n\t\t\t\tcout << fixed << setprecision(4) << bla << endl;\n\t\t\t} else {\n\t\t\t\tcout << \"-.-\" << endl;\n\t\t\t}\n\t\t}\n\n\t\tcin >> n >> a;\n\t\ttotal = 0;\n\t\tgreater = 0;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/help_seu_madruga_int.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1912\n\n#include <iostream>\n#include <vector>\n#include <iomanip>\n\nusing namespace std;\n\nint get_bigger(vector<int> &v) {\n\tint max = v[0];\n\tfor (int i = 1; i < v.size(); i++) if (v[i] > max) max = v[i];\n\treturn max;\n}\n\nint area_binary_search(vector<int> &v, int area) {\n\tint NOT_FOUND = -1;\n\tint low = 0, high = get_bigger(v), mid, sum;\n\n\twhile (low <= high) {\n\t\tmid = (low + high) / 2;\n\t\tsum = 0;\n\n\t\tfor (int i = 0; i < v.size(); i++) if (v[i] - mid > 0) sum += v[i] - mid;\n\n\t\tif (sum == area) return mid;\n\t\telse if (sum > area) low = mid + 1;\n\t\telse high = mid - 1;\n\t}\n\n\treturn NOT_FOUND;\t\n}\n\nint main() {\n\tvector<int> v;\n\tint n, x, value, temp, counter;\n\t\n\tcin >> n >> value;\n\n\twhile (n + value != 0) {\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> temp;\n\t\t\tv.push_back(temp);\n\t\t}\n\n\t\tfloat result;\n\n\t\tresult = area_binary_search(v, value);\n\n\t\tif (result == -1) cout << \"-.-\" << endl;\n\t\telse if (result == 0) cout << \":D\" << endl;\n\t\telse cout << fixed << setprecision(4) << result << endl;\n\t\t\n\t\tcin >> n >> value;\n\t\tv.clear();\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/help_the_federation.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1588\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nstruct team {\n  int id;\n  string name;\n  int points;\n  int wins;\n  int goals;\n};\n\nbool compareTeams(const team &team1, const team &team2) {\n\tif (team1.points > team2.points) return true;\n\telse if (team1.points == team2.points) {\n\t\tif (team1.wins > team2.wins) return true;\n\t\telse if (team1.wins == team2.wins) {\n\t\t\tif (team1.goals > team2.goals) return true;\n\t\t\telse if (team1.goals == team2.goals && team1.id < team2.id) return true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nint main() {\n\n  int num, n, m, goal1, goal2;\n  string name, player1, player2;\n  cin >> num;\n  \n  while (num--) {\n  \tcin >> n >> m;\n  \tvector<team> teams;\n  \t\n  \tfor (int i = 0; i < n; i++) {\n  \t\tteams.push_back(team());\n  \t\tcin >> name;\n  \t\tteams[i].id = i;\n  \t\tteams[i].name = name;\n  \t\tteams[i].points = 0;\n  \t\tteams[i].wins = 0;\n  \t\tteams[i].goals = 0;\n  \t}\n  \t\n  \tfor (int i = 0; i < m; i++) {\n  \t\tcin >> goal1 >> player1 >> goal2 >> player2;\n\n  \t\tif (goal1 > goal2) {\n\t  \t\tfor (int j = 0; j < teams.size(); j++) {\n\t  \t\t\tif (teams[j].name == player1) {\n\t  \t\t\t\tteams[j].points += 3;\n\t  \t\t\t\tteams[j].wins++;\n\t  \t\t\t\tteams[j].goals += goal1;\n\t  \t\t\t}\n\t  \t\t\t\n\t  \t\t\tif (teams[j].name == player2) teams[j].goals += goal2;\n\t  \t\t}\n\t  \t} else if (goal1 < goal2) {\n\t  \t\tfor (int j = 0; j < teams.size(); j++) {\n\t  \t\t\tif (teams[j].name == player2) {\n\t  \t\t\t\tteams[j].points += 3;\n\t  \t\t\t\tteams[j].wins++;\n\t  \t\t\t\tteams[j].goals += goal2;\n\t  \t\t\t}\n\t  \t\t\t\n\t  \t\t\tif (teams[j].name == player1) teams[j].goals += goal1;\n\t  \t\t}\n\t  \t} else {\n\t  \t\tfor (int j = 0; j < teams.size(); j++) {\n\t  \t\t\tif (teams[j].name == player1) {\n\t  \t\t\t\tteams[j].points++;\n\t  \t\t\t\tteams[j].goals += goal1;\n\t  \t\t\t}\n\t  \t\t\t\n\t  \t\t\tif (teams[j].name == player2) {\n\t  \t\t\t\tteams[j].points++;\n\t  \t\t\t\tteams[j].goals += goal2;\n\t  \t\t\t}\n\t  \t\t}\n\t  \t}\n  \t\t\n  \t}\n  \t\n  \tsort(teams.begin(), teams.end(), compareTeams);\n  \t\n  \tfor (int i = 0; i < teams.size(); i++) {\n  \t\tcout << teams[i].name << endl;\n  \t}\n  \t\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/hexagonal_tiles_1.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1393\n\n#include <iostream>\n#include <map>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n;\n\tmap<int, int> m;\n\n\tm[1] = 1;\n\tm[2] = 2;\n\tm[3] = 3;\n\tm[4] = 5;\n\tm[5] = 8;\n\tm[6] = 13;\n\tm[7] = 21;\n\tm[8] = 34;\n\tm[9] = 55;\n\tm[10] = 89;\n\tm[11] = 144;\n\tm[12] = 233;\n\tm[13] = 377;\n\tm[14] = 610;\n\tm[15] = 987;\n\tm[16] = 1597;\n\tm[17] = 2584;\n\tm[18] = 4181;\n\tm[19] = 6765;\n\tm[20] = 10946;\n\tm[21] = 17711;\n\tm[22] = 28657;\n\tm[23] = 46368;\n\tm[24] = 75025;\n\tm[25] = 121393;\n\tm[26] = 196418;\n\tm[27] = 317811;\n\tm[28] = 514229;\n\tm[29] = 832040;\n\tm[30] = 1346269;\n\tm[31] = 2178309;\n\tm[32] = 3524578;\n\tm[33] = 5702887;\n\tm[34] = 9227465;\n\tm[35] = 14930352;\n\tm[36] = 24157817;\n\tm[37] = 39088169;\n\tm[38] = 63245986;\n\tm[39] = 102334155;\n\tm[40] = 165580141;\n\n\twhile (cin >> n && n) {\n\t\tcout << m[n] << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/hexagonal_tiles_2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1393\n\n#include <iostream>\n\nusing namespace std;\n\nint resolve(int n1, int n2) {\n\tif (n == 1) return 1;\n\telse if (n == 2) return 2;\n\telse return resolve(n-2, n-1);\n}\n\nint main() {\n\t\n\tint n;\n\n\twhile (cin >> n && n) {\n\t\tif (n == 1) cout << 1 << endl;\n\t\telse if (n == 2) cout << 2 << endl;\n\t\telse cout << resolve(n-2, n-1) << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/hidden_message.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1272\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n  int n;\n  cin >> n;\n  string s;\n  getline(cin, s);\n\n  while (n--) {\n    getline(cin, s);\n    int can_get_letter = 1;\n    string result = \"\";\n    for (int i = 0; i < s.size(); i++) {\n      if (can_get_letter && s[i] != ' ') {\n        result.push_back(s[i]);\n        can_get_letter = 0;\n      } else {\n        if (s[i] == ' ') can_get_letter = 1;\n      }\n    }\n\n    cout << result << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/highest_and_position.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1080\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n, max=0, index;\n\n\tfor (int i = 1; i <= 100; i++) {\n\t\tcin >> n;\n\t\tif (n > max) {\n\t\t\tmax = n;\n\t\t\tindex = i;\n\t\t}\n\t}\n\n\tcout << max << endl << index << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/hohoho.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1759\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\tcin >> n;\n\n\tfor (int i = 0; i < n; i++) {\n\n\t\tif (n-1 == i) {\n\t\t\tcout << \"Ho!\" << endl;\n\t\t} else {\n\t\t\tcout << \"Ho \";\n\t\t}\n\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/honey_reservoir.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2029\n\n#include <iostream>\n#include <iomanip>\n#include <math.h>\n\nusing namespace std;\n\nint main() {\n\n  float vol, diam, area, height, pi=3.14, radius;\n\n  while (scanf(\"%f %f\", &vol, &diam) != EOF) {\n    radius = diam / 2;\n    area = pi * pow(radius, 2);\n    height = vol / area;\n    cout << fixed << setprecision(2) << \"ALTURA = \" << height << endl;\n    cout << fixed << setprecision(2) << \"AREA = \" << area << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/hours_and_minutes.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1300\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {  \n  int angle;\n\n  while (scanf(\"%i\", &angle) != EOF) {\n    if (angle % 6 == 0) cout << \"Y\" << endl;\n    else cout << \"N\" << endl;\n  }\n\n  return 0;\n}"
  },
  {
    "path": "competitive-programming/uri/how_easy.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1243\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nbool correct_word(string word) {\n\tstring not_word_part = \"0123456789 .\";\n\tfor (int j = 0; j < word.size(); j++) if (not_word_part.find(word[j]) != -1) return false;\n\treturn true;\n}\n\nvector<string> parse_string(string line) {\n\tvector<string> v;\n\tstring word = \"\";\n\t\n\tfor (int i = 0; i < line.size(); i++) {\n\t\tif (line[i] == ' ' && word.size() > 0) {\n\t\t\tif (correct_word(word)) v.push_back(word);\n\t\t\tword.clear();\n\t\t} else if (line[i] == '.' && i < line.size() - 1 && line[i+1] == ' ' && word.size() > 0) {\n\t\t\tif (correct_word(word)) v.push_back(word);\n\t\t\tword.clear();\n\t\t\tword += line[i];\n\t\t} else if (i == line.size() - 1) {\n\t\t\tif (line[i] != '.') word += line[i];\n\t\t\tif (correct_word(word)) v.push_back(word);\n\t\t\tword.clear();\n\t\t} else {\n\t\t\tif (line[i] != ' ') word += line[i];\n\t\t}\n\t}\n\t\n\treturn v;\n}\n\nint main() {\t\n\tvector<string> words;\n\tstring phrase;\n\tint word_size_counter = 0, words_size, average;\n\n\twhile (getline(cin, phrase)) {\n\t\twords = parse_string(phrase);\n\t\twords_size = words.size();\n\n\t\tif (words_size) {\n\t\t\tfor (int i = 0; i < words_size; i++) word_size_counter += words[i].size();\n\t\t\taverage = word_size_counter / words_size;\n\n\t\t\tif (average <= 3) cout << 250 << endl;\n\t\t\telse if (average <= 5) cout << 500 << endl;\n\t\t\telse cout << 1000 << endl;\n\t\t} else {\n\t\t\tcout << 250 << endl;\n\t\t}\n\n\t\tword_size_counter = 0;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/huehue.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2242\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nstring removeConsoants(string s) {\n\tstring stringWithoutConsoants = \"\",\n\t\t\t\t vogals = \"aeiou\";\n\n\n\tfor (int i = 0; i < s.size(); i++) {\n\t\tif (vogals.find(s[i]) != -1)\n\t\t\tstringWithoutConsoants += s[i];\n\t}\n\n\treturn stringWithoutConsoants;\n}\n\nbool funniest(string s) {\n\tfor (int i = 0; i < s.size(); i++) {\n\t\tif (s[i] != s[s.size()-i-1])\n\t\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nint main() {\n\tstring s;\n\tcin >> s;\n\n\ts = removeConsoants(s);\n\n\tif (funniest(s)) cout << \"S\" << endl;\n\telse cout << \"N\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/i_am_toorg.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int N;\n  cin >> N;\n\n  while (N--) {\n    cout << \"I am Toorg!\" << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/ice_statuses.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/1034\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint min(int a, int b) {\n  return (a < b)? a : b;\n}\n\nint main() {\n  int T, N, M, num;\n\n  cin >> T;\n\n  while (T--) {\n    cin >> N >> M;\n    vector<int> V;\n\n    while (N--) {\n      cin >> num;\n      V.push_back(num);\n    }\n\n    sort(V.begin(), V.end());\n\n    int dp[V.size()][M+1];\n\n    for (int i = 0; i <= M; i++) dp[0][i] = i;\n\n    for (int i = 1; i < V.size(); i++) {\n      for (int j = 0; j <= M; j++) {\n        if (V[i] <= j) dp[i][j] = min(1 + dp[i][j-V[i]], dp[i-1][j]);\n        else dp[i][j] = dp[i-1][j];\n      }\n    }\n\n    cout << dp[V.size()-1][M] << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/identifying_tea.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2006\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n, counter=5, total=0, x;\n\tcin >> n;\n\n\twhile (counter--) {\n\t\tcin >> x;\n\t\tif (n == x) total++;\n\t}\n\n\tcout << total << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/image.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1516\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nstring concatenate(char c, int times) {\n  string new_string = \"\";\n  for (int i = 0; i < times; i++) new_string += c;\n  return new_string;\n}\n\nint main() {\n\n  int m, n, a, b;\n\n  cin >> m >> n;\n\n  while (m + n != 0) {\n    string v = \"\";\n    vector<string> draw;\n    char pixel;\n\n    for (int i = 0; i < m; i++) {\n      for (int j = 0; j < n; j++) {\n        cin >> pixel;\n        v += pixel;\n      }\n\n      draw.push_back(v);\n      v.clear();\n    }\n\n    cin >> a >> b;\n    int mult_m = a / m, mult_n = b / n;\n\n    for (int i = 0; i < m; i++) {\n      string line = \"\";\n      for (int j = 0; j < n; j++) line += concatenate(draw[i][j], mult_n);\n      for (int x = 0; x < mult_m; x++) cout << line << endl;\n    }\n\n    cout << endl;\n    draw.clear();\n    cin >> m >> n;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/impar_par_roubo.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2059\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint p, j1, j2, r, a;\n\tcin >> p >> j1 >> j2 >> r >> a;\n\n\tif (r == 1 && a == 1) cout << \"Jogador 2 ganha!\" << endl;\n\telse if (r == 1 && a == 0) cout << \"Jogador 1 ganha!\" << endl;\n\telse {\n\t\tint sum = j1 + j2;\n\t\tif (sum % 2 == 0 && p == 1) cout << \"Jogador 1 ganha!\" << endl;\n\t\telse if (sum % 2 == 0 && p == 0) cout << \"Jogador 2 ganha!\" << endl;\n\t\telse if (sum % 2 != 0 && p == 0) cout << \"Jogador 1 ganha!\" << endl;\n\t\telse cout << \"Jogador 2 ganha!\" << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/inferior_area.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1188\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  vector< vector<double> > v1;\n  double n, total=0;\n  string operation;\n\n  cin >> operation;\n\n  for (int i = 0; i < 12; i++) {\n    vector<double> v;\n\n    for (int j = 0; j < 12; j++) {\n      cin >> n;\n      v.push_back(n);\n    }\n\n    v1.push_back(v);\n  }\n\n  int counter1=5, counter2=7, count = 0;\n\n  for (int i = 7; i < 12; i++) {\n    for (int j = counter1; j < counter2; j++) {\n      total += v1[i][j];\n      count++;\n    }\n\n    counter1--;\n    counter2++;\n  }\n\n  if (operation == \"S\") cout << fixed << setprecision(1) << total << endl;\n  else cout << fixed << setprecision(1) << total / count << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/inside_out.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1235\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\tstring line;\n\t\n\tcin >> n;\n\tcin.ignore();\n\t\n\twhile (n--) {\n\t\tgetline(cin, line);\n\t\tint pos = line.size() / 2;\n\t\t\n\t\tstring new_line = \"\";\n\t\t\n\t\tfor (int i = pos-1; i >= 0; i--) new_line += line[i];\n\t\tfor (int i = line.size()-1; i >= pos; i--) new_line += line[i];\n\t\t\n\t\tcout << new_line << endl;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/international_chat.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1581\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\n  int num, n;\n  cin >> num;\n  string lang;\n\n  while (num--) {\n    cin >> n;\n    vector<string> languages;\n\n    for (int i = 0; i < n; i++) {\n      cin >> lang;\n      languages.push_back(lang);\n    }\n\n    string first_language = languages[0];\n    bool english = false;\n\n    for (int j = 1; j < languages.size(); j++) {\n      if (first_language != languages[j]) {\n        english = true;\n        break;\n      }\n    }\n\n    if (english) cout << \"ingles\" << endl;\n    else cout << first_language << endl;\n\n    languages.clear();\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/internship.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2533\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n  int M, N, C, sum_of_c, sum_of_nc;\n\n  while(cin >> M) {\n    sum_of_c = 0, sum_of_nc = 0;\n\n    while (M--) {\n      cin >> N >> C;\n      sum_of_nc += N * C;\n      sum_of_c += C;\n    }\n\n    cout << fixed << setprecision(4) << sum_of_nc / (sum_of_c * 100.00) << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/interval.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1037\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tdouble n;\n\n\tcin >> n;\n\n\t// [0,25] (25,50], (50,75], (75,100]\n\n\tif (n >= 0.0 && n < 25.0) {\n\t\tcout << \"Intervalo [0,25]\" << endl;\n\t} else if (n > 25.0 && n <= 50.0) {\n\t\tcout << \"Intervalo (25,50]\" << endl;\n\t} else if (n > 50.0 && n <= 75.0) {\n\t\tcout << \"Intervalo (50,75]\" << endl;\n\t} else if (n > 75.0 && n <= 100.0) {\n\t\tcout << \"Intervalo (75,100]\" << endl;\n\t} else {\n\t\tcout << \"Fora de intervalo\" << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/interval2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1072\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint in=0, out=0, n, x;\n\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> x;\n\n\t\tif (x >= 10 && x <= 20) {\n\t\t\tin++;\n\t\t} else {\n\t\t\tout++;\n\t\t}\n\t}\n\n\tcout << in << \" in\" << endl;\n\tcout << out << \" out\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/inverse_numbers.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1984\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\t\n\tstring numbers, inverse=\"\";\n\n\tcin >> numbers;\n\n\tint numbers_size = numbers.size();\n\n\tfor (int i = numbers_size-1; i >= 0; i--) inverse += numbers[i];\n\n\tcout << inverse << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/is_triangle.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1929\n\n#include <iostream>\n\nusing namespace std;\n\nint is_triangle(int a, int b, int c) {\n\tif ((a < b + c) && (b < a + c) && (c < a + b)) return 1;\n\telse return 0;\n}\n\nint main() {\n\t\n\tint a, b, c, d, triangle=0;\n\n\tcin >> a >> b >> c >> d;\n\n\tif (is_triangle(a, b, c) || is_triangle(a, b, d) || is_triangle(a, c, d) || is_triangle(b, c, d)) {\n\t\tcout << \"S\" << endl;\n\t} else {\n\t\tcout << \"N\" << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/jetiqui.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2587\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n  int N, index1 = -1, index2;\n  string word1, word2, word;\n\n  cin >> N;\n\n  while (N--) {\n    cin >> word1 >> word2 >> word;\n\n    for (int i = 0; i < word.size(); i++) {\n      if (word[i] == '_') {\n        if (index1 == -1) index1 = i;\n        else index2 = i;\n      }\n    }\n\n    if (word1[index1] == word2[index2] || word1[index2] == word2[index1]) cout << \"Y\" << endl;\n    else cout << \"N\" << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/jingle_composing.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1430\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\t\n\tstring val, id = \"WHQESTX\";\n\tvector<float> v;\n\n\tv.push_back(1.0);\n\tv.push_back(1.0/2);\n\tv.push_back(1.0/4);\n\tv.push_back(1.0/8);\n\tv.push_back(1.0/16);\n\tv.push_back(1.0/32);\n\tv.push_back(1.0/64);\n\n\twhile (cin >> val && val != \"*\") {\n\n\t\tint counter = 0;\n\t\tfloat duration = 0;\n\t\tint index;\n\n\t\tfor (int i = 0; i < val.size(); i++) {\t\t\t\n\t\t\tif (val[i] == '/') {\n\t\t\t\tif (duration == 1) counter++;\n\t\t\t\tduration = 0;\t\t\t\t\n\t\t\t} else {\n\t\t\t\tindex = id.find(val[i]);\n\t\t\t\tduration += v[index];\n\t\t\t}\n\t\t}\n\n\t\tcout << counter << endl;\n\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/jogatina_ufpa.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int N, I, UID, G, total;\n\n  while (cin >> N >> I) {\n    total = 0;\n    while (N--) {\n      cin >> UID >> G;\n      if (UID == I && G == 0) total++;\n    }\n\n    cout << total << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/jogo_da_boca.py",
    "content": "n = input()\nprint n % 3\n"
  },
  {
    "path": "competitive-programming/uri/jollo.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1321\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\n  int a, b, c, x, y;\n  cin >> a >> b >> c >> x >> y;\n  vector<int> prince;\n  vector<int> princess;\n\n  while (a + b + c + x + y != 0) {\n    princess.push_back(a);\n    princess.push_back(b);\n    princess.push_back(c);\n    prince.push_back(x);\n    prince.push_back(y);\n\n    sort(princess.begin(), princess.end());\n    sort(prince.begin(), prince.end());\n\n    int princess_smaller = princess[0];\n    int prince_smaller = prince[0];\n\n    if (prince_smaller < princess_smaller) cout << -1 << endl;\n    else {\n\n    }\n\n    cin >> a >> b >> c >> x >> y;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/joulupukki.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2025\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nvector<string> split(string s) {\n\tvector<string> words;\n\tstring word;\n\tint pos = 0;\n\n\tfor (int i = 0; i < s.size(); i++) {\n\t\tif (s[i] == ' ') {\n\t\t\tword = s.substr(pos, i-pos);\n\t\t\twords.push_back(word);\n\t\t\tpos = i+1;\n\t\t}\n\t}\n\t\n\tword = s.substr(pos, s.size()-pos);\n\twords.push_back(word);\n\n\treturn words;\n}\n\nstring transformWord(string word) {\n\tif (word.size() == 10) {\n\t\tif (word.substr(1, 8) == \"oulupukk\") return \"Joulupukki\";\n\t} else if (word.size() == 11) {\n\t\tif (word.substr(1, 8) == \"oulupukk\") return \"Joulupukki.\";\n\t}\n\n\treturn word;\n}\n\nint main() {\n\tint n;\n\tcin >> n;\n\tcin.ignore();\n\tstring s;\n\n\twhile (n--) {\n\t\tgetline(cin, s);\n\t\tvector<string> words = split(s);\n\t\t\n\t\tfor (int i = 0; i < words.size(); i++) {\n\t\t\tif (i < words.size()-1) cout << transformWord(words[i]) << \" \";\n\t\t\telse cout << transformWord(words[i]) << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/jumping_frog.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1961\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n, x, jump, before, after, win=1;\n\tcin >> jump >> n;\n\n\tcin >> x;\n\tbefore = x;\n\n\twhile (n--) {\n\n\t\tcin >> x;\n\t\tafter = x;\n\n\t\tif (after > before) {\n\t\t\tif (after - before > jump) {\t\t\t\n\t\t\t\twin = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tif (before - after > jump) {\n\t\t\t\twin = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tbefore = after;\n\t}\n\n\tif (win) cout << \"YOU WIN\" << endl;\n\telse cout << \"GAME OVER\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/just_in_time.cpp",
    "content": "#include <iostream>\n#include <cmath>\n\nusing namespace std;\n\nbool isPrimo(int n);\nint menorPrimo(int n);\n\nint main (void) {\n\tint N;\n\t\n\tcin >> N;\n\n\tcout << menorPrimo(N) << endl;\n\n\treturn 0;\n}\n\nbool isPrimo(int n) {\n\tif (n < 2) return false;\n\tif (n == 2) return true;\n\tif (n % 2 == 0) return false;\n\t\n\tint sq = sqrt(n) + 1;\t\n\n\tfor (int i = 3; i <= sq; i += 2) {\n\t\tif (n % i == 0) return false;\n\t}\n\n\treturn true;\n}\n\nint menorPrimo(int n) {\n\twhile (n >= 2) {\n\t\tif (isPrimo(n)) return n;\n\t\tn--;\n\t}\n\n\treturn n;\n}\n\n"
  },
  {
    "path": "competitive-programming/uri/justifier.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1273\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint get_greater_size(vector<string> &v) {\n  int max = 0;\n  for (int i = 0; i < v.size(); i++) if (v[i].size() > max) max = v[i].size();\n  return max;\n}\n\nstring concatenate_spaces(int n) {\n  string spaces = \"\";\n  while (n--) spaces += \" \";\n  return spaces;\n}\n\nint main() {\n\n  int n;\n  cin >> n;\n  string s, spaces;\n\n  while (n) {\n    vector<string> v;\n\n    while (n--) {\n      cin >> s;\n      v.push_back(s);\n    }\n\n    int greater_size = get_greater_size(v);\n\n    for (int i = 0; i < v.size(); i++) {\n      spaces = concatenate_spaces(greater_size - v[i].size());\n      v[i].insert(0, spaces);\n      cout << v[i] << endl;\n    }\n\n    cin >> n;\n\n    if (n) cout << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/justifier_2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1273\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint get_greater_size(vector<string> &v) {\n  int max = 0;\n  for (int i = 0; i < v.size(); i++) if (v[i].size() > max) max = v[i].size();\n  return max;\n}\n\nstring concatenate_spaces(int n) {\n  string spaces = \"\";\n  while (n--) spaces += \" \";\n  return spaces;\n}\n\nstring remove_first_spaces(string phrase) {\n\tstring phrase_without_first_spaces = \"\";\n\tbool can_assign = false;\n\tfor (int i = 0; i < phrase.size(); i++) {\n\t\tif (phrase[i] != ' ') can_assign = true;\n\t\tif (can_assign) phrase_without_first_spaces += phrase[i];\n\t}\n\t\n\treturn phrase_without_first_spaces;\n}\n\nstring remove_spaces(string phrase) {\n\tstring phrase_without_spaces = \"\";\n\tbool can_assign = false;\n\tfor (int i = 0; i < phrase.size(); i++) {\n\t\tif (phrase[i] != ' ') {\n\t\t\tif (can_assign) phrase_without_spaces += \" \";\n\t\t\tphrase_without_spaces += phrase[i];\n\t\t}\n\t\t\n\t\tif (phrase[i] == ' ') can_assign = true;\n\t\telse can_assign = false;\n\t}\n\t\n\treturn phrase_without_spaces;\n}\n\nint main() {\n\n  int n;\n  cin >> n;\n  string s, spaces;\n\n  while (n != 0) {\n    vector<string> v;\n\t  int counter = 1;\n\t  cin.ignore();\n\t\n    while (counter <= n) {\n      getline(cin, s);\n      s = remove_first_spaces(s);\n      s = remove_spaces(s);\n      v.push_back(s);\n      counter++;\n    }\n\n    int greater_size = get_greater_size(v);\n\n    for (int i = 0; i < v.size(); i++) {\n      spaces = concatenate_spaces(greater_size - v[i].size());\n      v[i].insert(0, spaces);\n      cout << v[i] << endl;\n    }\n\n    cin >> n;\n    if (n) cout << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/kage_bunshin_no_jutsu.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint jutsuNumber(long long int N) {\n  if (N <= 1) return 0;\n  return 1 + jutsuNumber(N / 2);\n}\n\nint main() {\n  long long int N;\n\n  while (cin >> N) {\n    cout << jutsuNumber(N) << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/kiloman.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1250\n\n#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nbool is_hit(vector<int> &v, string js, int ind) {\n\tif (js[ind] == 'S' && (v[ind] == 1 || v[ind] == 2)) return true;\n\tif (js[ind] == 'J' && v[ind] > 2) return true;\n\treturn false;\n}\n\nint main() {\n\t\n\tint n, x, temp;\n\tstring js;\n\tvector<int> v;\n\t\n\tcin >> n;\n\t\n\twhile (n--) {\n\t\tint counter = 0;\n\t\tcin >> x;\n\t\t\n\t\tfor (int i = 0; i < x; i++) {\n\t\t\tcin >> temp;\n\t\t\tv.push_back(temp);\n\t\t}\n\t\t\n\t\tcin >> js;\n\t\t\n\t\tfor (int ind = 0; ind < x; ind++) \n\t\t\tif (is_hit(v, js, ind)) counter++;\n\t\t\n\t\tcout << counter << endl;\n\t\t\n\t\tv.clear();\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/koch_snowflake.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1760\n\n#include <iostream>\n#include <math.h>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\t\n\tint l;\n\tdouble total;\n\t\n\twhile (cin >> l) {\n\t\ttotal = 8 * pow(l, 2) * (sqrt(3)) / 20;\n\t\tcout << fixed << setprecision(2) << total << endl;\n\t}\n\t\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/lap.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1708\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n1, n2;\n\n\twhile (cin >> n1 >> n2) {\n\t\tint t1=n1, t2=n2, counter=1;\n\t\twhile(true) {\n\t\t\tcounter++;\n\t\t\tt1 += n1;\n\t\t\tif (t1 <= t2) break;\n\t\t\tt2 += n2;\n\t\t}\n\n\t\tcout << counter << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/laser_sculpture.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1107\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\tvector<int> v;\n\tint n1, n2, x;\n\n\twhile (cin >> n1 >> n2 && n1 + n2 != 0) {\t\n\t\tfor (int i = 0; i < n2; i++) {\n\t\t\tcin >> x;\n\t\t\tv.push_back(n1-x);\n\t\t}\n\n\t\tint counter = v[0];\n\t\t\n\t\tfor (int i = 1; i < n2; i++) {\n\t\t\tif (v[i] > v[i-1]) counter += v[i] - v[i-1];\n\t\t}\n\n\t\tcout << counter << endl;\n\t\tv.clear();\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/last_analogimon.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int N, M, cityX, cityY, monsterX, monsterY, X, seconds;\n\n  while (cin >> N >> M) {\n    seconds = 0;\n\n    for (int i = 0; i < N; i++) {\n      for (int j = 0; j < M; j++) {\n        cin >> X;\n\n        if (X == 1) {\n          cityY = i;\n          cityX = j;\n        } else if (X == 2) {\n          monsterY = i;\n          monsterX = j;\n        }\n      }\n    }\n\n    if (cityX > monsterX) seconds += cityX - monsterX;\n    else seconds += monsterX - cityX;\n    if (cityY > monsterY) seconds += cityY - monsterY;\n    else seconds += monsterY - cityY;\n    cout << seconds << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/laundry.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1794\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, la, lb, sa, sb;\n\tcin >> n >> la >> lb >> sa >> sb;\n\n\tif (n >= la && n <= lb && n >= sa && n <= sb) cout << \"possivel\" << endl;\n\telse cout << \"impossivel\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/leaders_impeachment.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int N, X;\n  double total = 0.0, rule = 2.0 / 3.0;\n\n  while (cin >> N) {\n    while (N--) {\n      cin >> X;\n      total += X;\n    }\n\n    if (total / N >= rule) cout << \"impeachment\" << endl;\n    else cout << \"acusacao arquivada\" << endl;\n    total = 0.0;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/led.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1168\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n;\n\tstring x;\n\tcin >> n;\n\n\tint ar[10] = { 6, 2, 5, 4, 5, 6, 3, 7, 6 };\n\n\twhile (n--) {\n\n\t\tcin >> x;\n\t\tint total = 0;\n\n\t\tfor (int i = 0; i < x.size(); i++) {\n\t\t\tint num = (int)x[i];\n\t\t\ttotal += ar[num];\n\t\t}\n\n\t\tcout << total << \" leds\" << endl;\n\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/left_area.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1188\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  vector< vector<double> > v1;\n  double n, total=0;\n  string operation;\n\n  cin >> operation;\n\n  for (int i = 0; i < 12; i++) {\n    vector<double> v;\n\n    for (int j = 0; j < 12; j++) {\n      cin >> n;\n      v.push_back(n);\n    }\n\n    v1.push_back(v);\n  }\n\n  int counter1=1, count = 0;\n\n  for (int i = 1; i < 11; i++) {\n    for (int j = 0; j < counter1; j++) {\n      total += v1[i][j];\n      count++;\n    }\n\n    if (i < 5) counter1++;\n    else if (i > 5) counter1--;\n  }\n\n  if (operation == \"S\") cout << fixed << setprecision(1) << total << endl;\n  else cout << fixed << setprecision(1) << total / count << endl;\n\n  return 0;\n}"
  },
  {
    "path": "competitive-programming/uri/libertadores_1.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1536\n\n#include <iostream>\n#include <vector>\n#include <map>\n#include <string>\n\nusing namespace std;\n\nvector<string> parse_string(string line) {\n\tvector<string> v;\n\tstring word = \"\";\n\t\n\tfor (int i = 0; i < line.size(); i++) {\n\t\tif (line[i] == ' ') {\n\t\t\tv.push_back(word);\n\t\t\tword.clear();\n\t\t} else if (i == line.size() - 1) {\n\t\t\tword += line[i];\n\t\t\tv.push_back(word);\n\t\t\tword.clear();\n\t\t} else {\n\t\t\tword += line[i];\n\t\t}\n\t}\n\t\n\treturn v;\n}\n\nint to_digit(char digit) {\n  return digit - '0';\n}\n\nint string_to_number(string n) {\n  if (n == \"\") {\n    return -1;\n  } else {\n    int num = 0;\n\n    for (int i = 0; i < n.size(); i++) {\n      num = num * 10 + to_digit(n[i]);\n    }\n\n    return num;\n  }\n}\n\nstruct team {\n\tint points;\n\tint goals_difference;\n\tint goals_away;\n};\n\nint main() {\n\t\n\tvector<string> matches;\n\tint n;\n\tcin >> n;\n\tcin.ignore();\n\tstring match;\n\t\n\twhile (n--) {\n\t\tteam team1, team2;\n\t\tteam1.points = 0;\n\t\tteam1.goals_difference = 0;\n\t\tteam1.goals_away = 0;\n\t\tteam2.points = 0;\n\t\tteam2.goals_difference = 0;\n\t\tteam2.goals_away = 0;\n\t\t\n\t\tgetline(cin, match);\n\t\tmatches = parse_string(match);\n\t\tint goals1 = string_to_number(matches.front());\n\t\tint goals2 = string_to_number(matches.back());\n\t\tif (goals1 > goals2) team1.points += 3;\n\t\telse if (goals1 < goals2) team2.points += 3;\n\t\telse {\n\t\t\tteam1.points += 1;\n\t\t\tteam2.points += 1;\n\t\t}\n\t\tteam1.goals_difference += goals1;\n\t\tteam2.goals_difference += goals2;\n\t\tteam2.goals_away += goals2;\n\t\t\n\t\tgetline(cin, match);\n\t\tmatches = parse_string(match);\n\t\tgoals1 = string_to_number(matches.front());\n\t\tgoals2 = string_to_number(matches.back());\n\t\tif (goals1 > goals2) team2.points += 3;\n\t\telse if (goals1 < goals2) team2.points += 3;\n\t\telse {\n\t\t\tteam1.points += 1;\n\t\t\tteam2.points += 1;\n\t\t}\n\t\tteam2.goals_difference += goals1;\n\t\tteam1.goals_difference += goals2;\n\t\tteam1.goals_away += goals2;\n\t\t\n\t\tif (team1.points > team2.points) cout << \"Time 1\" << endl;\n\t\telse if (team2.points > team1.points) cout << \"Time 2\" << endl;\n\t\telse if (team1.goals_difference > team2.goals_difference) cout << \"Time 1\" << endl;\n\t\telse if (team1.goals_difference < team2.goals_difference) cout << \"Time 2\" << endl;\n\t\telse if (team1.goals_away > team2.goals_away) cout << \"Time 1\" << endl;\n\t\telse if (team1.goals_away < team2.goals_away) cout << \"Time 2\" << endl;\n\t\telse cout << \"Penaltis\" << endl;\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/libertadores_2.cpp",
    "content": "#include <iostream>\n#include <algorithm>\n#include <cstdio>\nusing namespace std;\n\nint main() {\n\tint T;\n\tcin>>T;\n\twhile(T--) {\n\t\tint ga=0, gb=0, va=0, vb=0, gaw=0, gbw=0;\n\t\tint a, b;\n\t\tscanf(\"%d x %d\", &a, &b);\n\t\tif(a>b) va++;\n\t\tif(b>a) vb++;\n\t\tga += a;\n\t\tgb += b;\n\t\tgbw = b;\n\t\tscanf(\"%d x %d\", &b, &a);\n\t\tif(a>b) va++;\n\t\tif(b>a) vb++;\n\t\tga += a;\n\t\tgb += b;\n\t\tgaw = a;\n\t\tif(va > vb) cout<<\"Time 1\\n\";\n\t\telse if(vb > va) cout<<\"Time 2\\n\";\n\t\telse if(ga > gb) cout<<\"Time 1\\n\";\n\t\telse if(gb > ga) cout<<\"Time 2\\n\";\n\t\telse if(gaw > gbw) cout<<\"Time 1\\n\";\n\t\telse if(gbw > gaw) cout<<\"Time 2\\n\";\n\t\telse cout<<\"Penaltis\\n\";\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/line_in_array.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1181\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n\tint line;\n\tdouble n;\n\tcin >> line;\n\n\tstring t;\n\tcin >> t;\n\n\tvector< vector<double> > v1;\t\n\n\tfor (int i = 0; i < 12; i++) {\n\t\tvector<double> v2;\n\n\t\tfor (int j = 0; j < 12; j++) {\n\t\t\tcin >> n;\n\t\t\tv2.push_back(n);\n\t\t}\n\n\t\tv1.push_back(v2);\n\t}\n\n\tif (t == \"S\") {\n\t\tdouble sum = 0;\n\t\tfor (int i = 0; i < 12; i++) sum += v1[line][i];\n\t\tcout << fixed << setprecision(1) << sum << endl;\n\t} else if (t == \"M\") {\n\t\tdouble average = 0;\n\t\tfor (int i = 0; i < 12; i++) average += v1[line][i];\n\t\tcout << fixed << setprecision(1) << average / 12 << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/linear_parking_lot.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1523\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nstruct car {\n  int arrive;\n  int left;\n};\n\nint main() {\n  int N, K, arrive, left;\n  bool can;\n  cin >> N >> K;\n\n  while (N + K != 0)   {\n    vector<car> parking_lot;\n    can = true;\n\n    while (N--) {\n      cin >> arrive >> left;\n      car c;\n      c.arrive = arrive;\n      c.left = left;\n\n      while (parking_lot.size() > 0 && parking_lot.back().left <= arrive) parking_lot.pop_back();\n\n      if ((parking_lot.size() >= K && c.arrive < parking_lot.back().left) || parking_lot.size() > 0 && c.left > parking_lot.back().left) {\n        can = false;\n      } else {\n        parking_lot.push_back(c);\n      }\n    }\n\n    if (can) cout << \"Sim\" << endl;\n    else cout << \"Nao\" << endl;\n\n    cin >> N >> K;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/little_ant.cpp",
    "content": "#include <iostream>\n \nusing namespace std;\n \nint main() {\n    int n;\n    long long int x;\n    \n    cin >> n;\n    \n    while (n--) {\n        cin >> x;\n        cout << (x+1) / 2 << endl;\n    }\n \n    return 0;\n}"
  },
  {
    "path": "competitive-programming/uri/little_ducks.py",
    "content": "# https://www.urionlinejudge.com.br/judge/en/problems/view/2334\n\nn = int(raw_input())\n\nwhile n != -1:\n    if n == 0:\n        print(0)\n    else:\n        print(n - 1)\n\n    n = int(raw_input())\n"
  },
  {
    "path": "competitive-programming/uri/logical_sequence.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1144\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n, i=1;\n\tint count1=1, count2=1, count3=1;\n\tint x1=1, x2=2;\n\tint y1=1, y2=1, y3=1, y4=2;\n\n\tcin >> n;\n\n\tn *= 2;\n\n\twhile (n--) {\n\t\tcout << i << \" \" << x1 << \" \" << y1 << endl;\n\n\t\tif (count1 % 2 == 0) {\n\t\t\ti++;\n\t\t}\n\n\t\tif (count2 % 2 == 0) {\t\t\t\n\t\t\tx1 += x2;\n\t\t\tx2 += 2;\n\t\t} else {\n\t\t\tx1++;\n\t\t}\n\n\t\tif (count3 % 2 == 0) {\t\t\t\n\t\t\ty2 = 6 * y3;\n\t\t\ty1 += y2;\n\t\t\ty3 += y4;\t\t\t\n\t\t\ty4++;\n\t\t} else {\n\t\t\ty1++;\n\t\t}\n\n\t\tcount1++;\n\t\tcount2++;\n\t\tcount3++;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/logical_sequence_2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1145\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n1, n2;\n\n\tcin >> n1 >> n2;\n\n\tfor (int i = 1; i <= n2; i++) {\n\t\tcout << i;\n\t\tif (i % n1 == 0) cout << endl;\n\t\telse cout << \" \";\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/lost_boots.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1245\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\t\n\twhile (cin >> n) {\n\t\tmap<int, map<string, int> > boots;\n\t\tint num;\n\t\tstring side;\n\t\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> num >> side;\n\t\t\t\n\t\t\tif (boots.find(num) == boots.end()) {\n\t\t\t\tmap<string, int> sides;\n\t\t\t\tsides[side] = 1;\n\t\t\t\tboots[num] = sides;\n\t\t\t} else {\n\t\t\t\tif (boots[num].find(side) == boots[num].end()) {\n\t\t\t\t\tboots[num][side] = 1;\n\t\t\t\t} else {\n\t\t\t\t\tboots[num][side]++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tint counter = 0;\n\t\t\n\t\tfor (map<int, map<string, int> >::iterator it = boots.begin(); it != boots.end(); it++) {\n\t\t\tif (it->second[\"D\"] < it->second[\"E\"]) counter += it->second[\"D\"];\n\t\t\telse counter += it->second[\"E\"];\n\t\t}\n\t\t\n\t\tcout << counter << endl;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/lowest_number_and_position.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1180\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n, position, lowest=1001, x;\n\tcin >> n;\n\n\tfor (int i = 0; i < n; i++) {\n\n\t\tcin >> x;\n\n\t\tif (x < lowest) {\n\t\t\tlowest = x;\n\t\t\tposition = i;\n\t\t}\n\n\t}\n\n\tcout << \"Menor valor: \" << lowest << endl;\n\tcout << \"Posicao: \" << position << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/lu_di_oh.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2542\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n  int N, M, L, X, m_choice, l_choice;\n\n  while (cin >> N) {\n    vector< vector<int> > m_cards;\n    vector< vector<int> > l_cards;\n    cin >> M >> L;\n\n    while (M--) {\n      vector<int> card;\n      for (int i = 0; i < N; i++) {\n        cin >> X;\n        card.push_back(X);\n      }\n\n      m_cards.push_back(card);\n    }\n\n    while (L--) {\n      vector<int> card;\n      for (int i = 0; i < N; i++) {\n        cin >> X;\n        card.push_back(X);\n      }\n\n      l_cards.push_back(card);\n    }\n\n    cin >> m_choice >> l_choice >> X;\n\n    if (m_cards[m_choice-1][X-1] > l_cards[l_choice-1][X-1]) cout << \"Marcos\" << endl;\n    else if (m_cards[m_choice-1][X-1] < l_cards[l_choice-1][X-1]) cout << \"Leonardo\" << endl;\n    else cout << \"Empate\" << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/lucro.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/1310\n\n#include <iostream>\n\nusing namespace std;\n\nint max(int a, int b) {\n  return (a > b)? a : b;\n}\n\nint main() {\n  int N, C, pricePerDay;\n\n  while (cin >> N >> pricePerDay) {\n    int revenue[N+1];\n    revenue[0] = 0;\n\n    for (int i = 1; i <= N; i++) {\n      cin >> C;\n      revenue[i] = C;\n    }\n\n    int dp[N+1][N+1];\n\n    for (int i = 0; i < N+1; i++) {\n      for (int j = 0; j < N+1; j++) {\n        if (i != 0 && i == j) dp[i][j] = revenue[i] - pricePerDay;\n        else dp[i][j] = 0;\n      }\n    }\n\n    for (int i = 1; i < N+1; i++) {\n      for (int j = i+1; j < N+1; j++) {\n        if (dp[i][j] == 0) dp[i][j] = dp[i][j-1] + dp[j][j];\n      }\n    }\n\n    int greater = 0;\n\n    for (int i = 1; i < N+1; i++) {\n      for (int j = i; j < N+1; j++) {\n        greater = max(dp[i][j], greater);\n      }\n    }\n\n    cout << greater << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/lucro_otimizado.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/1310\n\n#include <iostream>\n\nusing namespace std;\n\nint max(int a, int b) {\n  return (a > b)? a : b;\n}\n\nint main() {\n  int N, C, pricePerDay;\n\n  while (cin >> N >> pricePerDay) {\n    int dp[N+1][N+1] = {};\n\n    for (int i = 1; i <= N; i++) {\n      cin >> C;\n      dp[i][i] = C - pricePerDay;\n    }\n\n    for (int i = 1; i < N+1; i++) {\n      for (int j = i+1; j < N+1; j++) {\n        if (dp[i][j] == 0) dp[i][j] = dp[i][j-1] + dp[j][j];\n      }\n    }\n\n    int greater = 0;\n\n    for (int i = 1; i < N+1; i++) {\n      for (int j = i; j < N+1; j++) {\n        greater = max(dp[i][j], greater);\n      }\n    }\n\n    cout << greater << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/macpronalts.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1985\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\ndouble total_price(int code, int number) {\n\n  double total;\n\n  if (code == 1001) total = number * 1.5;\n  else if (code == 1002) total = number * 2.5;\n  else if (code == 1003) total = number * 3.5;\n  else if (code == 1004) total = number * 4.5;\n  else if (code == 1005) total = number * 5.5;\n\n  return total;\n}\n\nint main() {\n\n  int n, code, number;\n  double total=0;\n\n  cin >> n;\n\n  while (n--) {\n    cin >> code >> number;\n    total += total_price(code, number);\n  }\n\n  cout << fixed << setprecision(2) << total << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/maesters_map.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1855\n\n#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n\tint n1, n2, i=0, j=0, found=0, direction=0;\n\tcin >> n2 >> n1;\n\n\tvector<string> v;\n\tstring x;\n\n\tfor (int i = 0; i < n1; i++) {\n\t\tcin >> x;\n\t\tv.push_back(x);\n\t}\n\n\tif (v[i][j] != '.') {\n\n\t\twhile (true) {\n\n\t\t\tif (v[i][j] == '*') {\n\t\t\t\tfound = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (v[i][j] == 'X') break;\n\n\t\t\tif (v[i][j] == '>') {\n\t\t\t\tdirection = 1;\n\t\t\t\tv[i][j] = 'X';\n\t\t\t} else if (v[i][j] == 'v') {\n\t\t\t\tdirection = 2;\n\t\t\t\tv[i][j] = 'X';\n\t\t\t} else if (v[i][j] == '<') {\n\t\t\t\tdirection = 3;\n\t\t\t\tv[i][j] = 'X';\n\t\t\t} else if (v[i][j] == '^') {\n\t\t\t\tdirection = 4;\n\t\t\t\tv[i][j] = 'X';\n\t\t\t} else {\n\t\t\t\tv[i][j] = 'X';\n\t\t\t}\n\n\t\t\tif (direction == 1) {\n\t\t\t\tj++;\n\t\t\t} else if (direction == 2) {\n\t\t\t\ti++;\n\t\t\t} else if (direction == 3) {\n\t\t\t\tj--;\n\t\t\t} else if (direction == 4) {\n\t\t\t\ti--;\n\t\t\t}\n\n\t\t}\n\t}\n\n\tif (found) cout << \"*\" << endl;\n\telse cout << \"!\" << endl;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/mean_median_problem.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1379\n\n#include <iostream>\n#include <cmath>\n\nusing namespace std;\n\nint is_integer(double n) {\n\tif (floor(n) == n) return 1;\n\telse return 0;\n}\n\nint main() {\n\n\tunsigned long long int n1, n2;\n\tlong long int n3;\n\tcin >> n1 >> n2;\n\n\twhile (n1 + n2 != 0) {\n\t\tunsigned long long int mean, median;\n\t\tint found = 0;\n\n\t\tif (n1 < n2) median = n1;\n\t\telse median = n2;\n\n\t\tif (is_integer(median * 3 - n1 - n2)) {\n\t\t\tn3 = median * 3 - n1 - n2;\n\t\t\tfound = 1;\n\t\t}\n\n\t\tcout << n3 << endl;\n\t\tcin >> n1 >> n2;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/medal_table.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2312\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n\nusing namespace std;\n\nstruct country {\n\tstring name;\n\tint gold;\n\tint silver;\n\tint bronze;\n};\n\nbool compareByMedals(const country &c1, const country &c2) {\n\tif (c1.gold > c2.gold) return true;\n\telse if (c1.gold == c2.gold) {\n\t\tif (c1.silver > c2.silver) return true;\n\t\telse if (c1.silver == c2.silver) {\n\t\t\tif (c1.bronze > c2.bronze) return true;\n\t\t\telse if (c1.bronze == c2.bronze) return c1.name < c2.name;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nint main() {\n\tstring country_name;\n\tint n, gold, silver, bronze;\n\tcin >> n;\n\n\tvector<country> countries;\n\n\twhile (n--) {\n\t\tcin >> country_name >> gold >> silver >> bronze;\n\t\tcountry c;\n\t\tc.name = country_name;\n\t\tc.gold = gold;\n\t\tc.silver = silver;\n\t\tc.bronze = bronze;\n\t\tcountries.push_back(c);\n\t}\n\n\tsort(countries.begin(), countries.end(), compareByMedals);\n\n\tfor (int i = 0; i < countries.size(); i++) {\n\t\tcout << countries[i].name << \" \" << countries[i].gold << \" \" << countries[i].silver << \" \" << countries[i].bronze << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/merry_christmaaaas.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2483\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nstring happiness_index(int index) {\n  string result = \"\";\n  while (index--) result += \"a\";\n  return result;\n}\n\nint main() {\n  cout << \"Feliz nat\";\n  int index;\n  cin >> index;\n  cout << happiness_index(index);\n  cout << \"l!\" << endl;\n}\n"
  },
  {
    "path": "competitive-programming/uri/mirror_sequence.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2157\n\n#include <iostream>\n#include <string>\n#include <sstream>\n\nusing namespace std;\n\nstring toString(int n) {\n\tstringstream ss;\n\tss << n;\n\treturn ss.str();\n}\n\nstring reverseString(string s) {\n\tstring reversedString = \"\";\n\tfor (int i = s.size()-1; i >= 0; i--) reversedString += s[i];\n\treturn reversedString;\n}\n\nint main() {\n\tint n, min, max;\n\tstring n1, n2, result, numbers = \"0123456789\";\n\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> min >> max;\n\t\tresult = \"\";\n\n\t\tfor (int i = min; i <= max; i++) {\n\t\t\tresult += toString(i);\n\t\t}\n\n\t\tresult += reverseString(result);\n\n\t\tcout << result << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/mjolnir.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1865\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n  string hero;\n  int n, force;\n\n  cin >> n;\n\n  while (n--) {\n\n    cin >> hero >> force;\n\n    if (hero == \"Thor\") cout << \"Y\" << endl;\n    else cout << \"N\" << endl;\n\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/monetary_formatting.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1309\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nbool under_ten(string cents) {\n\tif (cents == \"0\" || cents == \"1\" || cents == \"2\" || cents == \"3\" || cents == \"4\" || cents == \"5\" || cents == \"6\" || cents == \"7\" || cents == \"8\" || cents == \"9\") return true;\n\treturn false;\n}\n\nstring reverse_string(string s) {\n\tstring result_string = \"\";\n\tfor (int i = s.size()-1; i >= 0; i--) result_string += s[i];\n\treturn result_string;\n}\n\nstring parse_string(string s, string cents) {\n\tstring new_s = \"\";\n\tnew_s += cents[1];\n\tnew_s += cents[0];\n\tnew_s += \".\";\n\t\n\tint comma = 1;\n\t\n\tfor (int i = s.size()-1; i >= 0; i--) {\n\t\tnew_s += s[i];\n\t\tif (comma == 3 && i != 0) {\n\t\t\tnew_s += \",\";\n\t\t\tcomma = 1;\n\t\t} else {\n\t\t\tcomma++;\n\t\t}\n\t}\n\t\n\tnew_s += \"$\";\n\tnew_s = reverse_string(new_s);\n\treturn new_s;\n}\n\nint main() {\n\n\tstring money, cents;\n\t\n\twhile (cin >> money) {\n\t\tcin >> cents;\n\t\tif (under_ten(cents)) cents = \"0\" + cents;\n\n\t\tint money_size = money.size();\n\t\tstring real_money = parse_string(money, cents);\n\t\tcout << real_money << endl;\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/montanha_russa.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int N, min, max, X, total;\n\n  while (cin >> N >> min >> max) {\n    total = 0;\n    while (N--) {\n      cin >> X;\n      if (X >= min && X <= max) total++;\n    }\n\n    cout << total << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/month.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1052\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\n\tvector<string> v;\n\n\tv.push_back(\"January\");\n\tv.push_back(\"February\");\n\tv.push_back(\"March\");\n\tv.push_back(\"April\");\n\tv.push_back(\"May\");\n\tv.push_back(\"June\");\n\tv.push_back(\"July\");\n\tv.push_back(\"August\");\n\tv.push_back(\"September\");\n\tv.push_back(\"October\");\n\tv.push_back(\"November\");\n\tv.push_back(\"December\");\n\n\tint n;\n\n\tcin >> n;\n\n\tcout << v[n-1] << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/moon_phases.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1893\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int n1, n2;\n\n  cin >> n1 >> n2;\n\n  if (n2 >= 97 && n2 <= 100) cout << \"cheia\" << endl;\n  else if (n2 >= 0 && n2 <= 2) cout << \"nova\" << endl;\n  else if (n1 < n2) cout << \"crescente\" << endl;\n  else cout << \"minguante\" << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/morse.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2338\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nvoid createMorseTable(map<string, string> &morse) {\n  morse[\".-\"] = \"a\";\n  morse[\"-...\"] = \"b\";\n  morse[\"-.-.\"] = \"c\";\n  morse[\"-..\"] = \"d\";\n  morse[\".\"] = \"e\";\n  morse[\"..-.\"] = \"f\";\n  morse[\"--.\"] = \"g\";\n  morse[\"....\"] = \"h\";\n  morse[\"..\"] = \"i\";\n  morse[\".---\"] = \"j\";\n  morse[\"-.-\"] = \"k\";\n  morse[\".-..\"] = \"l\";\n  morse[\"--\"] = \"m\";\n  morse[\"-.\"] = \"n\";\n  morse[\"---\"] = \"o\";\n  morse[\".--.\"] = \"p\";\n  morse[\"--.-\"] = \"q\";\n  morse[\".-.\"] = \"r\";\n  morse[\"...\"] = \"s\";\n  morse[\"-\"] = \"t\";\n  morse[\"..-\"] = \"u\";\n  morse[\"...-\"] = \"v\";\n  morse[\".--\"] = \"w\";\n  morse[\"-..-\"] = \"x\";\n  morse[\"-.--\"] = \"y\";\n  morse[\"--..\"] = \"z\";\n}\n\nstring buildCode(string partial, int j) {\n  if (partial.find(\"...\") != string::npos) {\n    return morse[substr(j, partial.find(\"...\"))];\n  }\n\n  return morse[substr(partial.find(\"...\")+3, partial.size()-partial.find(\"...\")+3)];\n}\n\nint main() {\n  int N, i, j;\n  string s, result, partial;\n\n  while (N--) {\n    map<string, string> morse;\n\t  createMorseTable(morse);\n    cin >> s;\n    result = \"\";\n    i = 0, j = 0;\n\n    while (i < s.size()) {\n      if (s.find(\".......\") != string::npos) {\n        while (j < s.size()) {\n          partial = substr(i, s.find(\".......\"));\n          result += buildCode(partial, j);\n          j = partial.find(\"...\")+3;\n        }\n      } else {\n        while (j < s.size()) {\n          partial = substr(i, s.size()-s.find(\".......\")+7);\n          result += buildCode(partial, j);\n          j = partial.find(\"...\")+3;\n        }\n      }\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/motoboy.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/1286\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint max(int a, int b) {\n  return a > b? a : b;\n}\n\nstruct Obj {\n  int time, pizza;\n};\n\nbool sortByPizza(Obj obj1, Obj obj2) {\n  if (obj1.pizza < obj2.pizza) return true;\n  else if (obj1.pizza > obj2.pizza) return false;\n  else return obj1.time < obj2.time;\n}\n\nint main() {\n  int N, P, time, pizza;\n\n  while (cin >> N && N) {\n    vector<Obj> objects;\n    cin >> P;\n\n    for (int i = 0; i < N; i++) {\n      cin >> time >> pizza;\n      Obj object;\n      object.time = time;\n      object.pizza = pizza;\n      objects.push_back(object);\n    }\n\n    sort(objects.begin(), objects.end(), sortByPizza);\n\n    int dp[N][P+1];\n\n    for (int i = 0; i <= P; i++) {\n      if (objects[0].pizza <= i) dp[0][i] = objects[0].time;\n      else dp[0][i] = 0;\n    }\n\n    for (int i = 1; i < N; i++) {\n      for (int j = 0; j < P; j++) {\n        if (j - objects[i].pizza >= 0) dp[i][j] = max(dp[i-1][j - objects[i].pizza] + objects[i].time, dp[i-1][j]);\n        else dp[i][j] = dp[i-1][j];\n      }\n    }\n\n    cout << dp[N-1][P-1] << \" min.\"<< endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/multiple_of_13.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1132\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint x, y, total=0;\n\n\tcin >> x >> y;\n\n\tif (x < y) {\n\t\tfor (int i = x; i <= y; i++) {\n\t\t\tif (i % 13 != 0) {\n\t\t\t\ttotal += i;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor (int i = y; i <= x; i++) {\n\t\t\tif (i % 13 != 0) {\n\t\t\t\ttotal += i;\n\t\t\t}\n\t\t}\n\t}\n\n\tcout << total << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/multiple_reading.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1262\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\tstring process;\n\t\n\twhile (cin >> process) {\n\t\tcin >> n;\n\t\tint counter = 0;\n\t\tint number_of_rs = 0;\n\t\t\n\t\tfor (int i = 0; i < process.size(); i++) {\n\t\t\tif (process[i] == 'W') {\n\t\t\t\tcounter++;\n\t\t\t\tnumber_of_rs = 0;\n\t\t\t} else {\n\t\t\t\tif (number_of_rs == 0) counter++;\n\t\t\t\tnumber_of_rs++;\n\t\t\t}\n\t\t\t\n\t\t\tif (number_of_rs >= n) number_of_rs = 0;\n\t\t}\n\t\n\t\tcout << counter << endl;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/multiples.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1044\n\n#include <iostream>\n\nusing namespace std;\n\nint is_multiple(int n1, int n2) {\n\n\tif (n1 > n2) {\n\t\tif (n1 % n2 == 0) return 1;\n\t\telse return 0;\n\t} else if (n2 > n1) {\n\t\tif (n2 % n1 == 0) return 1;\n\t\telse return 0;\n\t}\n\n\treturn 1;\n}\n\nint main() {\n\n\tint n1, n2;\n\n\tcin >> n1 >> n2;\n\n\tif (is_multiple(n1, n2)) {\n\t\tcout << \"Sao Multiplos\" << endl;\n\t}\telse {\n\t\tcout << \"Nao sao Multiplos\" << endl;\n\t}\t\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/multiplication_table.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1078\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n;\n\n\tcin >> n;\n\n\tfor (int i = 1; i <= 10; i++) {\n\t\tcout << i << \" x \" << n << \" = \" << n * i << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/musical_loop.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1089\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, picos=0, temp;\n\tvector<int>\tloop;\n\n\tcin >> n;\n\n\twhile (n != 0) {\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> temp;\n\t\t\tloop.push_back(temp);\n\t\t}\n\n\t\tloop.push_back(loop[0]);\n\t\tloop.push_back(loop[1]);\n\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tif ((loop[i] > loop[i-1] && loop[i] > loop[i+1]) || (loop[i] < loop[i-1] && loop[i] < loop[i+1])) picos++;\n\t\t}\n\n\t\tcout << picos << endl;\n\n\t\tpicos = 0;\n\t\tloop.clear();\n\t\tcin >> n;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/name_at_form.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2160\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\tstring phrase;\n\tgetline(cin, phrase);\n\tif (phrase.size() <= 80) cout << \"YES\" << endl;\n\telse cout << \"NO\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/natural_sum.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1805\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tunsigned long long int n1, n2, total;\n\n\tcin >> n1 >> n2;\n\n\ttotal = (n1 + n2) * (n2 - n1 + 1) / 2;\n\n\tcout << total << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/new_record.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2551\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int N;\n  double best, time, distance;\n\n  while (cin >> N) {\n    best = 0;\n\n    for (int i = 1; i <= N; i++) {\n      cin >> time >> distance;\n\n      if (distance / time > best) {\n        best = distance / time;\n        cout << i << endl;\n      }\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/nine.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2217\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\tint n;\n\tlong long int num;\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> num;\n\t\tif (num % 2 == 0) cout << 1 << endl;\n\t\telse cout << 9 << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/number_frequence.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1171\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint get_position(vector< pair<int, int> >& v, int el) {\n  for (int i = 0; i < v.size(); i++) if (el == v[i].first) return i;\n  return v.size();\n}\n\nint main() {\n\n  int n, x;\n  cin >> n;\n\n  vector< pair<int, int> > v;\n  cin >> x;\n  v.push_back(make_pair(x, 1));\n  n--;\n\n  while (n--) {\n    cin >> x;    \n    if (get_position(v, x) < v.size()) v[get_position(v, x)].second++;\n    else v.push_back(make_pair(x, 1));    \n  }\n\n  sort(v.begin(), v.end());\n\n  for (int i = 0; i < v.size(); i++) cout << v[i].first << \" aparece \" << v[i].second << \" vez(es)\" << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/obi_uri.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2062\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n;\n\tcin >> n;\n\tstring s, ns;\n\tvector<string> v;\n\n\twhile (n--) {\n\t\tcin >> s;\n\t\tv.push_back(s);\n\t}\n\n\tvector<string> v1;\n\n\tfor (int i = 0; i < v.size(); i++) {\n\t\tif (v[i].size() == 3) {\n\t\t\tif (v[i].substr(0, 2) == \"UR\") v1.push_back(\"URI\");\n\t\t\telse if (v[i].substr(0, 2) == \"OB\") v1.push_back(\"OBI\");\n\t\t\telse v1.push_back(v[i]);\n\t\t} else {\n\t\t\tv1.push_back(v[i]);\n\t\t}\n\t}\n\n\tfor (int i = 0; i < v1.size(); i++) {\n\t\tif (i == v1.size()-1) cout << v1[i];\n\t\telse cout << v1[i] << \" \";\n\t}\n\n\tcout << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/odd_numbers.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1067\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\tcin >> n;\n\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (i % 2 != 0) cout << i << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/og.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1387\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n1, n2;\n\tcin >> n1 >> n2;\n\n\twhile (n1 + n2 != 0) {\n\t\tcout << n1 + n2 << endl;\n\t\tcin >> n1 >> n2;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/one_two_three.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1332\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint verify_num(string num, string number, int n) {\n  int total = num.size(), sum = 0;\n  for (int j = 0; j < num.size(); j++) if (num[j] == number[j]) sum++;\n  if (sum + 1 >= total) return n;\n  return -1;\n}\n\nint main() {\n\n  int n;\n  cin >> n;\n\n  string number;\n  vector<string> numbers;\n  numbers.push_back(\"one\");\n  numbers.push_back(\"two\");\n  numbers.push_back(\"three\");\n\n  while (n--) {\n    cin >> number;\n    for (int i = 0; i < 3; i++) {\n      int result = verify_num(numbers[i], number, i+1);\n      if (result != -1) {\n        cout << result << endl;\n        break;\n      }\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/operator_game.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2493\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nstruct operation {\n  int first_operator;\n  int second_operator;\n  int result;\n};\n\nbool is_result_correct(const operation &op, string oper) {\n  bool sum_correct = op.first_operator + op.second_operator == op.result,\n       subtraction_correct = op.first_operator - op.second_operator == op.result,\n       multiplication_correct = op.first_operator * op.second_operator == op.result;\n\n  return (oper == \"+\" && sum_correct ||\n          oper == \"-\" && subtraction_correct ||\n          oper == \"*\" && multiplication_correct ||\n          oper == \"I\" && !sum_correct && !subtraction_correct && !multiplication_correct);\n}\n\nint main() {\n  int N, first_operator, second_operator, result, ID;\n  char useless;\n  string name, oper;\n\n  while (cin >> N) {\n    vector<operation> operations;\n    vector<string> people;\n\n    for (int i = 0; i < N; i++) {\n      cin >> first_operator >> second_operator >> useless >> result;\n      operation op;\n      op.first_operator = first_operator;\n      op.second_operator = second_operator;\n      op.result = result;\n      operations.push_back(op);\n    }\n\n    for (int i = 0; i < N; i++) {\n      cin >> name >> ID >> oper;\n      if (!is_result_correct(operations[ID-1], oper)) people.push_back(name);\n    }\n\n    if (people.size() == N) {\n      cout << \"None Shall Pass!\" << endl;\n    } else if (people.size() > 0) {\n      sort(people.begin(), people.end());\n      cout << people[0];\n      for (int i = 1; i < people.size(); i++) cout << \" \" << people[i];\n      cout << endl;\n    } else {\n      cout << \"You Shall All Pass!\" << endl;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/optical_reader.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1129\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, counter=0, num, result;\n\tstring results = \"ABCDE\";\n\tcin >> n;\n\n\twhile (n != 0) {\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tfor (int i = 0; i < 5; i++) {\n\t\t\t\tcin >> num;\n\t\t\t\tif (num <= 127) {\n\t\t\t\t\tcounter++;\n\t\t\t\t\tresult = i;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (counter != 1) cout << \"*\" << endl;\n\t\t\telse cout << results[result] << endl;\n\n\t\t\tcounter = 0;\n\t\t}\t\t\n\n\t\tcin >> n;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/our_days_are_never_coming_back.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1864\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\tcin >> n;\n\n\tstring text = \"LIFE IS NOT A PROBLEM TO BE SOLVED\";\n\tstring final = \"\";\n\n\tfor (int i = 0; i < n; i++) final += text[i];\n\n\tcout << final << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/painel_led.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2292\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nchar change_light(char type, int num, bool change) {\n  if (type == 'X' && num == 0 && change) return 'O';\n  if (type == 'O' && num == 0 && change) return 'X';\n  if (type == 'X' && num == 1) return 'O';\n  if (type == 'O' && num == 1) return 'X';\n  if (type == 'X' && num % 2 != 0) return 'O';\n  if (type == 'O' && num % 2 != 0) return 'X';\n  if (num % 2 == 0) return type;\n}\n\nint main() {\n  int N, num;\n  string s, result;\n  bool change;\n\n  cin >> N;\n\n  while (N--) {\n    change = false;\n    cin >> s >> num;\n    result = \"\";\n\n    for (int i = 0; i < s.size(); i++) {\n      result += change_light(s[i], num, change);\n      change = change_light(s[i], num, change) == s[i];\n      num /= 2;\n    }\n\n    cout << result << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/palindrome_game.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2588\n\n#include <iostream>\n#include <string>\n#include <map>\n\nusing namespace std;\n\nint main() {\n  string s;\n  int N;\n\n  while (cin >> s) {\n    map<char, int> mapper;\n    N = 0;\n\n    for (int i = 0; i < s.size(); i++) {\n      if (mapper.find(s[i]) != mapper.end()) mapper.find(s[i])->second++;\n      else mapper[s[i]] = 1;\n    }\n\n    for (map<char, int>::iterator it = mapper.begin(); it != mapper.end(); it++) if (it->second % 2 != 0) N++;\n\n    if (N == 0) cout << 0 << endl;\n    else cout << --N << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/pandorgas.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1585\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\tint result;\n\tfloat n, n1, n2;\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> n1 >> n2;\n\t\tresult = n1 * n2 / 2;\n\t\tcout << result << \" cm2\" << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/pao_de_queijo_sweeper.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2552\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint calculate(const vector< vector<int> > &matrix, int i, int j, int max_line, int max_column) {\n  if (matrix[i][j] == 1) return 9;\n  int total = 0;\n  if (i+1 <= max_line) total += matrix[i+1][j]; // bottom\n  if (i-1 >= 0) total += matrix[i-1][j]; // top\n  if (j+1 <= max_column) total += matrix[i][j+1]; // right\n  if (j-1 >= 0) total += matrix[i][j-1]; // left\n  return total;\n}\n\nint main() {\n  int N, M, X;\n\n  while (cin >> N >> M) {\n    vector< vector<int> > matrix;\n\n    for (int i = 0; i < N; i++) {\n      vector<int> V;\n\n      for (int j = 0; j < M; j++) {\n        cin >> X;\n        V.push_back(X);\n      }\n\n      matrix.push_back(V);\n    }\n\n    for (int i = 0; i < N; i++) {\n      for (int j = 0; j < M; j++) {\n        cout << calculate(matrix, i, j, N-1, M-1);\n      }\n      cout << endl;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/parafusos_e_porcas.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/1520\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n  int N, n1, n2;\n\n  while (cin >> N) {\n    vector<int> V;\n\n    while (N--) {\n      cin >> n1 >> n2;\n\n      for (int i = n1; i <= n2; i++) {\n        V.push_back(i);\n      }\n    }\n\n    sort(V.begin(), V.end());\n    cin >> N;\n    n1 = -1;\n    n2 = -1;\n\n    for (int i = 0; i < V.size(); i++) {\n      if (N == V[i]) {\n        n1 = i;\n        break;\n      }\n    }\n\n    for (int i = V.size()-1; i >= 0; i--) {\n      if (N == V[i]) {\n        n2 = i;\n        break;\n      }\n    }\n\n    if (n1 != -1 && n2 != -1) cout << N << \" found from \" << n1 << \" to \" << n2 << endl;\n    else cout << N << \" not found\" << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/parenthesis_balance.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1068\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\tstring operation;\n\tint open = 0, close = 0;\n\tbool correct = true;\n\n\twhile (getline(cin, operation)) {\n\t\tfor (int i = 0; i < operation.size(); i++) {\n\t\t\tif (operation[i] == '(') {\n\t\t\t\topen++;\t\t\t\t\n\t\t\t} else if (operation[i] == ')') {\n\t\t\t\tclose++;\n\t\t\t\tif (open < close) {\n\t\t\t\t\tbreak;\n\t\t\t\t\tcorrect = false;\n\t\t\t\t}\n\t\t\t} \n\t\t}\n\t\t\n\t\tif (correct && open == close) cout << \"correct\" << endl;\n\t\telse cout << \"incorrect\" << endl;\n\n\t\topen = 0;\n\t\tclose = 0;\n\t\tcorrect = true;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/parity.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2176\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\tint numOfOneBits = 0;\n\tstring s;\n\tcin >> s;\n\t\n\tfor (int i = 0; i < s.size(); i++) if (s[i] == '1') numOfOneBits++;\n\t\n\tif (numOfOneBits % 2 == 0) s += '0';\n\telse s += '1';\n\t\n\tcout << s << endl;\n\t\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/pascal_library.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1267\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\t\n\tint alumnis, dinners, temp;\n\tvector<int> al;\n\n\tcin >> alumnis >> dinners;\n\n\twhile (alumnis + dinners != 0) {\n\t\tbool didit = false;\n\t\tfor (int i = 0; i < alumnis; i++) al.push_back(0);\n\n\t\tfor (int j = 0; j < dinners; j++) {\n\t\t\tfor (int i = 0; i < alumnis; i++) {\n\t\t\t\tcin >> temp;\n\t\t\t\tif (temp) al[i]++;\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = 0; i < alumnis; i++) {\n\t\t\tif (al[i] == dinners) {\n\t\t\t\tdidit = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (didit) cout << \"yes\" << endl;\n\t\telse cout << \"no\" << endl;\n\n\t\tal.clear();\n\t\tcin >> alumnis >> dinners;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/password.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2146\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\tint n;\n\n\twhile (cin >> n) {\n\t\tcout << n-1 << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/password_validator.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2253\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nbool validateString(string s) {\n\tstring alphabetUppercase = \"ABCDEFGHIJKLMNOPQRSTUVXWYZ\";\n\tstring alphabetLowercase = \"abcdefghijklmnopqrstuvxwyz\";\n\tstring numbers = \"0123456789\";\n\tbool hasUppercasedChar = false, hasLowercasedChar = false, hasNumber = false;\n\n\tfor (int i = 0; i < s.size(); i++) {\n\t\tif (alphabetUppercase.find(s[i]) != string::npos) hasUppercasedChar = true;\n\t\tif (alphabetLowercase.find(s[i]) != string::npos) hasLowercasedChar = true;\n\t\tif (numbers.find(s[i]) != string::npos) hasNumber = true;\n\t}\n\n\treturn hasUppercasedChar && hasLowercasedChar && hasNumber;\n}\n\nbool validatePunctuation(string s) {\n\tif (s.find(\"á\") == string::npos &&\n\t\t\ts.find(\"é\") == string::npos &&\n\t\t\ts.find(\"í\") == string::npos &&\n\t\t\ts.find(\"ó\") == string::npos &&\n\t\t\ts.find(\"ú\") == string::npos &&\n\t\t\ts.find(\"Á\") == string::npos &&\n\t\t\ts.find(\"É\") == string::npos &&\n\t\t\ts.find(\"Í\") == string::npos &&\n\t\t\ts.find(\"Ó\") == string::npos &&\n\t\t\ts.find(\"Ú\") == string::npos &&\n\t\t\ts.find(\"â\") == string::npos &&\n\t\t\ts.find(\"ê\") == string::npos &&\n\t\t\ts.find(\"î\") == string::npos &&\n\t\t\ts.find(\"ô\") == string::npos &&\n\t\t\ts.find(\"û\") == string::npos &&\n\t\t\ts.find(\"Â\") == string::npos &&\n\t\t\ts.find(\"Ê\") == string::npos &&\n\t\t\ts.find(\"Î\") == string::npos &&\n\t\t\ts.find(\"Ô\") == string::npos &&\n\t\t\ts.find(\"Û\") == string::npos &&\n\t\t\ts.find(\"ã\") == string::npos &&\n\t\t\ts.find(\"ẽ\") == string::npos &&\n\t\t\ts.find(\"ĩ\") == string::npos &&\n\t\t\ts.find(\"õ\") == string::npos &&\n\t\t\ts.find(\"ũ\") == string::npos &&\n\t\t\ts.find(\"Ã\") == string::npos &&\n\t\t\ts.find(\"Ẽ\") == string::npos &&\n\t\t\ts.find(\"Ĩ\") == string::npos &&\n\t\t\ts.find(\"Õ\") == string::npos &&\n\t\t\ts.find(\"Ũ\") == string::npos &&\n\t\t\ts.find(\"à\") == string::npos &&\n\t\t\ts.find(\"è\") == string::npos &&\n\t\t\ts.find(\"ì\") == string::npos &&\n\t\t\ts.find(\"ò\") == string::npos &&\n\t\t\ts.find(\"ù\") == string::npos &&\n\t\t\ts.find(\"À\") == string::npos &&\n\t\t\ts.find(\"È\") == string::npos &&\n\t\t\ts.find(\"Ì\") == string::npos &&\n\t\t\ts.find(\"Ò\") == string::npos &&\n\t\t\ts.find(\"Ù\") == string::npos &&\n\t\t\ts.find(\".\") == string::npos &&\n\t\t\ts.find(\",\") == string::npos &&\n\t\t\ts.find(\";\") == string::npos &&\n\t\t\ts.find(\"!\") == string::npos &&\n\t\t\ts.find(\"?\") == string::npos &&\n\t\t\ts.find(\":\") == string::npos &&\n\t\t\ts.find(\"(\") == string::npos &&\n\t\t\ts.find(\")\") == string::npos &&\n\t\t\ts.find(\"[\") == string::npos &&\n\t\t\ts.find(\"]\") == string::npos &&\n\t\t\ts.find(\"{\") == string::npos &&\n\t\t\ts.find(\"}\") == string::npos &&\n\t\t\ts.find(\"-\") == string::npos &&\n\t\t\ts.find(\"\\\"\") == string::npos &&\n\t\t\ts.find(\"\\\\\") == string::npos &&\n\t\t\ts.find(\"/\") == string::npos &&\n\t\t\ts.find(\"...\") == string::npos &&\n\t\t\ts.find(\"'\") == string::npos &&\n\t\t\ts.find(\"^\") == string::npos &&\n\t\t\ts.find(\"`\") == string::npos &&\n\t\t\ts.find(\"~\") == string::npos &&\n\t\t\ts.find(\"+\") == string::npos &&\n\t\t\ts.find(\"-\") == string::npos &&\n\t\t\ts.find(\"=\") == string::npos &&\n\t\t\ts.find(\"_\") == string::npos &&\n\t\t\ts.find(\"*\") == string::npos &&\n\t\t\ts.find(\"&\") == string::npos &&\n\t\t\ts.find(\"¨\") == string::npos &&\n\t\t\ts.find(\"%\") == string::npos &&\n\t\t\ts.find(\"$\") == string::npos &&\n\t\t\ts.find(\"#\") == string::npos &&\n\t\t\ts.find(\"@\") == string::npos &&\n\t\t\ts.find(\">\") == string::npos &&\n\t\t\ts.find(\"<\") == string::npos &&\n\t\t\ts.find(\" \") == string::npos) return true;\n\n\treturn false;\n}\n\nbool validateSize(string s) {\n\tif (s.size() >= 6 && s.size() <= 32) return true;\n\treturn false;\n}\n\nint main() {\n\tstring s;\n\n\twhile (getline(cin, s)) {\n\t\tif (validateString(s) && validatePunctuation(s) && validateSize(s)) cout << \"Senha valida.\" << endl;\n\t\telse cout << \"Senha invalida.\" << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/paulas_mathematic_game.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1192\n\n#include <iostream>\n#include <string>\n#include <cctype>\n\nusing namespace std;\n\nint main() {\n\n  int n;\n  cin >> n;\n\n  while (n--) {\n    string x;\n    cin >> x;\n\n    int n1 = x[0] - 48;\n    int n2 = x[2] - 48;\n\n    if (n1 == n2) {\n      cout << n1 * n2 << endl;\n    } else if (isupper(x[1])) {\n      cout << n2 - n1 << endl;\n    } else {\n      cout << n1 + n2 << endl;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/peaks_and_valleys.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2162\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int n, first, second, result = 1;\n  bool bigger;\n  cin >> n >> first >> second;\n  n -= 2;\n\n  if (first > second) {\n    bigger = true;\n  } else if (first < second) {\n    bigger = false;\n  } else {\n    cout << 0 << endl;\n    return 0;\n  }\n\n  while (n--) {\n    first = second;\n    cin >> second;\n\n    if (first > second && !bigger) bigger = true;\n    else if (first < second && bigger) bigger = false;\n    else result = 0;\n  }\n\n  cout << result << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/pedrinhos_christmas.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2139\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int month, day, days;\n  int daysInEachMonth[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 25 };\n\n  while (cin >> month >> day) {\n    if (month == 12) {\n      if (day < 24) cout << \"Faltam \" << 25 - day << \" dias para o natal!\" << endl;\n      else if (day == 24) cout << \"E vespera de natal!\" << endl;\n      else if (day == 25) cout << \"E natal!\" << endl;\n      else cout << \"Ja passou!\" << endl;\n    } else {\n      days = daysInEachMonth[month-1] - day;\n      for (int i = month; i < 12; i++) days += daysInEachMonth[i];\n      cout << \"Faltam \" << days << \" dias para o natal!\" << endl;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/pepe.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2152\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nstring parsePhrase(string hour, string minute, int opened) {\n\tstring parsedHour, parsedMinute, numbers = \"0123456789\";\n\tif (hour.size() == 1) parsedHour = \"0\" + hour;\n\telse parsedHour = hour;\n\tif (minute.size() == 1) parsedMinute = \"0\" + minute;\n\telse parsedMinute = minute;\n\n\tif (opened) return parsedHour + \":\" + parsedMinute + \" - A porta abriu!\";\n\telse return parsedHour + \":\" + parsedMinute + \" - A porta fechou!\";\n}\n\nint main() {\n\tint n, opened;\n\tstring hour, minute;\n\n\tcin >> n;\n\n\twhile (n--)\t{\n\t\tcin >> hour >> minute >> opened;\n\t\tcout << parsePhrase(hour, minute, opened) << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/perfect_number.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1164\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n, x, total=0;\n\tcin >> n;\n\n\twhile (n--) {\n\n\t\tcin >> x;\n\n\t\tfor (int i = 1; i < x; i++) {\n\t\t\tif (x % i == 0) total += i;\n\t\t\tif (total > x) break;\n\t\t}\n\n\t\tif (total == x) cout << x << \" eh perfeito\" << endl;\n\t\telse cout << x << \" nao eh perfeito\" << endl;\n\n\t\ttotal = 0;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/phin_bonati.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2149\n\n#include <iostream>\n\nusing namespace std;\n\nlong long int willBonatiAlgorithm(int n) {\n\tlong long int n1 = 0, n2 = 1, result;\n\n\tif (n == 1) return 0;\n\telse if (n == 2) return 1;\n\telse {\n\t\tfor (int i = 3; i <= n; i++) {\n\t\t\tif (i % 2 != 0) result = n1 + n2;\n\t\t\telse result = n1 * n2;\n\t\t\tn1 = n2;\n\t\t\tn2 = result;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nint main() {\n\tint n;\n\tlong long int result;\n\n\twhile (cin >> n) {\n\t\tresult = willBonatiAlgorithm(n);\n\t\tcout << result << endl;\n\t}\n}"
  },
  {
    "path": "competitive-programming/uri/pizza_pre_bh.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2554\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nstruct date {\n  int day;\n  int month;\n  int year;\n};\n\nint main() {\n  int N, D, X, day, month, year, total, result;\n  char useless;\n\n  while (cin >> N >> D) {\n    result = -1;\n    vector<date> dates;\n\n    for (int j = 0; j < D; j++) {\n      total = 0;\n      cin >> day >> useless >> month >> useless >> year;\n      date d;\n      d.day = day;\n      d.month = month;\n      d.year = year;\n      dates.push_back(d);\n\n      for (int i = 0; i < N; i++) {\n        cin >> X;\n        total += X;\n      }\n\n      if (total == N && result == -1) result = j;\n    }\n\n    if (result == -1) cout << \"Pizza antes de FdI\" << endl;\n    else cout << dates[result].day << \"/\" << dates[result].month << \"/\" << dates[result].year << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/pokemon.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1836\n\n#include <iostream>\n#include <string>\n#include <math.h>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, l, b, iv, e, result;\n\tstring pokemon;\n\n\tcin >> n;\n\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> pokemon >> l;\n\t\tcout << \"Caso #\" << i << \": \" << pokemon << \" nivel \" << l << endl;\n\n\t\tfor (int j = 0; j < 4; j++) {\n\t\t\tcin >> b >> iv >> e;\n\n\t\t\tif (j == 0) result = ((iv + b + 50 + sqrt(e) / 8) * l / 50) + 10;\t\t\t\t\n\t\t\telse result = ((iv + b + sqrt(e) / 8) * l / 50) + 5;\n\n\t\t\tif (j == 0) cout << \"HP: \" << result << endl;\n\t\t\telse if (j == 1) cout << \"AT: \" << result << endl;\n\t\t\telse if (j == 2) cout << \"DF: \" << result << endl;\n\t\t\telse cout << \"SP: \" << result << endl;\n\t\t}\n\t}\n\n\treturn 0;\t\n}"
  },
  {
    "path": "competitive-programming/uri/pomekon_collection.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2174\n\n#include <iostream>\n#include <set>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\tint n;\n\tstring pokemonName;\n\tset<string> pokemons;\n\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> pokemonName;\n\t\tpokemons.insert(pokemonName);\n\t}\n\n\tcout << \"Falta(m) \" << 151 - pokemons.size() << \" pomekon(s).\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/pomekons_battle.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2221\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\tint numberOfInstance, attack, defense, bonus, level;\n\tfloat firstPlayerValue, secondPlayerValue;\n\n\tcin >> numberOfInstance;\n\n\twhile (numberOfInstance--) {\n\t\tcin >> bonus;\n\n\t\tcin >> attack >> defense >> level;\n\t\tfirstPlayerValue = (attack + defense) / 2.0;\n\t\tif (level % 2 == 0) firstPlayerValue += bonus;\n\t\t\n\t\tcin >> attack >> defense >> level;\n\t\tsecondPlayerValue = (attack + defense) / 2.0;\n\t\tif (level % 2 == 0) secondPlayerValue += bonus;\n\n\t\tif (firstPlayerValue > secondPlayerValue) cout << \"Dabriel\" << endl;\n\t\telse if (secondPlayerValue > firstPlayerValue) cout << \"Guarte\" << endl;\n\t\telse cout << \"Empate\" << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/population_increase.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1160\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n, p1, p2, years=0;\n\tdouble g1, g2;\n\tcin >> n;\n\n\twhile (n--) {\n\n\t\tcin >> p1 >> p2;\n\t\tcin >> g1 >> g2;\n\n\t\twhile (true) {\n\n\t\t\tp1 += p1 * g1 / 100;\n\t\t\tp2 += p2 * g2 / 100;\n\n\t\t\tyears++;\n\n\t\t\tif (p1 > p2 || years > 100) break;\n\t\t}\n\n\t\tif (years > 100) cout << \"Mais de 1 seculo.\" << endl;\n\t\telse cout << years << \" anos.\" << endl;\n\n\t\tyears = 0;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/positive_numbers.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1060\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint total=0;\n\n\tfor (int i = 0; i < 6; i++) {\n\t\tdouble n;\n\t\tcin >> n;\n\t\tif (n > 0) total++;\n\t}\n\n\tcout << total << \" valores positivos\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/positives_and_average.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1064\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint total=0;\n\tdouble total1=0;\n\n\tfor (int i = 0; i < 6; i++) {\n\t\tdouble n;\n\t\tcin >> n;\t\t\n\t\tif (n > 0) {\n\t\t total++;\n\t\t total1 += n;\n\t\t}\n\t}\n\n\tcout << total << \" valores positivos\" << endl;\n\tcout << total1 / total << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/power_crisis.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1031\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvector<int> buildVector(int n) {\n  vector<int> v;\n  for(int i = 0; i < n; i++) v.push_back(1);\n  return v;\n}\n\nint getLastRegion(vector<int> regions, int m) {\n  int counter = 0, max = regions.size(), ind = 0, c = m;\n  while (counter < max - 1) {\n    while (regions[ind] == 0) {      \n      ind++;\n      if (ind >= max) ind -= max;\n    }\n    \n    if (c == m) {\n      regions[ind] = 0;\n      counter++;\n      c = 0;\n    }\n    \n    ind++;\n    c++;\n    if (ind >= max) ind -= max;\n  }\n\n  for (int i = 0; i < regions.size(); i++) if (regions[i] == 1) return i+1;\n}\n\nint main() {\n  vector<int> v;\n  int n, regionIndex;\n\n  while (cin >> n && n != 0) {\n    int i = 1;\n    while(true) {\n      if (getLastRegion(buildVector(n), i) == 13) {\n        regionIndex = i;\n        break;\n      }\n\n      i++;\n    }\n\n    cout << regionIndex << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/preface.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1837\n\n// 9 4 --> 2 1\n// 9 -4 --> -2 1\n// -9 4 --> -3 3\n// -9 -4 --> 3 3\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int x, n, q, r;\n  float n1, n2,xf;\n  cin >> n1 >> n2;\n\n  n = n2;\n  if (n < 0) n *= -1;\n\n  for (int i = 0; i < n; i++) {\n    x = (n1 - i) / n2;\n    xf = (n1 - i) / n2;\n\n    if (x == xf) {\n      r = i;\n      q = x;\n      break;\n    }\n  }\n\n  cout << q << \" \" << r << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/presents.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2022\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <iomanip>\n\nusing namespace std;\n\nstruct product {\n\tstring name;\n\tint preference;\n\tfloat price;\n};\n\nbool compareProducts(const product &p1, const product &p2) {\n\tif (p1.preference > p2.preference) return true;\n\telse if (p1.preference == p2.preference) {\n\t\tif (p1.price < p2.price) return true;\n\t\telse if (p1.price == p2.price) return p1.name < p2.name;\n\t}\n\n\treturn false;\n}\n\nint main() {\n\tstring name, productName;\n\tint n, preference;\n\tfloat price;\n\n\twhile (cin >> name) {\n\t\tcin >> n;\n\t\tvector<product> products;\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin.ignore();\n\t\t\tgetline(cin, productName);\n\t\t\tcin >> price >> preference;\n\t\t\tproduct p;\n\t\t\tp.name = productName;\n\t\t\tp.preference = preference;\n\t\t\tp.price = price;\n\t\t\tproducts.push_back(p);\n\t\t}\n\n\t\tsort(products.begin(), products.end(), compareProducts);\n\n\t\tcout << \"Lista de \" << name << endl;\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcout << products[i].name << \" - R$\";\n\t\t\tcout << fixed << setprecision(2) << products[i].price << endl;\n\t\t}\n\n\t\tcout << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/primary_arithmatic.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1212\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\n  long long int n1, n2;\n  cin >> n1 >> n2;\n\n  while (n1 + n2 != 0) {\n    vector<int> v1, v2;\n    int counter = 0;\n\n    while (n1 > 0) {\n      v1.push_back(n1 % 10);\n      n1 /= 10;\n    }\n\n    while (n2 > 0) {\n      v2.push_back(n2 % 10);\n      n2 /= 10;\n    }\n\n    if (v1.size() > v2.size()) {\n      for (int i = 0; i < v2.size(); i++) if (v1[i] + v2[i] >= 10) counter++;\n    } else {\n      for (int i = 0; i < v1.size(); i++) if (v1[i] + v2[i] >= 10) counter++;\n    }\n\n    if (counter == 1) cout << counter << \" carry operation.\" << endl;\n    else if (counter > 1) cout << counter << \" carry operations.\" << endl;\n    else cout << \"No carry operation.\" << endl;\n    cin >> n1 >> n2;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/prime_number.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1165\n\n#include <iostream>\n#include <math.h>\n\nusing namespace std;\n\nint is_prime(int n) {\n\n\tif (n == 2)\n\t\treturn 1;\n\n\tif ((n % 2) == 0)\n\t\treturn 0;\n\n\tint s = sqrt(n);\n\n\tfor (int i = 3; i <= s; i += 2) if (n % i == 0) return 0;\n\n\treturn 1;\n}\n\nint main() {\n\n\tint n, x;\n\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> x;\n\t\tif (is_prime(x)) cout << x << \" eh primo\" << endl;\n\t\telse cout << x << \" nao eh primo\" << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/pum.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1142\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n, pum=1;\n\n\tcin >> n;\n\n\twhile (n--) {\n\n\t\tint a = pum + 3;\n\n\t\tfor (int i = pum; i < a; i++) {\n\t\t\tcout << i << \" \";\n\t\t\tpum++;\n\t\t}\n\n\t\tcout << \"PUM\" << endl;\n\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/quadrant.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1115\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int x, y;\n\n  cin >> x >> y;\n\n  while (x != 0 && y != 0) {\n    if (x > 0 && y > 0) cout << \"primeiro\" << endl;\n    else if (x < 0 && y > 0) cout << \"segundo\" << endl;\n    else if (x < 0 && y < 0) cout << \"terceiro\" << endl;\n    else if (x > 0 && y < 0) cout << \"quarto\" << endl;\n\n    cin >> x >> y;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/queen.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1087\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint x1, x2, y1, y2, found=0;\n\tcin >> x1 >> y1 >> x2 >> y2;\n\n\twhile (x1 + x2 + y1 + y2 != 0) {\n\n\t\tint x = x1, y = y1;\n\n\t\twhile (x != 0 && y != 0) {\n\n\t\t\tif (x == x2 && y == y2) found = 1;\n\n\t\t\tx--;\n\t\t\ty--;\n\t\t}\n\n\t\tx = x1, y = y1;\n\n\t\twhile (x != 9 && y != 0) {\n\n\t\t\tif (x == x2 && y == y2) found = 1;\n\n\t\t\tx++;\n\t\t\ty--;\n\t\t}\n\n\t\tx = x1, y = y1;\n\n\t\twhile (x != 0 && y != 9) {\n\n\t\t\tif (x == x2 && y == y2) found = 1;\n\n\t\t\tx--;\n\t\t\ty++;\n\t\t}\n\n\t\tx = x1, y = y1;\n\n\t\twhile (x != 9 && y != 9) {\n\n\t\t\tif (x == x2 && y == y2) found = 1;\n\n\t\t\tx++;\n\t\t\ty++;\n\t\t}\n\n\t\tif (x1 == x2 && y1 == y2) cout << 0 << endl;\n\t\telse if (x1 == x2 || y1 == y2 || found) cout << 1 << endl;\n\t\telse cout << 2 << endl;\n\n\t\tcin >> x1 >> y1 >> x2 >> y2;\n\t\tfound = 0;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/radares.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2598\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int C, N, M, result;\n\n  cin >> C;\n\n  while (C--) {\n    cin >> N >> M;\n\n    result = N / M;\n    if (N % M > 0) result++;\n    cout << result << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/rails.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1062\n\n#include <iostream>\n#include <queue>\n#include <stack>\n\nusing namespace std;\n\nvoid clear(queue<int> &q) {\n   queue<int> empty;\n   swap(q, empty);\n}\n\nbool canMarshalInTheRequiredOrder(queue<int> &train) {\n\tstack<int> order;\n\torder.push(1);\n\tint max = train.size(), wagonNumber = 2;\n\n\twhile (true) {\n\t\tif (!train.empty() && !order.empty() && train.front() == order.top()) {\n\t\t\ttrain.pop();\n\t\t\torder.pop();\n\t\t} else if (wagonNumber <= max) {\n\t\t\torder.push(wagonNumber);\n\t\t\twagonNumber++;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (train.empty()) return true;\n\t}\t\n}\n\nint main() {\n\tint n, x;\n\tqueue<int> train;\n\t\n\twhile (cin >> n && n != 0) {\n\t\twhile (cin >> x && x != 0) {\n\t\t\ttrain.push(x);\n\n\t\t\tfor (int i = 1; i < n; i++) {\n\t\t\t\tcin >> x;\n\t\t\t\ttrain.push(x);\n\t\t\t}\n\n\t\t\tif (canMarshalInTheRequiredOrder(train)) cout << \"Yes\" << endl;\n\t\t\telse cout << \"No\" << endl;\n\n\t\t\tclear(train);\n\t\t}\n\n\t\tcout << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/rails_again.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1062\n\n#include <iostream>\n#include <queue>\n#include <stack>\n#include <string>\n\nusing namespace std;\n\nstring requiredOrder(queue<char> &t, queue<char> &order) {\n\tstack<char> train;\n\tint max = t.size(), wagonNumber = 1;\n\tstring result = \"\";\n\n\twhile (true) {\n\t\tif (!train.empty() && !order.empty() && train.top() == order.front()) {\n\t\t\ttrain.pop();\n\t\t\torder.pop();\n\t\t\tresult += \"R\";\n\t\t} else if (wagonNumber <= max) {\n\t\t\twagonNumber++;\n\t\t\ttrain.push(t.front());\n\t\t\tt.pop();\t\t\t\n\t\t\tresult += \"I\";\n\t\t} else {\n\t\t\treturn result + \" Impossible\";\n\t\t}\n\n\t\tif (order.empty()) return result;\n\t}\t\n}\n\nint main() {\n\tint n;\n\tchar el;\n\t\n\twhile (cin >> n && n != 0) {\n\t\tqueue<char> train;\n\t\tqueue<char> order;\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> el;\n\t\t\ttrain.push(el);\n\t\t}\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> el;\n\t\t\torder.push(el);\n\t\t}\t\t\n\n\t\tcout << requiredOrder(train, order) << endl;\n\t}\t\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/reading_books.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1542\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n1, n2, n3, result;\n\n\twhile (cin >> n1 && n1 != 0) {\n\t\tcin >> n2 >> n3;\n\t\tresult = n1 * (n2 * n3) / (n3 - n1);\t\t\n\t\tif (result <= 1) cout << result << \" pagina\" << endl;\n\t\telse cout << result << \" paginas\" << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/regular_simple_polygon.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1959\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  long long int n1, n2;\n  cin >> n1 >> n2;\n\n  cout << n1 * n2 << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/remaining2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1075\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\n\tcin >> n;\n\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (i % n == 2) {\n\t\t\tcout << i << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/removing_letter.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1556\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\n  string s;\n\n  while (cin >> s) {\n    vector<string> v;\n\n    for (int i = 0; i < s.size(); i++) {\n      string new_s = \"\";\n\n      for (int j = i; j < s.size(); j++) {\n        new_s += s[j];\n        v.push_back(new_s);\n        cout << new_s << endl;\n      }\n    }\n\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/rest_of_a_division.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1133\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint x, y;\n\t\n\tcin >> x >> y;\n\n\tif (x < y) {\n\t\tfor (int i = x+1; i < y; i++) {\n\t\t\tif (i % 5 == 2 || i % 5 == 3) {\n\t\t\t\tcout << i << endl;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor (int i = y+1; i < x; i++) {\n\t\t\tif (i % 5 == 2 || i % 5 == 3) {\n\t\t\t\tcout << i << endl;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/right_area.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1190\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  vector< vector<double> > v1;\n  double n, total=0;\n  string operation;\n\n  cin >> operation;\n\n  for (int i = 0; i < 12; i++) {\n    vector<double> v;\n\n    for (int j = 0; j < 12; j++) {\n      cin >> n;\n      v.push_back(n);\n    }\n\n    v1.push_back(v);\n  }\n\n  int counter1=11, count = 0;\n\n  for (int i = 1; i < 11; i++) {\n    for (int j = counter1; j < 12; j++) {\n      total += v1[i][j];\n      count++;\n    }\n\n    if (i < 5) counter1--;\n    else if (i > 5) counter1++;\n  }\n\n  if (operation == \"S\") cout << fixed << setprecision(1) << total << endl;\n  else cout << fixed << setprecision(1) << total / count << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/rlj.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2557\n\n#include <iostream>\n#include <string>\n#include <math.h>\n\nusing namespace std;\n\nint to_digit(char c) {\n  return c - '0';\n}\n\nint string_to_int(string num) {\n  int n = 0;\n  for (int i = num.size()-1, j = 0; i >= 0; i--, j++) n += to_digit(num[i]) * pow(10, j);\n  return n;\n}\n\nint parse_eq(string eq, int start, int size) {\n  string j = eq.substr(start, size);\n  return string_to_int(j);\n}\n\nint main() {\n  string eq;\n\n  while (getline(cin, eq)) {\n    if (eq[0] == 'R') {\n      cout << parse_eq(eq, eq.find(\"=\")+1, eq.size() - eq.find(\"=\") - 1) - parse_eq(eq, eq.find(\"+\")+1, eq.find(\"=\") - eq.find(\"+\") - 1) << endl;\n    } else if (eq[eq.size()-1] == 'J') {\n      cout << parse_eq(eq, 0, eq.find(\"+\")) + parse_eq(eq, eq.find(\"+\")+1, eq.find(\"=\") - eq.find(\"+\") - 1) << endl;\n    } else {\n      cout << parse_eq(eq, eq.find(\"=\")+1, eq.size() - eq.find(\"=\") - 1) - parse_eq(eq, 0, eq.find(\"+\")) << endl;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/robot_instructions.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1574\n\n#include <iostream>\n#include <vector>\n#include <map>\n#include <string>\n\nusing namespace std;\n\nstring parse_string(string line) {\n\tvector<string> v;\n\tstring word = \"\";\n\t\n\tfor (int i = 0; i < line.size(); i++) {\n\t\tif (line[i] == ' ') {\n\t\t\tv.push_back(word);\n\t\t\tword.clear();\n\t\t} else if (i == line.size() - 1) {\n\t\t\tword += line[i];\n\t\t\tv.push_back(word);\n\t\t\tword.clear();\n\t\t} else {\n\t\t\tword += line[i];\n\t\t}\n\t}\n\t\n\treturn v.back();\n}\n\nint to_digit(char digit) {\n  return digit - '0';\n}\n\nint string_to_number(string n) {\n  if (n == \"\") {\n    return -1;\n  } else {\n    int num = 0;\n\n    for (int i = 0; i < n.size(); i++) {\n      num = num * 10 + to_digit(n[i]);\n    }\n\n    return num;\n  }\n}\n\nint main() {\n\tint n, tests;\n\tcin >> n;\n\tstring command;\n\t\n\twhile (n--) {\n\t\tcin >> tests;\n\t\tcin.ignore();\n\t\tmap<int, int> m;\n\t\tgetline(cin, command);\n\t\tif (command == \"LEFT\") m[1] = -1;\n\t\telse m[1] = 1;\n\t\t\n\t\tfor (int i = 2; i <= tests; i++) {\n\t\t\tgetline(cin, command);\n\t\t\tcommand = parse_string(command);\n\t\t\tif (command == \"LEFT\") m[i] = -1;\n\t\t\telse if (command == \"RIGHT\") m[i] = 1;\n\t\t\telse {\n\t\t\t\tint key = string_to_number(command);\n\t\t\t\tm[i] = m[key];\n\t\t\t}\n\t\t}\n\t\t\n\t\tmap<int, int>::iterator it;\n\t\tint position = 0;\n\t\t\n\t\tfor (it = m.begin(); it != m.end(); it++) {\n\t\t\tposition += it->second;\n\t\t}\n\t\t\n\t\tcout << position << endl;\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/rock_paper_airstrike.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2031\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n  int n;\n  cin >> n;\n  string player1, player2;\n\n  while (n--) {\n    cin >> player1 >> player2;\n\n    if (player1 == player2) {\n      if (player1 == \"ataque\") cout << \"Aniquilacao mutua\" << endl;\n      else if (player1 == \"pedra\") cout << \"Sem ganhador\" << endl;\n      else cout << \"Ambos venceram\" << endl;\n    } else {\n      if (player1 == \"ataque\" && player2 == \"pedra\") cout << \"Jogador 1 venceu\" << endl;\n      else if (player2 == \"ataque\" && player1 == \"pedra\") cout << \"Jogador 2 venceu\" << endl;\n      else if (player1 == \"pedra\" && player2 == \"papel\") cout << \"Jogador 1 venceu\" << endl;\n      else if (player2 == \"pedra\" && player1 == \"papel\") cout << \"Jogador 2 venceu\" << endl;\n      else if (player1 == \"ataque\" && player2 == \"papel\") cout << \"Jogador 1 venceu\" << endl;\n      else if (player2 == \"ataque\" && player1 == \"papel\") cout << \"Jogador 2 venceu\" << endl;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/rock_paper_scissors_lizard_spock.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1873\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nstring get_winner(string type1, string type2) {\n  if (type1 == \"tesoura\" && type2 == \"papel\") return \"rajesh\";\n  else if (type1 == \"papel\" && type2 == \"pedra\") return \"rajesh\";\n  else if (type1 == \"pedra\" && type2 == \"lagarto\") return \"rajesh\";\n  else if (type1 == \"lagarto\" && type2 == \"spock\") return \"rajesh\";\n  else if (type1 == \"spock\" && type2 == \"tesoura\") return \"rajesh\";\n  else if (type1 == \"tesoura\" && type2 == \"lagarto\") return \"rajesh\";\n  else if (type1 == \"lagarto\" && type2 == \"papel\") return \"rajesh\";\n  else if (type1 == \"papel\" && type2 == \"spock\") return \"rajesh\";\n  else if (type1 == \"spock\" && type2 == \"pedra\") return \"rajesh\";\n  else if (type1 == \"pedra\" && type2 == \"tesoura\") return \"rajesh\";\n  else if (type1 == type2) return \"empate\";\n  else return \"sheldon\";\n}\n\nint main() {\n\n  int n;\n  string rajesh, sheldon;\n\n  cin >> n;\n\n  while (n--) {\n    cin >> rajesh >> sheldon;\n    cout << get_winner(rajesh, sheldon) << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/roman_numerals_for_page_numbers.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1960\n\n#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nint main() {\n  int n, remainder, integer;\n  string c[] = { \"C\", \"CC\", \"CCC\", \"CD\", \"D\", \"DC\", \"DCC\", \"DCCC\", \"CM\" };\n  string d[] = { \"X\", \"XX\", \"XXX\", \"XL\", \"L\", \"LX\", \"LXX\", \"LXXX\", \"XC\" };\n  string u[] = { \"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\" };\n  cin >> n;\n\n  integer = n / 100;\n  remainder = n % 100;\n\n  switch(integer) {\n      case 1: cout << c[0]; break;\n      case 2: cout << c[1]; break;\n      case 3: cout << c[2]; break;\n      case 4: cout << c[3]; break;\n      case 5: cout << c[4]; break;\n      case 6: cout << c[5]; break;\n      case 7: cout << c[6]; break;\n      case 8: cout << c[7]; break;\n      case 9: cout << c[8]; break;\n  }\n\n  integer = remainder / 10;\n  remainder = remainder % 10;\n\n  switch(integer) {\n      case 1: cout << d[0]; break;\n      case 2: cout << d[1]; break;\n      case 3: cout << d[2]; break;\n      case 4: cout << d[3]; break;\n      case 5: cout << d[4]; break;\n      case 6: cout << d[5]; break;\n      case 7: cout << d[6]; break;\n      case 8: cout << d[7]; break;\n      case 9: cout << d[8]; break;\n  }\n\n  integer = remainder / 1;\n\n  switch(integer) {\n      case 1: cout << u[0]; break;\n      case 2: cout << u[1]; break;\n      case 3: cout << u[2]; break;\n      case 4: cout << u[3]; break;\n      case 5: cout << u[4]; break;\n      case 6: cout << u[5]; break;\n      case 7: cout << u[6]; break;\n      case 8: cout << u[7]; break;\n      case 9: cout << u[8]; break;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/rot13.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1249\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\t\n\tstring word;\n\tstring alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz\";\n\n\twhile (getline(cin, word)) {\n\t\tstring new_word = \"\";\n\t\tfor (int i = 0; i < word.size(); i++) {\n\t\t\tint index = alphabet.find(word[i]);\n\t\t\tif (index != -1) {\n\t\t\t\tindex += 13;\n\t\t\t\tnew_word += alphabet[index];\n\t\t\t} else {\n\t\t\t\tnew_word += word[i];\n\t\t\t}\n\t\t}\t\n\t\t\n\t\tcout << new_word << endl;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/s_sequence.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1155\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n\tint n = 1;\n\tdouble total = 0;\n\n\tfor (int i = 1; i <= 100; i++) {\n\t\ttotal += (1.0 / i);\n\t}\n\n\tcout << fixed << setprecision(2) << total << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/s_sequence_2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1156\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n\tdouble n = 1;\n\tdouble total = 0;\n\n\tfor (int i = 1; i <= 39; i += 2) {\n\t\ttotal += (i / n);\n\t\tn *= 2;\n\t}\n\n\tcout << fixed << setprecision(2) << total << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/salary.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1008\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  int n1, n2;\n  float num;\n\n  cin >> n1 >> n2 >> num;\n\n  cout << \"NUMBER = \" << n1 << endl;\n  cout << fixed << setprecision(2) << \"SALARY = U$ \" << n2 * num << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/salary_with_bonus.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1009\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  string name;\n  float n1, n2;\n\n  cin >> name;\n  cin >> n1 >> n2;\n\n  cout << fixed << setprecision(2) << \"TOTAL = R$ \" << n1 + n2 * 0.15 << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/santas_translator.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1763\n\n#include <iostream>\n#include <string>\n#include <map>\n\nusing namespace std;\n\nint main() {\n\t\n\tmap<string,string> Dictionary;\n\n\tDictionary[\"brasil\"] = \"Feliz Natal!\";\n\tDictionary[\"alemanha\"] = \"Frohliche Weihnachten!\";\n\tDictionary[\"austria\"] = \"Frohe Weihnacht!\";\n\tDictionary[\"coreia\"] = \"Chuk Sung Tan!\";\n\tDictionary[\"espanha\"] = \"Feliz Navidad!\";\n\tDictionary[\"grecia\"] = \"Kala Christougena!\";\n\tDictionary[\"estados-unidos\"] = \"Merry Christmas!\";\n\tDictionary[\"inglaterra\"] = \"Merry Christmas!\";\n\tDictionary[\"australia\"] = \"Merry Christmas!\";\n\tDictionary[\"portugal\"] = \"Feliz Natal!\";\n\tDictionary[\"suecia\"] = \"God Jul!\";\n\tDictionary[\"turquia\"] = \"Mutlu Noeller\";\n\tDictionary[\"argentina\"] = \"Feliz Navidad!\";\n\tDictionary[\"chile\"] = \"Feliz Navidad!\";\n\tDictionary[\"mexico\"] = \"Feliz Navidad!\";\n\tDictionary[\"antardida\"] = \"Merry Christmas!\";\n\tDictionary[\"canada\"] = \"Merry Christmas!\";\n\tDictionary[\"irlanda\"] = \"Nollaig Shona Dhuit!\";\n\tDictionary[\"belgica\"] = \"Zalig Kerstfeest!\";\n\tDictionary[\"italia\"] = \"Buon Natale!\";\n\tDictionary[\"libia\"] = \"Buon Natale!\";\n\tDictionary[\"siria\"] = \"Milad Mubarak!\";\n\tDictionary[\"marrocos\"] = \"Milad Mubarak!\";\n\tDictionary[\"japao\"] = \"Merii Kurisumasu!\";\n\n\tstring country, result;\n\tbool found = false;\n\n\twhile (cin >> country) {\n\t\tif (Dictionary.find(country) ==  Dictionary.end()) cout << \"--- NOT FOUND ---\" << endl;      \n    else cout << Dictionary[country] << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/scientific_notation.cpp",
    "content": "#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\tlong double X;\n\tcin >> X;\n\tcout << showpos << uppercase << scientific << setprecision(4) << X << endl;\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/score_validation.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1117\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  int total=0;\n  double n, media=0;\n\n  cin >> n;\n\n  while (total < 2) {\n\n    if (n >= 0 && n <= 10) {\n      media += n;\n      total++;\n    } else {\n      cout << \"nota invalida\" << endl;\n    }\n\n    cin >> n;\n  }\n\n  cout << fixed << setprecision(2) << \"media = \" << media / 2.0 << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/searching_for_nessy.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1428\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\tint n, n1, n2, num, num1, num2;\n\tfloat aux1, aux2;\n\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> n1 >> n2;\n\t\t\n\t\taux1 = (n1 - 2) / 3.0;\n\t\tnum1 = aux1;\n\t\tif (aux1 - num1 > 0.0) num1++;\n\n\t\taux2 = (n2 - 2) / 3.0;\n\t\tnum2 = aux2;\n\t\tif (aux2 - num2 > 0.0) num2++;\n\t\t\n\t\tnum = num1 * num2;\n\t\tcout << num << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/searching_subsequences.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2126\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n  string subs, s;\n  int pos, qtd, casy = 1;\n\n  while (cin >> subs && cin >> s) {\n    qtd = 0;\n    pos = -1;\n\n    for (int i = 0; i < s.size() - subs.size() + 1; i++) {\n      if (subs == s.substr(i, subs.size())) {\n        qtd++;\n        pos = i+1;\n      }\n    }\n\n    cout << \"Caso #\" << casy << \":\" << endl;\n\n    if (pos == -1) cout << \"Nao existe subsequencia\" << endl;\n    else cout << \"Qtd.Subsequencias: \" << qtd << endl << \"Pos: \" << pos << endl;\n    cout << endl;\n    casy++;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/selection_test_1.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1035\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n1, n2, n3, n4;\n\n\tcin >> n1 >> n2 >> n3 >> n4;\n\n\t// Then if B is greater than C and D is greater than A and \n\t// if the sum of C and D is greater than the sum of A and B and \n\t// if C and D were positives values and if A is even\n\n\tif (n2 > n3 && n4 > n1 && n3 + n4 > n1 + n2 && n3 > 0 && n4 > 0 && n1 % 2 == 0)\n\t\tcout << \"Valores aceitos\" << endl;\n\telse\n\t\tcout << \"Valores nao aceitos\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/sequence_ij_1.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1095\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint j = 1;\n\n\tfor (int i = 60; i >= 0; i -= 5, j += 3) {\n\t\tcout << \"I=\" << j << \" J=\" << i << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/sequence_ij_2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1096\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint i = 1, j = 7, counter=0;\n\n\twhile (i != 9 || j != 5) {\n\t\tcout << \"I=\" << i << \" J=\" << j << endl;\n\n\t\tcounter++;\n\t\tj--;\n\n\t\tif (counter == 3) {\n\t\t\ti += 2;\n\t\t\tj = 7;\n\t\t\tcounter = 0;\n\t\t}\n\t}\n\t\n\tcout << \"I=\" << i << \" J=\" << j << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/sequence_ij_3.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1097\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint i = 1, j = 7, counter=0;\n\n\twhile (true) {\n\t\tcout << \"I=\" << i << \" J=\" << j << endl;\n\n\t\tcounter++;\n\t\tj--;\n\n\t\tif (counter == 3) {\n\t\t\ti += 2;\n\t\t\tj += 5;\n\t\t\tcounter = 0;\n\t\t}\n\n\t\tif (i == 9 && j == 13) {\n\t\t\tcout << \"I=\" << i << \" J=\" << j << endl;\n\t\t\tbreak;\n\t\t}\n\t}\t\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/sequence_ij_4.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1098\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\n  float i = 0;\n  vector<float> v;\n  v.push_back(1);\n  v.push_back(2);\n  v.push_back(3);\n\n  while (i < 2.1) {\n    for (int a = 0; a < 3; a++) cout << \"I=\" << i << \" J=\" << v[a] << endl;\n    for (int j = 0; j < 3; j++) v[j] += 0.2;\n    i += 0.2;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/sequence_of_numbers_and_sum.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1101\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n1, n2, total=0;\n\n\tcin >> n1 >> n2;\n\n\twhile (n1 > 0 && n2 > 0) {\n\t\tif (n1 > n2) {\n\t\t\tfor (int i = n2; i <= n1; i++) {\n\t\t\t\tcout << i << \" \";\n\t\t\t\ttotal += i;\n\t\t\t}\n\n\t\t\tcout << \"Sum=\" << total << endl;\n\t\t} else if (n2 > n1) {\n\t\t\tfor (int i = n1; i <= n2; i++) {\n\t\t\t\tcout << i << \" \";\n\t\t\t\ttotal += i;\n\t\t\t}\n\n\t\t\tcout << \"Sum=\" << total << endl;\n\t\t} else {\n\t\t\tcout << n1 << \" Sum=\" << n1 << endl;\n\t\t}\n\n\t\ttotal = 0;\n\t\tcin >> n1 >> n2;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/sequence_of_sequence.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2028\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\n  int n, counter=1, size, num;\n\n  while (scanf(\"%i\", &n) != EOF) {\n    if (n == 0) {\n      cout << \"Caso \" << counter << \": \" << 1 << \" numero\" << endl;\n      cout << 0;\n    } else {\n      size = ((n * (1 + n)) / 2) + 1;\n      cout << \"Caso \" << counter << \": \";\n      if (size == 1) cout << size << \" numero\" << endl;\n      else cout << size << \" numeros\" << endl;\n\n      for (int i = 0; i <= n; i++) {\n        if (i == 0) num = 1;\n        else num = i;\n        for (int j = 0; j < num; j++) {\n          cout << i;\n          if (i != n || j != num - 1) cout << \" \";\n        }\n      }\n    }\n\n    cout << endl << endl;\n    counter++;\n  }\n\n  return 0;\n}\n\n"
  },
  {
    "path": "competitive-programming/uri/seven.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2590\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n  cin.tie(NULL);\n  cout.sync_with_stdio(false);\n  long long int N, num;\n  cin >> N;\n\n  while (N--) {\n    cin >> num;\n\n    switch (num & 3) {\n      case 0:\n        cout << 1 << '\\n';\n        break;\n      case 1:\n        cout << 7 << '\\n';\n        break;\n      case 2:\n        cout << 9 << '\\n';\n        break;\n      case 3:\n        cout << 3 << '\\n';\n        break;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/several_scores_with_validation.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1118\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  int response = 1;\n  float grade1, grade2;\n\n  while (response != 2) {\n    while (true) {\n      cin >> grade1;\n      if (grade1 >= 0 && grade1 <= 10) break;\n      else cout << \"nota invalida\" << endl;\n    }\n\n    while (true) {\n      cin >> grade2;\n      if (grade2 >= 0 && grade2 <= 10) break;\n      else cout << \"nota invalida\" << endl;\n    }\n\n    cout << fixed << setprecision(2) << \"media = \" << (grade1 + grade2) / 2 << endl;\n\n    cout << \"novo calculo (1-sim 2-nao)\" << endl;\n    cin >> response;\n\n    while (response != 1 && response != 2) {\n      cout << \"novo calculo (1-sim 2-nao)\" << endl;\n      cin >> response;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/short_attendance.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1277\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nbool need_attendance(string attendance) {\n  double total = attendance.size(), present = 0.0, medical = 0.0;\n  for (double i = 0; i < attendance.size(); i++) {\n    if (attendance[i] == 'P') present++;\n    else if (attendance[i] == 'M') medical++;\n  }\n\n  total -= medical;\n\n  if (present / total >= 0.75) return false;\n  else return true;\n}\n\nint main() {\n\n  int n, num;\n  cin >> n;\n\n  while (n--) {\n    cin >> num;\n    if (num) {\n      string name, attendance;\n      bool first_name = true;\n      vector<string> students, stud;\n      vector<int> attendances;\n\n      for (int i = 0; i < num; i++) {\n        cin >> name;\n        students.push_back(name);\n      }\n\n      for (int i = 0; i < num; i++) {\n        cin >> attendance;\n        if (need_attendance(attendance)) stud.push_back(students[i]);\n      }\n\n      for (int i = 0; i < stud.size(); i++) {\n        if (first_name) {\n          cout << stud[i];\n          first_name = false;\n        } else {\n          cout << \" \" << stud[i];\n        }\n      }\n\n      cout << endl;\n    } else {\n      cout << endl;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/short_story.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1222\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\t\n\tint num_words, max_char_per_line, max_line_per_page, counter_char = 0, counter_lines = 0, counter_pages = 0;\n\tstring word;\n\tvector<string> words;\n\n\twhile (cin >> num_words >> max_line_per_page >> max_char_per_line) {\n\t\tfor (int i = 0; i < num_words; i++) {\n\t\t\tcin >> word;\n\t\t\twords.push_back(word);\n\t\t}\n\n\t\tfor (int i = 0; i < num_words; i++) {\n\t\t\tcounter_char += words[i].size();\n\n\t\t\tif (i+1 < num_words && counter_char < max_char_per_line) counter_char++;\t\t\n\t\t\t\n\t\t\tif (counter_char > max_char_per_line) {\n\t\t\t\tcounter_lines++;\n\t\t\t\tcounter_char = 0;\n\t\t\t\ti--;\n\t\t\t} else if (counter_char == max_char_per_line) {\n\t\t\t\tcounter_lines++;\n\t\t\t\tcounter_char = 0;\n\t\t\t}\n\n\t\t\tif (counter_lines >= max_line_per_page) {\n\t\t\t\tcounter_pages++;\n\t\t\t\tcounter_lines = 0;\n\t\t\t}\n\t\t}\n\n\t\tcounter_pages++;\n\n\t\tcout << counter_pages << endl;\n\n\t\tcounter_char = 0;\n\t\tcounter_lines = 0;\n\t\tcounter_pages = 0;\n\t\twords.clear();\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/simple_calculate.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1010\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  int code1, code2, unit1, unit2;\n  float price_per_unit1, price_per_unit2;\n\n  cin >> code1 >> unit1 >> price_per_unit1;\n  cin >> code2 >> unit2 >> price_per_unit2;\n\n  cout << fixed << setprecision(2) << \"VALOR A PAGAR: R$ \" << unit1 * price_per_unit1 + unit2 * price_per_unit2 << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/simple_factorial.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1153\n\n#include <iostream>\n\nusing namespace std;\n\nint fatorial(int n) {\n\tif (n == 1) return 1;\n\treturn n * fatorial(n - 1);\n}\n\nint main() {\n\t\n\tint n;\n\tcin >> n;\n\n\tcout << fatorial(n) << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/simple_prod.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1004\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int a, b;\n  cin >> a >> b;\n\n  cout << \"PROD = \" << a * b << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/simple_sort.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1042\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n1, n2, n3;\n\n\tcin >> n1 >> n2 >> n3;\n\n\tif (n1 < n2 && n1 < n3) {\n\t\tcout << n1 << endl;\n\t\tif (n2 < n3) {\n\t\t\tcout << n2 << endl;\n\t\t\tcout << n3 << endl;\n\t\t} else {\n\t\t\tcout << n3 << endl;\n\t\t\tcout << n2 << endl;\n\t\t}\n\t} else if (n2 < n3) {\n\t\tcout << n2 << endl;\n\t\tif (n1 < n3) {\n\t\t\tcout << n1 << endl;\n\t\t\tcout << n3 << endl;\n\t\t} else {\n\t\t\tcout << n3 << endl;\n\t\t\tcout << n1 << endl;\n\t\t}\n\t} else {\n\t\tcout << n3 << endl;\n\t\tif (n1 < n2) {\n\t\t\tcout << n1 << endl;\n\t\t\tcout << n2 << endl;\n\t\t} else {\n\t\t\tcout << n2 << endl;\n\t\t\tcout << n1 << endl;\n\t\t}\n\t}\t\n\n\tcout << endl << n1 << endl << n2 << endl << n3 << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/simple_sum.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1003\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int a, b;\n  cin >> a >> b;\n\n  cout << \"SOMA = \" << a + b << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/simulator.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2368\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\tint n1, n2, x, y;\n\tstring v;\n\tvector<int> nums;\n\n\tcin >> n1 >> n2;\n\n\tfor (int i = 1; i <= n1; i++) nums.push_back(i);\n\n\twhile (n2--) {\n\t\tcin >> v >> x >> y;\n\n\t\tif (v == \"I\") {\n\t\t\twhile (x < y) {\n\t\t\t\titer_swap(nums.begin() + x-1, nums.begin() + y-1);\n\t\t\t\tx++;\n\t\t\t\ty--;\n\t\t\t}\n\t\t} else {\n\t\t\tint sum = 0;\n\t\t\tfor (int i = x-1; i < y; i++) sum += nums[i];\n\t\t\tcout << sum << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/six_odd_numbers.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1070\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n, times=0;\n\tcin >> n;\n\n\twhile (times < 6) {\n\t\tif (n % 2 != 0) { \n\t\t\tcout << n << endl;\n\t\t\ttimes++;\n\t\t}\n\n\t\tn++;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/snack.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1038\n\n#include <iostream>\n#include <iomanip>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\n\tvector<double> ar;\n\tar.push_back(4.0);\n\tar.push_back(4.5);\n\tar.push_back(5.0);\n\tar.push_back(2.0);\n\tar.push_back(1.5);\n\n\tint n1, n2;\n\n\tcin >> n1 >> n2;\n\n\tcout << fixed << setprecision(2) << \"Total: R$ \" << ar[n1-1] * n2 << endl;\n\n\treturn 0;\n}\t"
  },
  {
    "path": "competitive-programming/uri/sort_by_length.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nvector<string> parse_string(string line) {\n\tvector<string> v;\n\tstring word = \"\";\n\t\n\tfor (int i = 0; i < line.size(); i++) {\n\t\tif (line[i] == ' ') {\n\t\t\tv.push_back(word);\n\t\t\tword.clear();\n\t\t} else if (i == line.size() - 1) {\n\t\t\tword += line[i];\n\t\t\tv.push_back(word);\n\t\t\tword.clear();\n\t\t} else {\n\t\t\tword += line[i];\n\t\t}\n\t}\n\t\n\treturn v;\n}\n\nvector<string> sort_by_size(vector<string> &v) {\n\tvector<string> new_v;\n\tint size = v.size();\n\t\n\twhile (size--) {\n\t\tint max_size = v[0].size(), index = 0;\n\t\tfor (int i = 1; i < v.size(); i++) {\n\t\t\tif (v[i].size() > max_size) {\n\t\t\t\tindex = i;\n\t\t\t\tmax_size = v[i].size();\n\t\t\t}\n\t\t}\n\n\t\tnew_v.push_back(v[index]);\n\t\tv.erase(v.begin() + index);\n\t}\n\t\n\treturn new_v;\n}\n\nint main() {\n\t\n\tstring s;\n\tint n;\n\tcin >> n;\n\tcin.ignore();\n\t\n\twhile (n--) {\n\t\tgetline(cin, s);\n\t\tvector<string> strings = parse_string(s);\n\t\tvector<string> sorted_strings = sort_by_size(strings);\n\t\n\t\tfor (int i = 0; i < sorted_strings.size()-1; i++) cout << sorted_strings[i] << \" \";\n\t\tcout << sorted_strings[sorted_strings.size()-1] << endl;\n\t}\n\t\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/sort_sort_and_sort.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1252\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nbool sortBy(const pair<int, int> &pair1, const pair<int, int> &pair2) {\n\tif (pair1.first > pair2.first) {\n\t\treturn false;\n\t} else if (pair1.first < pair2.first) {\n\t\treturn true;\n\t} else {\n\t\tif (pair1.second % 2 == 0 && pair2.second % 2 == 0) {\n\t\t\treturn pair1.second < pair2.second;\n\t\t} else if (pair1.second % 2 != 0 && pair2.second % 2 != 0) {\n\t\t\treturn pair1.second > pair2.second;\n\t\t} else if (pair1.second % 2 != 0 && pair2.second % 2 == 0) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n}\n\nint main() {\n\tint n, m, x;\n\n\twhile (cin >> n >> m && n + m != 0) {\n\t\tvector< pair<int, int> > v;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> x;\n\t\t\tv.push_back(make_pair(x % m, x));\n\t\t}\n\n\t\tsort(v.begin(), v.end(), sortBy);\n\n\t\tcout << n << \" \" << m << endl;\n\t\tfor (int i = 0; i < v.size(); i++) cout << v[i].second << endl;\n\t}\n\n\tcout << 0 << \" \" << 0 << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/sphere.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1011\n\n#include <iostream>\n#include <math.h>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n\tconst double PI = 3.14159;\n\tint n;\n\tcin >> n;\n\n\tcout << fixed << setprecision(3) << \"VOLUME = \" << (4.0 / 3) * PI * pow(n, 3) << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/spurs_rock.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1303\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nstruct team {\n  int id;\n  int points;\n  float scores;\n  float scoresConceded;\n  int games;\n};\n\nbool untie(const team &t1, const team &t2) {\n  if (t1.points > t2.points) return true;\n  else if (t1.points < t2.points) return false;\n  else {\n    float team1AverageBasket, team2AverageBasket;\n\n    if (t1.scoresConceded) team1AverageBasket = t1.scores / t1.scoresConceded;\n    else team1AverageBasket = t1.scores;\n\n    if (t2.scoresConceded) team2AverageBasket = t2.scores / t2.scoresConceded;\n    else team2AverageBasket = t2.scores;\n\n    if (team1AverageBasket > team2AverageBasket) return true;\n    else if (team1AverageBasket < team2AverageBasket) return false;\n    else {\n      if (t1.points > t2.points) return true;\n      else if (t1.points < t2.points) return false;\n      else {\n        if (t1.games < t2.games) return true;\n        else if (t1.games > t2.games) return false;\n      }\n    }\n  }\n}\n\nint main() {\n  int n, p1, p2, instance=1;\n  float score1, score2;\n  cin >> n;\n\n  while (n) {\n    vector<team> teams;\n    map<int, team> t;\n\n    for (int i = 0; i < n * (n-1) / 2; i++) {\n      cin >> p1 >> score1 >> p2 >> score2;\n\n      if (score1 > score2) {\n        if (t.find(p1) != t.end()) {\n          t[p1].points += 2;\n          t[p1].scores += score1;\n          t[p1].scoresConceded += score2;\n          t[p1].games++;\n          if (t.find(p2) != t.end()) {\n            t[p2].points++;\n            t[p2].scores += score2;\n            t[p2].scoresConceded += score1;\n            t[p2].games++;\n          } else {\n            team te;\n            te.id = p2;\n            te.points = 1;\n            te.scores = score2;\n            te.scoresConceded = score1;\n            te.games = 1;\n            t[p2] = te;\n          }\n        } else {\n          team te;\n          te.id = p1;\n          te.points = 2;\n          te.scores = score1;\n          te.scoresConceded = score2;\n          te.games = 1;\n          t[p1] = te;\n          if (t.find(p2) != t.end()) {\n            t[p2].points++;\n            t[p2].scores += score2;\n            t[p2].scoresConceded += score1;\n            t[p2].games++;\n          } else {\n            team te;\n            te.id = p2;\n            te.points = 1;\n            te.scores = score2;\n            te.scoresConceded = score1;\n            te.games = 1;\n            t[p2] = te;\n          }\n        }\n      } else if (score1 < score2) {\n        if (t.find(p1) != t.end()) {\n          t[p1].points++;\n          t[p1].scores += score1;\n          t[p1].scoresConceded += score2;\n          t[p1].games++;\n          if (t.find(p2) != t.end()) {\n            t[p2].points += 2;\n            t[p2].scores += score2;\n            t[p2].scoresConceded += score1;\n            t[p2].games++;\n          } else {\n            team te;\n            te.id = p2;\n            te.points = 2;\n            te.scores = score2;\n            te.scoresConceded = score1;\n            te.games = 1;\n            t[p2] = te;\n          }\n        } else {\n          team te;\n          te.id = p1;\n          te.points = 1;\n          te.scores = score1;\n          te.scoresConceded = score2;\n          te.games = 1;\n          t[p1] = te;\n          if (t.find(p2) != t.end()) {\n            t[p2].points += 2;\n            t[p2].scores += score2;\n            t[p2].scoresConceded += score1;\n            t[p2].games++;\n          } else {\n            team te;\n            te.id = p2;\n            te.points = 2;\n            te.scores = score2;\n            te.scoresConceded += score1;\n            te.games = 1;\n            t[p2] = te;\n          }\n        }\n      }\n    }\n\n    for (map<int, team>::iterator it = t.begin(); it != t.end(); ++it) {\n      teams.push_back(it->second);\n    }\n\n    sort(teams.begin(), teams.end(), untie);\n\n    cout << \"Instancia \" << instance << endl;\n\n    cout << teams[0].id;\n    for (int i = 1; i < teams.size(); i++) {\n      cout << \" \" << teams[i].id;\n    }\n    cout << endl;\n\n    instance++;\n    cin >> n;\n    if (n) cout << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/square_array_4.cpp",
    "content": "#include <iostream>\n#include <string>\nusing namespace std;\n\nvoid generateFirstStep(int n, int x) {\n\tfor (int i = 0; i < x; i++) {\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tif (i == j) cout << \"2\";\n\t\t\telse if (n-i-1 == j) cout << \"3\";\n\t\t\telse cout << \"0\";\n\t\t}\n\t\tcout << endl;\n\t}\n}\n\nvoid generateSecondStep(int n, int x) {\n\tint medi = (n-x-x) / 2;\n\tint medj = n / 2;\n\tfor (int i = 0; i < n-x-x; i++) {\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tif (medi == i && medj == j) cout << \"4\";\n\t\t\telse if (j >= x && j < n-x) cout << \"1\";\n\t\t\telse cout << \"0\";\n\t\t}\n\t\tcout << endl;\n\t}\n}\n\nvoid generateThirdStep(int n, int x) {\n\tfor (int i = n-x; i < n; i++) {\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tif (i == j) cout << \"2\";\n\t\t\telse if (n-i-1 == j) cout << \"3\";\n\t\t\telse cout << \"0\";\n\t\t}\n\t\tcout << endl;\n\t}\n}\n\nint main() {\n\tint n, x;\n\t\n\twhile (cin >> n) {\n\t\tx = n / 3;\n\t\tgenerateFirstStep(n, x);\n\t\tgenerateSecondStep(n, x);\n\t\tgenerateThirdStep(n, x);\n\t\tcout << endl;\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/square_game.cpp",
    "content": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, m, q, t, greatest = 0;\n\tint grid[205][205];\n\tint dp[205][205];\n\t\n\tmemset(dp, 0, sizeof dp);\n\n\tcin >> n >> m;\n\n\tfor (int i = 1; i <= n; i++) {\n\t\tfor (int j = 1; j <= m; j++) {\n\t\t\tcin >> grid[i][j];\n\t\t\t\n\t\t\tif (grid[i][j] == 0) dp[i][j] = 0;\n\t\t\telse {\n\t\t\t\tdp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1;\n\t\t\t\tgreatest = max(greatest, dp[i][j]);\n\t\t\t}\n\t\t}\n\t}\n\n\tcin >> q;\n\n\twhile (q--) {\n\t\tcin >> t;\n\t\t\n\t\tif (t <= greatest) cout << \"yes\" << endl;\n\t\telse cout << \"no\" << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/square_matrix_1.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1435\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint get_limit(int n) {\n  int limit = 0;\n  for (int i = 0; i < n; i += 2) limit++;\n  return limit;\n}\n\nint main() {\n\n  int n;\n  cin >> n;\n\n  while (n != 0) {\n\n    vector<int> v;\n    vector< vector<int> > table;\n\n    for (int i = 0; i < n; i++) {\n      for (int j = 0; j < n; j++) v.push_back(0);\n      table.push_back(v);\n    }\n\n    int start = 0;\n    int limit = get_limit(n);\n\n    while (start < limit) {\n      for (int i = start; i < n-start; i++) {\n        for (int j = start; j < n-start; j++) table[i][j]++;\n      }\n\n      start++;\n    }\n\n    for (int i = 0; i < n; i++) {\n      for (int j = 0; j < n; j++) {\n        if (table[i][j] <= 9) cout << \"  \";\n        else if (table[i][j] <= 99) cout << \" \";\n        cout << table[i][j];\n        if (j < n-1) cout << \" \";\n      }\n      cout << endl;\n    }\n\n    cout << endl;\n    cin >> n;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/square_matrix_2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1478\n\n#include <iostream>\n\nusing namespace std;\n\nstring generateSpaces(int n) {\n\tif (n >= 1 && n <= 9) return \"  \";\n\telse if (n >= 10 && n <= 99) return \" \";\n\telse return \"\";\n}\n\nint main() {\n\tint n, startIndex, des;\n\n\twhile (cin >> n && n) {\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tdes = i;\n\t\t\tstartIndex = 1;\n\t\t\tfor (int j = 1; j <= n; j++) {\n\t\t\t\tif (des >= 2) {\n\t\t\t\t\tif (j != 1) cout << \" \";\n\t\t\t\t\tcout << generateSpaces(des) << des;\n\t\t\t\t\tdes--;\n\t\t\t\t} else {\n\t\t\t\t\tif (j != 1) cout << \" \";\n\t\t\t\t\tcout << generateSpaces(startIndex) << startIndex;\n\t\t\t\t\tstartIndex++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n\n\t\tcout << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/square_matrix_3.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1557\n\n#include <iostream>\n#include <vector>\n#include <math.h>\n\nusing namespace std;\n\nint getNumberOfDigits(int n) {\n  int counter = 0;\n  while (n) {\n    counter++;\n    n /= 10;    \n  }\n\n  return counter;\n}\n\nstring generateSpaces(int n, int t) {\n  int diff = t - getNumberOfDigits(n);\n  string s = \"\";\n  for (int i = 0; i < diff; i++) s += \" \";\n  return s;\n}\n\nint main() {\n  int n, num, t;\n\n  while (cin >> n && n) {\n    vector<int> v;\n    vector< vector<int> > matrix;\n\n    for (int i = 0; i < n; i++) {\n      num = pow(2, i);\n      v.push_back(num);\n      for (int j = 1; j < n; j++) {\n        num *= 2;\n        v.push_back(num);\n      }\n\n      matrix.push_back(v);\n      v.clear();\n    }\n\n    t = getNumberOfDigits(matrix[n-1][n-1]);\n\n    for (int i = 0; i < n; i++) {\n      for (int j = 0; j < n; j++) {\n        if (j == n-1) cout << generateSpaces(matrix[i][j], t) << matrix[i][j];\n        else cout << generateSpaces(matrix[i][j], t) << matrix[i][j] << \" \";\n      }\n\n      cout << endl;\n    }\n\n    cout << endl;\n  }\n\n  return 0;\n}"
  },
  {
    "path": "competitive-programming/uri/square_root_of_10.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2161\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\ndouble rootNumber(int n1, int n2) {\n  if (n1 == n2) return 6.0;\n  return 6 + 1.0 / rootNumber(n1+1, n2);\n}\n\nint main() {\n  int n;\n  cin >> n;\n  if (n) cout << fixed << setprecision(10) << 3.0 + 1.0 / rootNumber(1, n) << endl;\n  else cout << fixed << setprecision(10) << 3.0 << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/square_root_of_2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2166\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\ndouble rootNumber(int n1, int n2) {\n  if (n1 == n2) return 2.0;\n  return 2 + 1.0 / rootNumber(n1+1, n2);\n}\n\nint main() {\n  int n;\n  cin >> n;\n  if (n) cout << fixed << setprecision(10) << 1.0 + 1.0 / rootNumber(1, n) << endl;\n  else cout << fixed << setprecision(10) << 1.0 << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/square_spiral.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1868\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, x, y, num;\n\tcin >> n;\n\n\twhile (n != 0) {\n\t\tstring s;\n\t\tvector<string> v;\n\n\t\tfor (int i = 0; i < n; i++) s += \"O\";\n\t\tfor (int j = 0; j < n; j++) v.push_back(s);\n\n\t\tx = (n / 2);\n\t\ty = x;\n\t\tnum = (n * n) - 1;\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tif (i == x && j == y) cout << \"X\";\n\t\t\t\telse cout << \"O\";\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n\n\t\tcout << \"@\" << endl;\n\t\ty++;\n\n\t\tint direction = 2; // up\n\t\tint counter = 0, dist = 1, count = 0;\n\n\t\twhile (num--) {\n\t\t\tcounter++;\n\t\t\tcount++;\n\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\t\tif (i == x && j == y) cout << \"X\";\n\t\t\t\t\telse cout << \"O\";\n\t\t\t\t}\n\t\t\t\tcout << endl;\n\t\t\t}\n\n\t\t\tcout << \"@\" << endl;\n\n\t\t\tif (counter == dist * 2) {\n\t\t\t\tcounter = 0;\n\t\t\t\tdist++;\t\t\t\t\n\t\t\t}\t\t\t\n\n\t\t\tif (direction == 1) y++;\n\t\t\telse if (direction == 2) x--;\n\t\t\telse if (direction == 3) y--;\n\t\t\telse x++;\n\n\t\t\tif (count == dist) {\n\t\t\t\tcount = 0;\n\t\t\t\tif (direction == 1) direction = 2; // up\n\t\t\t\telse if (direction == 2) direction = 3; // left\n\t\t\t\telse if (direction == 3) direction = 4; // down\n\t\t\t\telse direction = 1; // right\n\t\t\t}\n\t\t}\n\n\t\tcin >> n;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/squared_and_cubic.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1143\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\n\tcin >> n;\n\n\tfor (int i = 1; i <= n; i++) {\n\t\tcout << i << \" \" << i * i << \" \" << i * i * i << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/ssn_1.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1769\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint to_digit(char num) {\n\treturn num - '0';\n}\n\nint main() {\n\t\n\tstring cpf;\n\n\twhile (cin >> cpf) {\n\t\tint total1 = 0, num, total2 = 0, c1 = 1, c2 = 9;\n\t\tfor (int i = 0; i < 11; i++) {\n\t\t\tif (cpf[i] != '.') {\n\t\t\t\tnum = to_digit(cpf[i]);\n\t\t\t\ttotal1 += num * c1;\n\t\t\t\ttotal2 += num * c2;\n\t\t\t\tc1++;\n\t\t\t\tc2--;\n\t\t\t}\n\t\t}\n\n\t\tint rem1 = total1 % 11;\n\t\tint rem2 = total2 % 11;\n\n\t\tif (rem1 == 10 && rem2 == 10) {\n\t\t\tif (cpf[12] == '0' && cpf[13] == '0') cout << \"CPF valido\" << endl;\n\t\t\telse cout << \"CPF invalido\" << endl;\n\t\t} else if (rem1 == 10) {\n\t\t\tif (cpf[12] == '0' && rem2 == to_digit(cpf[13])) cout << \"CPF valido\" << endl;\n\t\t\telse cout << \"CPF invalido\" << endl;\n\t\t} else if (rem2 == 10) {\n\t\t\tif (rem1 == to_digit(cpf[12]) && cpf[13] == '0') cout << \"CPF valido\" << endl;\n\t\t\telse cout << \"CPF invalido\" << endl;\n\t\t} else if (rem1 == to_digit(cpf[12]) && rem2 == to_digit(cpf[13])) {\n\t\t\tcout << \"CPF valido\" << endl;\n\t\t} else {\n\t\t\tcout << \"CPF invalido\" << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/star_trek.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1973\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\n  long long int n, x, total=0, total_capture=0, start_counter=0;\n  cin >> n;\n\n  vector<int> v;\n  vector<int> v1;\n\n  for (int i = 1; i <= n; i++) {\n    cin >> x;\n    total += x;\n    v.push_back(x);\n    v1.push_back(1);\n  }\n\n  int i = 0;\n\n  while (true) {\n    cout << v[i] << endl;\n    if (v[i] == 0 || i < 0 || i >= n) break;\n\n    v1.at(i) = 0;\n    int j = i;\n\n    if (v[i] % 2 == 0) i--;\n    else i++;\n\n    v[j]--;\n    total_capture++;\n    j = i;\n  }\n\n  for (int i = 0; i < n; i++) if (v1[i] == 0) start_counter++;\n\n  cout << start_counter << \" \" << total - total_capture << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/start_grid.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1228\n\n#include <iostream>\n\n#define swap(a, b) { int x=a; a=b; b=x; }\n\nusing namespace std;\n\nint main() {\n\tint n, num, passing;\n\tint start[25], finish[25], mapper[25];\n\n\twhile (cin >> n) {\n\t\tpassing = 0;\n\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tcin >> num;\n\t\t\tstart[i] = num;\n\t\t}\n\t\t\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tcin >> num;\n\t\t\tfinish[i] = num;\n\t\t}\n\n\t\tfor (int i = 1; i <= n; i++) mapper[finish[i]] = i;\n\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfor (int j = i+1; j <= n; j++) {\n\t\t\t\tif (mapper[start[i]] > mapper[start[j]]) {\n\t\t\t\t\tswap(mapper[start[i]], mapper[start[j]]);\n\t\t\t\t\tpassing++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcout << passing << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/stick_collector_robot.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1121\n\n#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nbool isInsideGrid(int x, int y, int lines, int columns) {\n\tif (x < 0 || y < 0 || x >= columns || y >= lines) return false;\n\treturn true;\n}\n\nint main() {\n\tint lines, columns, instructionsNumber, x, y;\n\tstring instructions;\n\tchar orientation;\n\n\twhile (cin >> lines >> columns >> instructionsNumber && lines + columns + instructionsNumber != 0) {\n\t\tvector<string> grid;\n\t\tstring line;\n\t\tcin.ignore();\n\n\t\tfor (int i = 0; i < lines; i++) {\n\t\t\tgetline(cin, line);\n\t\t\tgrid.push_back(line);\n\t\t}\t\t\n\t\t\t\t\n\t\tgetline(cin, instructions);\n\n\t\tfor (int i = 0; i < lines; i++) {\n\t\t\tfor (int j = 0; j < columns; j++) {\n\t\t\t\tif (grid[i][j] == 'N') {\n\t\t\t\t\torientation = 'N';\n\t\t\t\t\tx = j;\n\t\t\t\t\ty = i;\n\t\t\t\t} else if (grid[i][j] == 'S') {\n\t\t\t\t\torientation = 'S';\n\t\t\t\t\tx = j;\n\t\t\t\t\ty = i;\n\t\t\t\t} else if (grid[i][j] == 'L') {\n\t\t\t\t\torientation = 'L';\n\t\t\t\t\tx = j;\n\t\t\t\t\ty = i;\n\t\t\t\t} else if (grid[i][j] == 'O') {\n\t\t\t\t\torientation = 'O';\n\t\t\t\t\tx = j;\n\t\t\t\t\ty = i;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tint figuresNumber = 0;\n\t\tgrid[y][x] = '.';\n\n\t\tfor (int i = 0; i < instructions.size(); i++) {\n\t\t\tif (orientation == 'N') {\n\t\t\t\tif (instructions[i] == 'D') orientation = 'L';\n\t\t\t\telse if (instructions[i] == 'E') orientation = 'O';\n\t\t\t\telse {\n\t\t\t\t\tif (isInsideGrid(x, y-1, lines, columns)) {\n\t\t\t\t\t\tif (grid[y-1][x] == '.') y--;\n\t\t\t\t\t\telse if (grid[y-1][x] == '*') {\n\t\t\t\t\t\t\tgrid[y-1][x] = '.';\n\t\t\t\t\t\t\ty--;\n\t\t\t\t\t\t\tfiguresNumber++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (orientation == 'S') {\n\t\t\t\tif (instructions[i] == 'D') orientation = 'O';\n\t\t\t\telse if (instructions[i] == 'E') orientation = 'L';\n\t\t\t\telse {\n\t\t\t\t\tif (isInsideGrid(x, y+1, lines, columns)) {\n\t\t\t\t\t\tif (grid[y+1][x] == '.') y++;\n\t\t\t\t\t\telse if (grid[y+1][x] == '*') {\n\t\t\t\t\t\t\tgrid[y+1][x] = '.';\n\t\t\t\t\t\t\ty++;\n\t\t\t\t\t\t\tfiguresNumber++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (orientation == 'L') {\n\t\t\t\tif (instructions[i] == 'D') orientation = 'S';\n\t\t\t\telse if (instructions[i] == 'E') orientation = 'N';\n\t\t\t\telse {\n\t\t\t\t\tif (isInsideGrid(x+1, y, lines, columns)) {\n\t\t\t\t\t\tif (grid[y][x+1] == '.') x++;\n\t\t\t\t\t\telse if (grid[y][x+1] == '*') {\n\t\t\t\t\t\t\tgrid[y][x+1] = '.';\n\t\t\t\t\t\t\tx++;\n\t\t\t\t\t\t\tfiguresNumber++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (instructions[i] == 'D') orientation = 'N';\n\t\t\t\telse if (instructions[i] == 'E') orientation = 'S';\n\t\t\t\telse {\n\t\t\t\t\tif (isInsideGrid(x-1, y, lines, columns)) {\n\t\t\t\t\t\tif (grid[y][x-1] == '.') x--;\n\t\t\t\t\t\telse if (grid[y][x-1] == '*') {\n\t\t\t\t\t\t\tgrid[y][x-1] = '.';\n\t\t\t\t\t\t\tx--;\n\t\t\t\t\t\t\tfiguresNumber++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t}\n\n\t\tcout << figuresNumber << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/sticks_game.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1366\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, size, quant, total, result;\n\n\twhile (cin >> n && n != 0) {\n\t\ttotal = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> size >> quant;\n\t\t\tif (quant % 2 != 0) quant--;\n\t\t\ttotal += quant;\n\t\t}\n\n\t\tresult = total / 4;\n\t\tcout << result << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/strategy_game.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1940\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\t\n\tvector<int> v;\n\tint players, rounds, temp;\n\tcin >> players >> rounds;\n\t\n\tfor (int i = 0; i < players; i++) v.push_back(0);\n\t\n\tfor (int i = 0; i < rounds; i++) {\n\t\tfor (int j = 0; j < players; j++) {\n\t\t\tcin >> temp;\n\t\t\tv[j] += temp;\n\t\t}\n\t}\n\t\n\tint winner = 1, greater = v[0];\n\t\n\tfor (int i = 1; i < players; i++) {\n\t\tif (v[i] >= greater) {\n\t\t\tgreater = v[i];\n\t\t\twinner = i+1;\n\t\t}\n\t}\n\t\n\tcout << winner << endl;\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/subprime.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1105\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nstruct bank {\n\tint code;\n\tint money;\n\tint owing;\n};\n\nint main() {\t\n\tint n1, n2, m, debtor, creditor, value;\n\tcin >> n1 >> n2;\n\n\twhile (n1 + n2 != 0) {\n\t\tvector<bank> banks;\n\t\tbool pos_liqui = true;\n\n\t\tfor (int i = 0; i < n1; i++) {\n\t\t\tcin >> m;\n\t\t\tbank b;\n\t\t\tb.code = i;\n\t\t\tb.money = m;\n\t\t\tbanks.push_back(b);\n\t\t}\n\n\t\tfor (int j = 0; j < n2; j++) {\n\t\t\tcin >> debtor >> creditor >> value;\n\t\t\tbanks[debtor-1].owing += value;\n\t\t\tbanks[creditor-1].money += value;\n\t\t}\n\n\t\tfor (int k = 0; k < n1; k++) {\n\t\t\tcout << \"Money: \" << banks[k].money << \" | Owing: \" << banks[k].owing << endl;\n\t\t\tif (banks[k].owing > banks[k].money) {\n\t\t\t\tpos_liqui = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (pos_liqui) cout << \"S\" << endl;\n\t\telse cout << \"N\" << endl;\n\n\t\tcin >> n1 >> n2;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/sucessor_par.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n    long long int X;\n    cin >> X;\n    if (X % 2 == 0) cout << X + 2 << endl;\n    else cout << X + 1 << endl;\n    return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/sudoku.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1383\n\n#include <iostream>\n#include <vector>\n#include <map>\n#include <set>\n\nusing namespace std;\n\nbool correct_mini_matrix(vector< vector<int> > &sudoku, int x, int y) {\n\tint limit_x = x + 3, limit_y = y + 3;\n\tset<int> s;\n\n\tfor (int i = x; i < limit_x; i++) {\n\t\tfor (int j = y; j < limit_y; j++) {\n\t\t\ts.insert(sudoku[i][j]);\n\t\t}\n\t}\n\n\tint size = s.size();\n\n\tif (size == 9) return true;\n\treturn false;\n}\n\nbool correct_horizontal_line(vector< vector<int> > &sudoku) {\n\tset<int> s;\n\n\tfor (int i = 0; i < 9; i++) {\n\t\tfor (int j = 0; j < 9; j++) {\n\t\t\ts.insert(sudoku[i][j]);\n\t\t}\n\n\t\tif (s.size() != 9) return false;\n\t\ts.clear();\n\t}\n\n\treturn true;\n}\n\nbool correct_vertical_line(vector< vector<int> > &sudoku) {\n\tset<int> s;\n\n\tfor (int i = 0; i < 9; i++) {\n\t\tfor (int j = 0; j < 9; j++) {\n\t\t\ts.insert(sudoku[j][i]);\n\t\t}\n\n\t\tif (s.size() != 9) return false;\n\t\ts.clear();\n\t}\n\n\treturn true;\n}\n\nint main() {\n\tint instance = 1;\n\tvector<int> v;\n\tvector< vector<int> > sudoku;\n\tint n, temp;\n\n\tcin >> n;\n\n\twhile (n--) {\n\t\tbool correct_sudoku = true;\t\t\n\t\tfor (int i = 0; i < 9; i++) {\n\t\t\tfor (int j = 0; j < 9; j++) {\n\t\t\t\tcin >> temp;\n\t\t\t\tv.push_back(temp);\n\t\t\t}\n\n\t\t\tsudoku.push_back(v);\n\t\t\tv.clear();\n\t\t}\n\n\t\tfor (int i = 0; i < 9; i += 3) {\n\t\t\tfor (int j = 0; j < 9; j += 3) {\n\t\t\t\tif (!correct_mini_matrix(sudoku, i, j)) {\n\t\t\t\t\tcorrect_sudoku = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcout << \"Instancia \" << instance << endl;\n\n\t\tif (correct_sudoku && correct_horizontal_line(sudoku) && correct_vertical_line(sudoku)) {\n\t\t\tcout << \"SIM\" << endl << endl;\n\t\t} else {\n\t\t\tcout << \"NAO\" << endl << endl;\n\t\t}\n\n\t\tsudoku.clear();\n\t\tinstance++;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/sum_of_consecutive_even_numbers.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1159\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n, total=0, counter=0;\n\n\tcin >> n;\n\n\twhile (n != 0) {\n\n\t\twhile (counter < 5) {\n\t\t\tif (n % 2 == 0) {\n\t\t\t\ttotal += n;\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t\tn++;\t\t\t\n\t\t}\n\n\t\tcout << total << endl;\n\t\tcounter = 0;\n\t\ttotal=0;\n\t\tcin >> n;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/sum_of_consecutive_odd_numbers_3.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1158\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int n, n1, n2, counter=0, total=0;\n\n  cin >> n;\n\n  while (n--) {\n    cin >> n1 >> n2;\n\n    while (true) {\n      if (n1 % 2 != 0) {\n        total += n1;\n        counter++;\n      }\n\n      if (counter == n2) {\n        break;\n      }\n\n      n1++;\n    }\n\n    cout << total << endl;\n    counter = 0;\n    total = 0;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/sum_of_consecutive_odd_numbers_I.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1071\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n1, n2, total=0;\n\n\tcin >> n1 >> n2;\n\n\tif (n1 == n2) {\n\t\tcout << 0 << endl;\n\t} else if (n1 > n2) {\n\t\tfor (int i = n2; i < n1; i++) {\n\t\t\tif (i < 0) i = i * (-1);\n\t\t\tif (i % 2 != 0) total++;\n\t\t}\n\n\t\tcout << total << endl;\n\t} else {\n\t\tfor (int i = n1; i < n2; i++) {\n\t\t\tif (i < 0) i = i * (-1);\n\t\t\tif (i % 2 != 0) total++;\n\t\t}\n\n\t\tcout << total << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/sum_of_consecutive_odd_numbers_II.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1099\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n, x, y, total=0;\n\n\tcin >> n;\n\n\twhile(n--) {\n\t\tcin >> x >> y;\n\t\tif (x > y) {\n\t\t\tfor (int i = y+1; i < x; i++) {\n\t\t\t\tif (i % 2 != 0) {\t\t\t\t\n\t\t\t\t\ttotal += i;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (y > x) {\n\t\t\tfor (int i = x+1; i < y; i++) {\n\t\t\t\tif (i % 2 != 0) {\n\t\t\t\t\ttotal += i;\n\t\t\t\t}\n\t\t\t}\t\t\n\t\t}\n\n\t\tif (total > 0) {\n\t\t\tcout << total << endl;\n\t\t} else {\n\t\t\tcout << 0 << endl;\n\t\t}\n\n\t\ttotal = 0;\n\t}\t\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/sum_of_two_squares.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1558\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <math.h>\n\nusing namespace std;\n\nbool is_int(float n) {\n\tint num = n;\n\tif (num == n) return true;\n\treturn false;\n}\n\nint main() {\n\t\n\tint n;\n\t\n\twhile (cin >> n) {\n\t\tunsigned int n1, n2;\n\t\tfloat res;\n\t\tstring response = \"NO\";\n\n\t\tfor (int i = 1; pow(i, 2) < n; i++) {\n\t\t\tn1 = pow(i, 2);\n\t\t\tn2 = n - n1;\n\t\t\tres = sqrt(n2);\n\t\t\tif (is_int(res)) {\n\t\t\t\tresponse = \"YES\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcout << response << endl;\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/summer_camp.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1167\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n\nusing namespace std;\n\nstruct student {\n  string studentName;\n  int tokenNumber;\n  bool eliminated;\n};\n\nint updateStartIndexOnClockWise(vector<student> &students, int startIndex) {\n  int maximumStudentsEliminated = students.size() - 1;\n\n  if (students[startIndex].tokenNumber % 2 == 0) {\n    while (students[startIndex].eliminated) {\n      startIndex--;\n      if (startIndex > maximumStudentsEliminated) startIndex = 0;\n    }\n  } else {\n    while (students[startIndex].eliminated) {\n      startIndex++;\n      if (startIndex > maximumStudentsEliminated) startIndex = 0;\n    }\n  }\n\n  return startIndex;\n}\n\nint updateStartIndexOnCounterClockWise(vector<student> &students, int startIndex) {\n  int maximumStudentsEliminated = students.size() - 1;\n\n  if (students[startIndex].tokenNumber % 2 == 0) {\n    while (students[startIndex].eliminated) {\n      startIndex++;\n      if (startIndex > maximumStudentsEliminated) startIndex = 0;\n    }\n  } else {\n    while (students[startIndex].eliminated) {\n      startIndex--;\n      if (startIndex > maximumStudentsEliminated) startIndex = 0;\n    }\n  }\n\n  return startIndex;\n}\n\nint main() {\n  int n, tokenNumber;\n  string studentName;\n\n  while (cin >> n && n != 0) {\n    vector<student> students;\n\n    while (n--) {\n      cin >> studentName >> tokenNumber;\n      student s;\n      s.studentName = studentName;\n      s.tokenNumber = tokenNumber;\n      s.eliminated = false;\n      students.push_back(s);\n    }\n\n    int counter = students[0].tokenNumber;\n    int maximumStudentsEliminated = students.size() - 1;\n    int studentsEliminated = 0;\n    int startIndex = 0;\n    bool onClockWise;\n\n    if (counter % 2 != 0) onClockWise = true;\n    else onClockWise = false;\n\n    while (studentsEliminated < maximumStudentsEliminated) {\n      while (counter--) {\n        if (onClockWise) startIndex++;\n        else startIndex--;\n        if (startIndex > maximumStudentsEliminated) startIndex = 0;\n        else if (startIndex < 0) startIndex = students.size() - 1;\n\n        while (students[startIndex].eliminated) {\n          if (onClockWise) startIndex++;\n          else startIndex--;\n          if (startIndex > maximumStudentsEliminated) startIndex = 0;\n          else if (startIndex < 0) startIndex = students.size() - 1;\n        }\n      }\n\n      students[startIndex].eliminated = true;\n      counter = students[startIndex].tokenNumber;\n      studentsEliminated++;\n      if (counter % 2 != 0) onClockWise = true;\n      else onClockWise = false;\n    }\n\n    for (int i = 0; i < students.size(); i++) {\n      if (!students[i].eliminated)\n        cout << \"Vencedor(a): \" << students[i].studentName << endl;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/summing_consecutive_integers.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1149\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n1, n2, total=0;\n\n\tcin >> n1 >> n2;\n\n\twhile (n2 <= 0) {\n\t\tcin >> n2;\n\t}\n\n\twhile (n2--) {\n\t\ttotal += n1;\n\t\tn1++;\n\t}\n\n\tcout << total << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/sunday_morning.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2003\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint get_minutes(string minutes) {\n  string numbers = \"0123456789\";\n  int min = 0;\n  min += 10 * numbers.find(minutes[0]);\n  min += numbers.find(minutes[1]);\n  return min;\n}\n\nint main() {\n\n  string hour, minutes, s;\n\n  while (cin >> s) {\n    hour = s.substr(0, 1);\n    minutes = s.substr(2, 2);\n\n    if (hour == \"5\" || hour == \"6\" || (hour == \"7\" && minutes == \"00\")) {\n      cout << \"Atraso maximo: 0\" << endl;\n    } else {\n      if (hour == \"7\") {\n        cout << \"Atraso maximo: \" << get_minutes(minutes) << endl;\n      } else if (hour == \"8\") {\n        cout << \"Atraso maximo: \" << 60 + get_minutes(minutes) << endl;\n      } else if (hour == \"9\") {\n        cout << \"Atraso maximo: 120\" << endl;\n      }\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/superior_area.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1187\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n  vector< vector<double> > v1;\n  double n, total=0;\n  string operation;\n\n  cin >> operation;\n\n  for (int i = 0; i < 12; i++) {\n    vector<double> v;\n\n    for (int j = 0; j < 12; j++) {\n      cin >> n;\n      v.push_back(n);\n    }\n\n    v1.push_back(v);\n  }\n\n  int counter1=1, counter2=11, count = 0;\n\n  for (int i = 0; i < 5; i++) {\n    for (int j = counter1; j < counter2; j++) {\n      total += v1[i][j];\n      count++;\n    }\n\n    counter1++;\n    counter2--;\n  }\n\n  if (operation == \"S\") cout << fixed << setprecision(1) << total << endl;\n  else cout << fixed << setprecision(1) << total / count << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/system_of_download.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nint main() {\n  int N, X, Y;\n  vector<string> V;\n  cin >> N;\n\n  V.push_back(\"PROXYCITY\");\n  V.push_back(\"P.Y.N.G.\");\n  V.push_back(\"DNSUEY!\");\n  V.push_back(\"SERVERS\");\n  V.push_back(\"HOST!\");\n  V.push_back(\"CRIPTONIZE\");\n  V.push_back(\"OFFLINE DAY\");\n  V.push_back(\"SALT\");\n  V.push_back(\"ANSWER!\");\n  V.push_back(\"RAR?\");\n  V.push_back(\"WIFI ANTENNAS\");\n\n  while (N--) {\n    cin >> X >> Y;\n    cout << V[X+Y] << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/taxes_of_project.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2170\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\tint project = 1;\n\tdouble n1, n2, result;\n\n\twhile (cin >> n1 >> n2) {\n\t\tresult = ((n2 - n1) / n1) * 100.00;\n\t\tcout << fixed << setprecision(2) << \"Projeto \" << project << \":\" << endl << \"Percentual dos juros da aplicacao: \" << result << \" %\" << endl << endl;\n\t\tproject++;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/tda_rational_1.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1022\n\n#include <iostream>\n\nusing namespace std;\n\nint lcm(int num1, int num2) {\n\tint n1 = num1, n2 = num2, remainder;\n\n\tdo {\n\t\tremainder = n1 % n2;\n\t\tn1 = n2;\n\t\tn2 = remainder;\n\t} while (remainder != 0)\n\n\treturn (num1 * num2) / n1;\n}\n\nint new_num(int num1, int num2, char op) {\n\tif (op == '+') return num1 + num2;\n\telse if (op == '-') return num1 - num2;\n\telse if (op == '*') return num1 * num2;\n\telse return num1 / num2;\n}\n\nint main() {\n\tchar operator, op;\t\n\tint n, num, num1, num2, den1, den2, nden1, nden2;\n\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> num1 >> op >> den1 >> operator >> num2 >> op >> den2;\n\t\tnden1 = lcm(den1, den2);\n\t\tnden2 = lcm(den1, den2);\n\t\tnum1 *= nden1 / den1;\n\t\tnum2 *= nden2 / den2;\n\t\tnum = new_num(num1, num2, operator);\n\t\t// continue\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/tda_rational_2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1022\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint mdc(int num1, int num2) {\n\tint remainder;\n\n\tdo {\n\t\tremainder = num1 % num2;\n\t\tnum1 = num2;\n\t\tnum2 = remainder;\n\t} while (remainder != 0);\n\n\treturn num1;\n}\n\nint main() {\n\tstring ope, op;\n\tint n, num, num1, num2, den, den1, den2, div;\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> num1 >> op >> den1 >> ope >> num2 >> op >> den2;\n\t\tden = den1 * den2;\n\t\tif (ope == \"+\") num = num1 * den2 + num2 * den1;\n\t\telse if (ope == \"-\") num = num1 * den2 - num2 * den1;\n\t\telse if (ope == \"*\") num = num1 * num2;\n\t\telse {\n\t\t\tnum = num1 * den2;\n\t\t\tden = num2 * den1;\n\t\t}\n\n\t\tdiv = mdc(num, den);\n\t\tif (div < 0) div *= -1;\n\t\tcout << num << \"/\" << den << \" = \" << num/div << \"/\" << den/div << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/tell_me_the_frequencies.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1251\n\n#include <iostream>\n#include <string>\n#include <map>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint toASCII(char charac) {\n  int newCharac = int(charac);\n  return newCharac;\n}\n\nbool compareByFrequency(const pair<int, int> &item1, const pair<int, int> &item2) {\n  if (item1.second < item2.second) return true;\n  else if (item1.second == item2.second) return item1.first > item2.first;\n  else return false;\n}\n\nint main() {\n  char charac;\n  string text;\n  bool first = true;\n\n  while (getline(cin, text)) {\n    map<int, int> m;\n    if (first) first = false;\n    else cout << endl;\n\n    for (int i = 0; i < text.size(); i++) {\n      charac = toASCII(text[i]);\n      if (m.find(charac) != m.end()) m[charac]++;\n      else m[charac] = 1;\n    }\n\n    vector< pair<int, int> > vec(m.begin(), m.end());\n    sort(vec.begin(), vec.end(), compareByFrequency);\n\n    for (int i = 0; i < vec.size(); ++i) {\n      cout << vec[i].first << \" \" << vec[i].second << endl;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/the_chosen.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1983\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n, final, code;\n\tdouble greater = 7.9, note;\n\tcin >> n;\n\n\twhile (n--) {\n\n\t\tcin >> code >> note;\n\n\t\tif (note > greater) {\n\t\t\tgreater = note;\n\t\t\tfinal = code;\n\t\t}\n\n\t}\n\n\tif (greater == 7.9) cout << \"Minimum note not reached\" << endl;\n\telse cout << final << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/the_force_awakens.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2163\n\n#include <iostream>\n\nusing namespace std;\n\nbool surroundedBySevens(int matrix[1001][1001], int y, int x) {\n  int sum = 0;\n\n  for (int i = y-1; i <= y+1; i++) {\n    for (int j = x-1; j <= x+1; j++) {\n      if (y != i || x != j) sum += matrix[i][j];\n    }\n  }\n\n  return sum == 56;\n}\n\nint main() {\n  int n1, n2, y = 0, x = 0;\n  cin >> n1 >> n2;\n  int matrix[1001][1001];\n\n  for (int i = 0; i < n1; i++) {\n    for (int j = 0; j < n2; j++) {\n      cin >> matrix[i][j];\n    }\n  }\n\n  for (int i = 1; i < n1-1; i++) {\n    for (int j = 1; j < n2-1; j++) {\n      if (matrix[i][j] == 42 && surroundedBySevens(matrix, i, j)) {\n        y = i+1;\n        x = j+1;\n      }\n    }\n  }\n\n  cout << y << \" \" << x << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/the_greater_one_digit_number.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1867\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <math.h>\n\nusing namespace std;\n\nbool is_one_digit(int n) {\n\tif (n >= 0 && n <= 9) return true;\n\treturn false;\n}\n\nint sum_digits_1(string n) {\n\tint sum = 0, digit;\n\n\tfor (int i = 0; i < n.size(); i++) {\n\t\tdigit = n[i] - 48;\n\t\tsum += digit;\n\t}\n\n\treturn sum;\n}\n\nint sum_digits_2(int n) {\n\tint sum = 0, digit;\n\n\twhile (n) {\n\t\tdigit = n % 10;\n\t\tsum += digit;\n\t\tn /= 10;\n\t}\n\n\treturn sum;\n}\n\nint main() {\n\t\n\tstring n, m;\n\tcin >> n >> m;\n\n\twhile (n != \"0\" || m != \"0\") {\n\t\tint n1 = sum_digits_1(n);\n\t\tint n2 = sum_digits_1(m);\n\n\t\twhile (!is_one_digit(n1)) n1 = sum_digits_2(n1);\t\t\n\t\twhile (!is_one_digit(n2)) n2 = sum_digits_2(n2);\n\n\t\tif (n1 == n2) cout << 0 << endl;\n\t\telse if (n1 > n2) cout << 1 << endl;\n\t\telse cout << 2 << endl;\n\n\t\tcin >> n >> m;\n\t}\n\t\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/the_greatest.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1013\n\n#include <iostream>\n\nusing namespace std;\n\nint abs(int a, int b) {\n\n  if (a > b) return a - b;\n  else if (a < b) return b - a;\n  else return 0;\n}\n\nint main() {\n\n  int n1, n2, n3;\n\n  cin >> n1 >> n2 >> n3;\n\n  int maior = ((n1 + n2) + abs(n1, n2)) / 2;\n  maior = ((maior + n3) + abs(maior, n3)) / 2;\n\n  cout << maior << \" eh o maior\" << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/the_library_of_mr_severino.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2137\n\n#include <iostream>\n#include <algorithm>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\tint n;\n\tstring s;\n\tvector<string> ss;\n\n\twhile (cin >> n) {\n\t\twhile (n--) {\n\t\t\tcin >> s;\n\t\t\tss.push_back(s);\n\t\t}\n\n\t\tsort(ss.begin(), ss.end());\n\n\t\tfor (int i = 0; i < ss.size(); i++) {\n\t\t\tcout << ss[i] << endl;\n\t\t}\n\n\t\tss.clear();\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/the_motion_picture.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1963\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n\tdouble n1, n2;\n\n\tcin >> n1 >> n2;\n\n\tcout << fixed << setprecision(2) << ((n2 - n1) / n1) * 100 << \"%\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/the_pythagorean_theorem.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1582\n\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\n#define min(m,n) ((m) < (n) ? (m) : (n))\n\nint mdc(int m, int n){\n\tint a = min(abs(m), abs(n));;\n\twhile (m % a != 0 || n % a != 0) a--;\n \treturn a;\n}\n\nint main(){\n    int x, y, z;\n    while(cin >> x >> y >> z) {\n        int hip, c1, c2;\n        if(z >= y && z >= x) { \n        \thip = z; \n        \tc1 = y;\n        \tc2 = x;\n        } else if (y >= z && y >= x) {\n        \thip = y; \n        \tc1 = z;\n        \tc2 = x;\n        } else if (x >= z && x >= y) { \n        \thip = x; \n        \tc1 = z; \n        \tc2 = y;\n        }\n\n        printf(\"tripla\");\n\t    \n\t    if(hip * hip == (c1 * c1 + c2 * c2)) {\n\t        printf(\" pitagorica\");\n\t        if(mdc(mdc(x,y), z) == 1) printf(\" primitiva\");\n\t    }\n\t    \n    \tcout << endl;\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/the_race_of_slugs.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1789\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n, x, faster = 0;\n\t\n\twhile (scanf(\"%d\", &n) != EOF) {\n\n\t\twhile (n--) {\n\t\t\tcin >> x;\n\t\t\tif (x > faster) faster = x;\n\t\t}\n\n\t\tif (faster < 10) cout << 1 << endl;\n\t\telse if (faster < 20) cout << 2 << endl;\n\t\telse cout << 3 << endl;\n\n\t\tfaster = 0;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/the_return_of_radar.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2143\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\tint n, x;\n\t\n\twhile (cin >> n && n != 0) {\n\t\twhile (n--) {\n\t\t\tcin >> x;\n\t\t\tif (x % 2 == 0) {\n\t\t\t\tcout << (x-2) * 2 + 2 << endl;\n\t\t\t} else {\n\t\t\t\tcout << (x-1) * 2 + 1 << endl;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/the_return_of_the_king.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <iomanip>\nusing namespace std;\n\nint to_digit(char digit) {\n  return digit - '0';\n}\n\nint string_to_number(string n) {\n  if (n == \"\") {\n    return -1;\n  } else {\n    int num = 0;\n\n    for (int i = 0; i < n.size(); i++) {\n      num = num * 10 + to_digit(n[i]);\n    }\n\n    return num;\n  }\n}\n\nint main() {\n\tstring num;\n\tcin >> num;\n\t\n\tfloat total = 0, total_num = 0;\n\t\n\tfor (int i = 0; i < num.size(); i++) {\n\t\tif (num[i] != '1') {\n\t\t\ttotal += to_digit(num[i]);\n\t\t} else {\n\t\t\tif (num[i+1] == '0') total += 10;\n\t\t\telse total += 1;\n\t\t}\n\t\t\n\t\tif (num[i] != '0') total_num++;\n\t}\n\t\n\tcout << fixed << setprecision(2) << total / total_num << endl;\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/the_square_game.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nstring findSquare(vector< vector<int> > &matrix, int x, int n, int m) {\n\tint total = 1;\n\n\tfor (int i = 0; i < n+1-x; i++) {\n\t\tfor (int j = 0; j < m+1-x; j++) {\n\t\t\tfor (int k = i; k < i+x; k++) {\n\t\t\t\tfor (int l = j; l < j+x; l++) {\n\t\t\t\t\ttotal *= matrix[k][l];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (total) return \"yes\";\n\t\t\ttotal = 1;\n\t\t}\n\t}\n\n\treturn \"no\";\n}\n\nmain() {\n\tvector<int> v;\n\tvector< vector<int> > matrix;\n\tint n, m, q, x;\n\tcin >> n >> m;\n\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tcin >> x;\n\t\t\tv.push_back(x);\n\t\t}\n\n\t\tmatrix.push_back(v);\n\t\tv.clear();\n\t}\n\n\tcin >> q;\n\tint greater;\n\n\twhile (q--) {\n\t\tcin >> x;\n\t\n\t\tif (x <= greater) {\n\t\t\tcout << \"yes\" << endl;\n\t\t} else if (findSquare(matrix, x, n, m) == \"yes\") {\n\t\t\tcout << \"yes\" << endl;\n\t\t\tgreater = x;\n\t\t} else {\n\t\t\tcout << \"no\" << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/the_wrath_of_khan.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1964\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint c, va, vb, t, d, da, db;\n\n\tcin >> c >> va >> vb >> t >> d;\n\n\tva /= 100;\n\tva *= 60;\n\tvb /= 100;\n\tvb *= 60;\n\n\tda = va * t;\n\tdb = vb * t;\n\n\tif ()\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/theons_answer.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1858\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n, x, smaller=21, index;\n\tcin >> n;\n\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> x;\n\t\tif (x < smaller) {\n\t\t\tsmaller = x;\n\t\t\tindex = i;\n\t\t}\n\t}\n\n\tcout << index << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/threebonacci_sequence.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1739\n\n#include <iostream>\n#include <map>\n\nusing namespace std;\n\nbool hasDigitThree(unsigned long long int n) {\n  bool has = false;\n  while (n) {\n    if (n % 10 == 3) {\n      has = true;\n      break;\n    }\n\n    n /= 10;\n  }\n\n  return has;\n}\n\nunsigned long long int fibonacci(int n) {\n  map<int, unsigned long long int> ar, threebonacci;\n  ar[1] = 1;\n  ar[2] = 1;\n  int counter = 1;\n\n  for (int i = 3; counter <= 60; i++) {\n    ar[i] = ar[i-1] + ar[i-2];\n    if ((ar[i] % 3 == 0 || hasDigitThree(ar[i]))) {      \n      threebonacci[counter] = ar[i];\n      counter++;\n    }\n\n    if (counter > n) break;\n  }\n\n  return threebonacci[n];\n}\n\nint main() {\n  int n;\n  while (cin >> n) {\n    cout << fibonacci(n) << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/throwing_cards_away.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1110\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nstruct num {\n\tint number;\n\tbool discarded;\n};\n\nint main() {\n\tint n;\n\n\twhile (cin >> n && n != 0) {\n\t\tvector<num> numbers;\n\t\tvector<int> discardedNumbers;\n\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tnum k;\n\t\t\tk.number = i;\n\t\t\tk.discarded = false;\n\t\t\tnumbers.push_back(k);\n\t\t}\n\n\t\tint numberOfDiscardedNum = 0;\n\t\tint startIndex = 0;\n\t\tint counter;\n\n\t\twhile (numberOfDiscardedNum < n - 1) {\n\t\t\tcounter = 2;\n\t\t\tnumbers[startIndex].discarded = true;\n\t\t\tdiscardedNumbers.push_back(numbers[startIndex].number);\n\t\t\t\n\t\t\twhile (counter--) {\n\t\t\t\tstartIndex++;\n\t\t\t\tif (startIndex >= n) startIndex = 0;\n\t\t\t\twhile (numbers[startIndex].discarded) {\n\t\t\t\t\tstartIndex++;\n\t\t\t\t\tif (startIndex >= n) startIndex = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnumberOfDiscardedNum++;\n\t\t}\n\n\t\tcout << \"Discarded cards: \" << discardedNumbers[0];\n\t\tfor (int i = 1; i < discardedNumbers.size(); i++) {\n\t\t\tcout << \", \" << discardedNumbers[i];\n\t\t}\n\n\t\tcout << endl << \"Remaining card: \";\n\t\tfor (int i = 1; i < n; i++) {\n\t\t\tif (!numbers[i].discarded)\n\t\t\t\tcout << numbers[i].number << endl;\n\t\t}\t\t\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/time_conversion.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1019\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n\tint time, hours=0, minutes=0, seconds=0;\n\n\tcin >> time;\n\n\twhile (time >= 3600) {\n\t\ttime -= 3600;\n\t\thours++;\n\t}\n\n\twhile (time >= 60) {\n\t\ttime -= 60;\n\t\tminutes++;\n\t}\n\n\twhile (time >= 1) {\n\t\ttime -= 1;\n\t\tseconds++;\n\t}\n\n\tcout << hours << \":\" << minutes << \":\" << seconds << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/time_zone.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2057\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\tint n1, n2, n3;\n\tcin >> n1 >> n2 >> n3;\n\tint total = n1 + n2 + n3;\n\tif (total >= 24) total -= 24;\n\telse if (total < 0) total += 24;\n\tcout << total << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/to_care_or_not_to_care.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1026\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <math.h>\n\nusing namespace std;\n\nvoid add_zero_values(vector<int> &v1, vector<int> &v2) {\n  int v1_size = v1.size(), v2_size = v2.size(), difference;\n\n  if (v1_size > v2_size) {\n    difference = v1_size - v2_size;\n    for (int j = 0; j < difference; j++) v2.push_back(0);\n  } else if (v1_size < v2_size) {\n    difference = v2_size - v1_size;\n    for (int j = 0; j < difference; j++) v1.push_back(0);\n  }\n\n  if (v1.size() % 4 != 0) {\n    int total_num_of_values = v1.size();\n    int num_needed = total_num_of_values % 4;\n    difference = 4 - num_needed;\n    for (int j = 0; j < difference; j++) v1.push_back(0);\n    for (int j = 0; j < difference; j++) v2.push_back(0);\n  }\n}\n\nvector<int> to_binary_number(int n) {\n  vector<int> v;\n  while (n > 0) {\n    v.push_back(n % 2);\n    n /= 2;\n  }\n\n  return v;\n}\n\nunsigned int to_decimal(vector<int> &v) {\n  unsigned int decimal_num = 0;\n  int size = v.size();\n  for (int i = 0; i < size; i++) if (v[i] == 1) decimal_num += pow(2, size-i-1);\n  return decimal_num;\n}\n\nint main() {\n\n  int num1, num2;\n\n  while (scanf(\"%i %i\", &num1, &num2) != EOF) {\n    vector<int> binary_num1 = to_binary_number(num1);\n    vector<int> binary_num2 = to_binary_number(num2);\n\n    for (int j = 0; j < binary_num1.size(); j++) cout << binary_num1[j];\n    cout << endl;\n    for (int j = 0; j < binary_num2.size(); j++) cout << binary_num2[j];\n    cout << endl;\n\n    reverse(binary_num1.begin(), binary_num1.end());\n    reverse(binary_num2.begin(), binary_num2.end());\n    add_zero_values(binary_num1, binary_num2);\n\n    vector<int> new_vec;\n\n    for (int j = 0; j < binary_num1.size(); j++) cout << binary_num1[j];\n    cout << endl;\n    for (int j = 0; j < binary_num2.size(); j++) cout << binary_num2[j];\n    cout << endl;\n\n    for (int i = 0; i < binary_num2.size(); i++) {\n      if (binary_num1[i] == binary_num2[i]) new_vec.push_back(0);\n      else new_vec.push_back(1);\n    }\n\n    cout << to_decimal(new_vec) << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/to_care_or_not_to_care2.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n  unsigned long int a, b, i;\n\n  while(cin >> a >> b){\n    i = a ^ b;\n    cout << i << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/top_n.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1943\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int n;\n  cin >> n;\n\n  if (n <= 1) {\n    cout << \"Top 1\" << endl;\n  } else if (n <= 3) {\n    cout << \"Top 3\" << endl;\n  } else if (n <= 5) {\n    cout << \"Top 5\" << endl;\n  } else if (n <= 10) {\n    cout << \"Top 10\" << endl;\n  } else if (n <= 25) {\n    cout << \"Top 25\" << endl;\n  } else if (n <= 50) {\n    cout << \"Top 50\" << endl;\n  } else if (n <= 100) {\n    cout << \"Top 100\" << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/tornado.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1266\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int n;\n  char post;\n\n  while (cin >> n && n != 0) {\n    int neededPostsNumber = 0, sum = 0, x, numberOfBrokenPosts = 0, firstZeros = 0;\n    bool finishedFirstZerosLot = false;\n\n    for (int i = 0; i < n; i++) {\n      cin >> post;\n      if (i == 0 && post == '1') finishedFirstZerosLot = true;\n\n      x = post - '0';\n      sum += x;\n\n      if (sum > 0) {\n        if (numberOfBrokenPosts % 2 == 0) neededPostsNumber += numberOfBrokenPosts / 2;\n        else neededPostsNumber += (numberOfBrokenPosts-1) / 2;\n        numberOfBrokenPosts = 0;\n        sum = 0;\n        finishedFirstZerosLot = true;\n      } else {\n        numberOfBrokenPosts++;\n        if (!finishedFirstZerosLot) firstZeros++;\n      }\n    }\n\n    if (numberOfBrokenPosts % 2 == 0) neededPostsNumber += numberOfBrokenPosts / 2;\n    else neededPostsNumber += (numberOfBrokenPosts-1) / 2;\n    if (firstZeros + numberOfBrokenPosts != 0 && (firstZeros + numberOfBrokenPosts) % 2 == 0) neededPostsNumber++;\n    cout << neededPostsNumber << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/train_swaping.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\n#define swap(a, b) { int x=a; a=b; b=x; }\n\nint numberOfSwaps(int v[], int n) {\n\tint swapNumber = 0;\n  for (int i = 1; i <= n - 1; i++) {\n    for (int j = 0; j < n - i; j++) {\n      if (v[j] > v[j+1]) {\n      \tswap(v[j], v[j+1]);\n      \tswapNumber++;\n      }\n    }\n  }\n\n  return swapNumber;\n}\n\nint main() {\n\tint n, x, c;\n\tcin >> n;\n\n\twhile (n--) {\n\t\tint num = 0;\n\t\tcin >> c;\n\t\tint ar[51];\n\n\t\tfor (int i = 0; i < c; i++) {\n\t\t\tcin >> x;\n\t\t\tar[i] = x;\n\t\t\tnum++;\n\t\t}\n\n\t\tcout << \"Optimal train swapping takes \" << numberOfSwaps(ar, num) << \" swaps.\" << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/tri-du.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1933\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint n1, n2, n3;\n\n\tcin >> n1 >> n2;\n\n\tif (n1 >= n2) cout << n1 << endl;\n\telse if (n2 > n1) cout << n2 << endl;\t\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/triangle.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1043\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint is_triangle(double a, double b, double c) {\n\tif ((a < b + c) && (b < a + c) && (c < a + b)) return 1;\n\telse return 0;\n}\n\nint main() {\n\n\tdouble a, b, c;\n\n\tcin >> a >> b >> c;\n\n\tif (is_triangle(a, b, c)) {\n\t\tcout << fixed << setprecision(1) << \"Perimetro = \" << a + b + c << endl;\n\t} else {\n\t\tcout << fixed << setprecision(1) << \"Area = \" << (a + b) * c / 2 << endl;\n\t}\n\n\treturn 0;\t\n}"
  },
  {
    "path": "competitive-programming/uri/triangle_types.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1045\n\n#include <iostream>\n#include <iomanip>\n#include <math.h>\n#include <vector>\n\nusing namespace std;\n\nint is_triangle(double a, double b, double c) {\n\tif ((a < b + c) && (b < a + c) && (c < a + b)) return 1;\n\telse return 0;\n}\n\nint main() {\n\n\tdouble a, b, c, n;\n\n\tcin >> a >> b >> c;\n\n\tif (b > a && b >= c) {\n\t\tn = b;\n\t\tb = a;\n\t\ta = n;\n\t} else if (c > a && c >= b) {\n\t\tn = c;\n\t\tc = a;\n\t\ta = n;\n\t}\n\n\tif (is_triangle(a, b, c)) {\n\t\tif (pow(a, 2) == pow(b, 2) + pow(c, 2)) {\n\t\t\tcout << \"TRIANGULO RETANGULO\" << endl;\n\t\t} else if (pow(a, 2) > pow(b, 2) + pow(c, 2)) {\n\t\t\tcout << \"TRIANGULO OBTUSANGULO\" << endl;\n\t\t} else if (pow(a, 2) < pow(b, 2) + pow(c, 2)) {\n\t\t\tcout << \"TRIANGULO ACUTANGULO\" << endl;\n\t\t}\n\n\t\tif (a == b && a != c || a == c && a != b || b == c && a != c) cout << \"TRIANGULO ISOSCELES\" << endl;\n\t\telse if (a == b && a == c) cout << \"TRIANGULO EQUILATERO\" << endl;\n\n\t} else {\n\t\tcout << \"NAO FORMA TRIANGULO\" << endl;\n\t}\n\n\treturn 0;\t\n}"
  },
  {
    "path": "competitive-programming/uri/triangles.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1472\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\tint n, x, num, sum, partOfArc;\n\n\twhile (cin >> n) {\n\t\tvector<int> nums;\n\t\tsum = 0;\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> x;\n\t\t\tsum += x;\n\t\t\tnums.push_back(x);\n\t\t}\n\n\t\tif (sum % 3 == 0) {\n\t\t\tpartOfArc = sum / 3;\n\t\t} else {\n\t\t\tcout << 0 << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/tribol.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1875\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, m;\n\tstring p1, p2;\n\tcin >> n;\n\n\twhile (n--) {\n\t\tint b = 0, g = 0, r = 0;\n\t\tcin >> m;\n\t\twhile (m--) {\n\t\t\tcin >> p1 >> p2;\n\n\t\t\tif (p1 == \"G\") {\n\t\t\t\tif (p2 == \"B\") g += 2;\n\t\t\t\telse g++;\n\t\t\t} else if (p1 == \"R\") {\n\t\t\t\tif (p2 == \"G\") r += 2;\n\t\t\t\telse r++;\n\t\t\t} else {\n\t\t\t\tif (p2 == \"R\") b += 2;\n\t\t\t\telse b++;\n\t\t\t}\n\t\t}\n \n\t\tif (b == g && b == r) cout << \"trempate\" << endl;\n\t\telse if (b > g && b == r) cout << \"empate\" << endl;\n\t\telse if (g > b && g == r) cout << \"empate\" << endl;\n\t\telse if (g > r && g == b) cout << \"empate\" << endl;\n\t\telse if (g > r && g > b) cout << \"green\" << endl;\n\t\telse if (b > r && b > g) cout << \"blue\" << endl;\n\t\telse if (r > g && r > b) cout << \"red\" << endl;\n\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/trinomial_triangle.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1795\n\n#include <iostream>\n#include <math.h>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n;\n\tcin >> n;\n\n\tlong long int result = pow(3, n);\n\n\tcout << result << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/tshirt2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1258\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n\nusing namespace std;\n\nstruct tshirt {\n  string color;\n  string tshirtSize;\n};\n\nint clothesFound(vector< pair< tshirt, vector<string> > > &clothes, string tshirtSize, string color) {\n  for (int i = 0; i < clothes.size(); i++) {\n    if (clothes[i].first.tshirtSize == tshirtSize && clothes[i].first.color == color) \n      return i;\n  }\n\n  return -1;\n}\n\nbool compareClothes(const pair< tshirt, vector<string> > &p1, const pair< tshirt, vector<string> > &p2) {\n  if (p1.first.color < p2.first.color) return true;\n  else if (p1.first.color > p2.first.color) return false;\n  else {\n    if (p1.first.tshirtSize >= p2.first.tshirtSize) return true;\n    else return false;\n  }\n}\n\nint main() {\n  int n, found;\n  string name, tshirtSize, color;\n  cin >> n;\n\n  while (n != 0) {    \n    vector< pair< tshirt, vector<string> > > clothes;\n    vector<string> v;\n\n    while (n--) {\n      cin.ignore();\n      getline(cin, name);\n      cin >> color >> tshirtSize;\n      tshirt t;\n      t.tshirtSize = tshirtSize;\n      t.color = color;\n      found = clothesFound(clothes, tshirtSize, color);\n\n      if (found != -1) {\n        clothes[found].second.push_back(name);\n      } else {\n        vector<string> names;\n        names.push_back(name);\n        clothes.push_back(make_pair(t, names));\n      }\n    }\n\n    sort(clothes.begin(), clothes.end(), compareClothes);\n\n    for (int i = 0; i < clothes.size(); i++) {\n      sort(clothes[i].second.begin(), clothes[i].second.end());\n      for (int j = 0; j < clothes[i].second.size(); j++) {\n        cout << clothes[i].first.color << \" \" << clothes[i].first.tshirtSize << \" \" << clothes[i].second[j] << endl;\n      }\n    }\n\n    cin >> n;\n    if (n) cout << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/tshirts.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1258\n\n#include <iostream>\n#include <map>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nint main() {\n  int n;\n  string name, tshirt, size;\n\n  while (cin >> n && n != 0) {\n    cin.ignore();\n    map < string, pair< string, vector<string> > > m;\n    vector<string> v;\n\n    while (n--) {\n      getline(cin, name);\n      cin >> tshirt >> size;\n\n      if (m.find(tshirt) != m.end()) {\n        m[tshirt].second.push_back(name);\n      } else {\n        v.push_back(name);\n        m[tshirt] = make_pair(size, v);\n        v.clear();\n      }\n    }\n\n    for (map < string, pair< string, vector<string> > >::iterator it = m.begin(); it != m.end(); ++it) {\n      for (int i = 0; i < it->second.size(); i++) {\n        cout << it->first << \" \" << it->second[i] << endl;\n      }\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/tug_of_war.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1586\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n  int n;\n  string names;\n\n  while (cin >> n && n != 0) {\n\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/turma_jb6.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2626\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n  string j1, j2, j3;\n\n  while (cin >> j1 >> j2 >> j3) {\n    if (j1 == \"papel\" && j2 == \"pedra\" && j3 == j2 || j1 == \"pedra\" && j2 == \"tesoura\" && j3 == j2 || j1 == \"tesoura\" && j2 == \"papel\" && j3 == j2) {\n      cout << \"Os atributos dos monstros vao ser inteligencia, sabedoria...\" << endl;\n    } else if (j2 == \"papel\" && j1 == \"pedra\" && j3 == j1 || j2 == \"pedra\" && j1 == \"tesoura\" && j3 == j1 || j2 == \"tesoura\" && j1 == \"papel\" && j3 == j1) {\n      cout << \"Iron Maiden's gonna get you, no matter how far!\" << endl;\n    } else if (j3 == \"papel\" && j1 == \"pedra\" && j2 == j1 || j3 == \"pedra\" && j1 == \"tesoura\" && j2 == j1 || j3 == \"tesoura\" && j1 == \"papel\" && j2 == j1) {\n      cout << \"Urano perdeu algo muito precioso...\" << endl;\n    } else {\n      cout << \"Putz vei, o Leo ta demorando muito pra jogar...\" << endl;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/turn_left.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1437\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\tcin >> n;\n\n\tstring s;\n\n\twhile (n) {\n\t\tgetline(cin, s);\n\t\tchar dir[1] = 'N';\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (s[i] == 'D') {\n\t\t\t\tif (dir == 'N') dir = 'L';\n\t\t\t\telse if (dir == 'L') dir = 'S';\n\t\t\t\telse if (dir == 'S') dir = 'O';\n\t\t\t\telse if (dir == 'O') dir = 'N';\n\t\t\t} else {\n\t\t\t\tif (dir == 'N') dir = 'O';\n\t\t\t\telse if (dir == 'O') dir = 'S';\n\t\t\t\telse if (dir == 'S') dir = 'L';\n\t\t\t\telse if (dir == 'L') dir = 'N';\n\t\t\t}\n\t\t}\n\n\t\tcout << dir << endl;\n\t\tcin.ignore();\n\t\tcin >> n;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/turn_left2.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1437\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n;\n\tcin >> n;\n\tstring directions;\n\n\tchar ar[] = { 'N', 'L', 'S', 'O' };\n\n\twhile (n) {\n\t\tint num = 0;\n\t\tcin >> directions;\n\n\t\tfor (int i = 0; i < directions.size(); i++) {\n\t\t\tif (directions[i] == 'D') {\n\t\t\t\tif (num >= 3) num = 0;\n\t\t\t\telse num++;\n\t\t\t} else  {\n\t\t\t\tif (num <= 0) num = 3;\n\t\t\t\telse num--;\n\t\t\t}\n\t\t}\n\n\t\tcout << ar[num] << endl;\n\n\t\tcin >> n;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/tustin_and_his_new_die.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2600\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n  long long int N, n1, n2, n3, n4, n5, n6, total;\n  vector<long long int> V;\n  cin >> N;\n\n  while (N--) {\n    cin >> n1 >> n2 >> n3 >> n4 >> n5 >> n6;\n\n    V.push_back(n1);\n    V.push_back(n2);\n    V.push_back(n3);\n    V.push_back(n4);\n    V.push_back(n5);\n    V.push_back(n6);\n    sort(V.begin(), V.end());\n\n    if (n1 + n6 == 7 && n2 + n4 == 7 && n3 + n5 == 7 && V[0] == 1 && V[1] == 2 && V[2] == 3 && V[3] == 4 && V[4] == 5 && V[5] == 6) cout << \"SIM\" << endl;\n    else cout << \"NAO\" << endl;\n    V.clear();\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/twilight_at_portland.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2168\n\n#include <iostream>\n\nusing namespace std;\n\nbool isSecure(int matrix[101][101], int i, int j) {\n  int numOfCameras = 0;\n  numOfCameras += matrix[i][j];\n  numOfCameras += matrix[i][j+1];\n  numOfCameras += matrix[i+1][j];\n  numOfCameras += matrix[i+1][j+1];\n  return numOfCameras >= 2;\n}\n\nint main() {\n  int n;\n  int matrix[101][101];\n  string line;\n  cin >> n;\n\n  for (int i = 0; i < n+1; i++) {\n    for (int j = 0; j < n+1; j++) {\n      cin >> matrix[i][j];\n    }\n  }\n\n  for (int i = 0; i < n; i++) {\n    line = \"\";\n    for (int j = 0; j < n; j++) {\n      if (isSecure(matrix, i, j)) line += \"S\";\n      else line += \"U\";\n    }\n    cout << line << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/twitting.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2165\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n  string tweet;\n  getline(cin, tweet);\n  if (tweet.size() <= 140) cout << \"TWEET\" << endl;\n  else cout << \"MUTE\" << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/two_bills.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2140\n\n#include <iostream>\n\nusing namespace std;\n\nint getMaximumBill(int diff) {\n\tif (diff >= 100) return 100;\n\telse if (diff >= 50) return 50;\n\telse if (diff >= 20) return 20;\n\telse if (diff >= 10) return 10;\n\telse if (diff >= 5) return 5;\n\telse return 2;\n}\n\nint main() {\n\tint n1, n2, diff, firstBill, counter;\n\n\twhile (cin >> n1 >> n2 && n1 + n2 != 0) {\n\t\tcounter = 0;\n\t\tdiff = n2 - n1;\n\n\t\twhile (diff > 0 && counter < 2) {\n\t\t\tfirstBill = getMaximumBill(diff);\n\t\t\tdiff -= firstBill;\n\t\t\tcounter++;\n\t\t}\n\n\t\tif (counter == 2 && diff == 0) cout << \"possible\" << endl;\n\t\telse cout << \"impossible\" << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/type_of_fuel.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1134\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\t\n\tint total_of_alcool=0, total_of_gas=0, total_of_diesel=0, n;\n\n\tcin >> n;\n\n\twhile (n != 4) {\n\n\t\tif (n == 1) {\n\t\t\ttotal_of_alcool++;\n\t\t} else if (n == 2) {\n\t\t\ttotal_of_gas++;\n\t\t} else if (n == 3) {\n\t\t\ttotal_of_diesel++;\n\t\t}\n\n\t\tcin >> n;\n\t}\n\n\tcout << \"MUITO OBRIGADO\" << endl;\n\tcout << \"Alcool: \" << total_of_alcool << endl;\n\tcout << \"Gasolina: \" << total_of_gas << endl;\n\tcout << \"Diesel: \" << total_of_diesel << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/upset_fracil.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2005\n\n#include <iostream>\n#include <algorithm>\n#include <set>\n\nusing namespace std;\n\nstruct msComparator {\n  bool operator() (const int &lhs, const int &rhs) const { return lhs > rhs; }\n};\n\nint main() {\n  int n1, n2, temp, food, decremented;\n\n  while (cin >> n1 >> n2) {\n    multiset<int, msComparator> ms;\n    multiset<int, msComparator>::iterator it;\n\n    for (int i = 0; i < n1; i++) {\n      cin >> temp;\n      ms.insert(temp);\n    }    \n\n    int counter = 0;\n\n    while (n2--) {\n      cin >> food;\n      bool hunger_satisfied = false;\n\n      for (it = ms.begin(); it != ms.end(); ++it) {\n        if (food >= *it && *it > 0) {\n          counter++;\n          ms.erase(*it);\n          hunger_satisfied = true;\n          break;\n        }\n      }\n\n      if (!hunger_satisfied) {\n        multiset<int, msComparator>::iterator first = ms.begin();\n        decremented = *first;\n        ms.erase(first);\n        ms.insert(decremented - food);\n      }\n    }\n\n    cout << counter << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/uri.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n\nusing namespace std;\n\nbool is_power_of_two(int n) {\n\tfor (int i = 2; i <= n; i *= 2)\n\t\tif (i == n) return true;\n\t\n\treturn false;\n}\n\nstring get_winner(vector<int> &points) {\n\tint bigger = -1, index = -1;\n\tfor (int i = 0; i < points.size(); i++) {\n\t\tif (points[i] > bigger) {\n\t\t\tindex = i;\n\t\t\tbigger = points[i];\n\t\t}\n\t}\n\t\n\tfor (int i = 0; i < points.size(); i++) cout << points[i] << \" \";\n\tcout << endl;\n\t\n\tsort(points.begin(), points.end());\n\tint last = points.back(), penultimate = points.end()[-2];\n\t\n\tif (last == penultimate) return \"URI\";\n\telse if (index == 0) return \"Uilton\";\n\telse if (index == 1) return \"Rita\";\n\telse return \"Ingred\";\n}\n\nint main() {\n\tint n, x;\n\tcin >> n;\n\t\n\twhile (n != 0) {\n\t\tvector<int> points(3, 0);\n\t\twhile (n--) {\n\t\t\tint greater = 0, index = -1;\n\t\t\tfor (int i = 0; i < 3; i++) {\n\t\t\t\tcin >> x;\n\t\t\t\tif (is_power_of_two(x)) {\n\t\t\t\t\tpoints[i]++;\n\t\t\t\t\tif (x > greater) {\n\t\t\t\t\t\tgreater = x;\n\t\t\t\t\t\tindex = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (index != -1) points[index]++;\n\t\t}\n\t\t\n\t\tstring winner = get_winner(points);\n\t\tcout << winner << endl;\n\t\tcin >> n;\n\t}\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/vai_na_sort.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2592\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int N, num, counter, count;\n  bool right;\n\n  while (cin >> N && N != 0) {\n    right = false;\n    counter = 0;\n\n    while (!right) {\n    \tcount = 0;\n      for (int i = 1; i <= N; i++) {\n        cin >> num;\n        if (num == i) count++;\n      }\n\n      right = count == N;\n      counter++;\n    }\n\n    cout << counter << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/variations.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1632\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nbool in_new(char l) {\n\tif (l == 'a' || l == 'A' || l == 'e' || l == 'E' || l == 'i' || l == 'I' || l == 'o' || l == 'O' || l == 's' || l == 'S') return true;\n\treturn false;\n}\n\nint main() {\n\t\n\tint n, total;\n\tcin >> n;\n\tstring code;\n\n\twhile (n--) {\n\t\tcin >> code;\n\t\ttotal = 1;\n\n\t\tfor (int i = 0; i < code.size(); i++) {\n\t\t\tif (in_new(code[i])) total *= 3;\n\t\t\telse total *= 2;\n\t\t}\n\n\t\tcout << total << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/virus.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/pt/problems/view/2567\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n  int N, num, level;\n\n  while (cin >> N) {\n    vector<int> V;\n    level = 0;\n\n    while (N--) {\n      cin >> num;\n      V.push_back(num);\n    }\n\n    sort(V.begin(), V.end());\n\n    for (int i = 0; i < V.size() / 2; i++) {\n      level += (V[V.size()-1] - V[i]);\n    }\n\n    cout << level << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/vitoria_and_her_indecision.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1924\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n  int n;\n  cin >> n;\n\n  string course;\n\n  while (n--) {\n    cin >> course;\n  }\n\n  cout << \"Ciencia da Computacao\" << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/volleyball.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/2310\n\n#include <iostream>\n#include <string>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\tint n, saque, bloqueio, ataque;\n\tfloat totalSaque = 0, totalBloqueio = 0, totalAtaque = 0;\n\tfloat totalSaqueOk = 0, totalBloqueioOk = 0, totalAtaqueOk = 0;\n\tstring s;\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> s;\n\t\t\n\t\tcin >> saque >> bloqueio >> ataque;\n\t\ttotalSaque += saque;\n\t\ttotalBloqueio += bloqueio;\n\t\ttotalAtaque += ataque;\n\n\t\tcin >> saque >> bloqueio >> ataque;\n\t\ttotalSaqueOk += saque;\n\t\ttotalBloqueioOk += bloqueio;\n\t\ttotalAtaqueOk += ataque;\t\t\n\t}\n\n\tcout << setprecision(2) << fixed << \"Pontos de Saque: \" << totalSaqueOk / totalSaque * 100 << \" %.\" << endl;\n\tcout << setprecision(2) << fixed << \"Pontos de Bloqueio: \" << totalBloqueioOk / totalBloqueio * 100 << \" %.\" << endl;\n\tcout << setprecision(2) << fixed << \"Pontos de Ataque: \" << totalAtaqueOk / totalAtaque * 100 << \" %.\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/weighted_averages.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1079\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main() {\n\n\tint n;\n\tdouble weight1, weight2, weight3, total=0;\n\n\tcin >> n;\n \n\twhile (n--) {\t\t\n\t\t\n\t\tcin >> weight1;\n\t\ttotal += weight1 * 2;\n\t\tcin >> weight2;\n\t\ttotal += weight2 * 3;\n\t\tcin >> weight3;\n\t\ttotal += weight3 * 5;\n\n\t\tcout << fixed << setprecision(1) << total / 10 << endl;\n\t\ttotal = 0;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/welcome_to_the_winter.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1847\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n  int a, b, c;\n\n  cin >> a >> b >> c;\n\n  if (a == b && b == c) {\n  \tcout << \":(\" << endl;\n  } else {\n\t\tif (b - a < c - b) cout << \":)\" << endl;\n\t\telse if (b - a == c - b && b - a > 0) cout << \":)\" << endl;\n\t\telse if (b - a == c - b && b - a < 0) cout << \":(\" << endl;\n\t\telse cout << \":(\" << endl;\n\t}\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/wertyu.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1196\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n  string s = \"QWERTYUIOP[]\\\\ASDFGHJKL;'ZXCVBNM,./`1234567890-=\";\n  string thing;\n  int index;\n\n  while (getline(cin, thing)) {\n    string new_thing = \"\";\n    for (int i = 0; i < thing.size(); i++) {\n      if (thing[i] != ' ') {\n        index = s.find(thing[i]) - 1;\n        new_thing += s[index];\n      } else {\n        new_thing += \" \";\n      }\n    }\n\n    cout << new_thing << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/where_is_the_marble.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1025\n\n#include <iostream>\n#include <map>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n\tvector<int> v;\n\tmap<int, int> m;\n\tint n, q, casy = 1, x;\n\n\twhile (cin >> n >> q && n + q != 0) {\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> x;\n\t\t\tv.push_back(x);\n\t\t}\n\n\t\tsort(v.begin(), v.end());\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (m.find(v[i]) != m.end()) m[v[i]] = i+1;\n\t\t}\n\n\t\tcout << \"CASE# \" << casy << \":\" << endl;\n\n\t\twhile (q--) {\n\t\t\tcin >> x;\n\t\t\tif (m.find(x) != m.end()) cout << x << \" found at \" << m[x] << endl;\n\t\t\telse cout << x << \" not found\" << endl;\n\t\t}\n\n\t\tcasy++;\n\t\tv.clear();\n\t\tm.clear();\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/which_triangle.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n\nusing namespace std;\n\nstring is_rectangular(int a, int b, int c) {\n  if (c * c == a * a + b * b) return \"Retangulo: S\";\n  return \"Retangulo: N\";\n}\n\nint main() {\n  vector<int> V;\n  int N = 3, side;\n\n  while (N--) {\n    cin >> side;\n    V.push_back(side);\n  }\n\n  sort(V.begin(), V.end());\n\n  if (V[2] >= V[0] + V[1]) {\n    cout << \"Invalido\" << endl;\n  } else {\n    if (V[0] == V[1] && V[1] == V[2]) {\n      cout << \"Valido-Equilatero\" << endl;\n      cout << \"Retangulo: N\" << endl;\n    } else if (V[0] == V[1] || V[1] == V[2]) {\n      cout << \"Valido-Isoceles\" << endl;\n      cout << is_rectangular(V[0], V[1], V[2]) << endl;\n    } else {\n      cout << \"Valido-Escaleno\" << endl;\n      cout << is_rectangular(V[0], V[1], V[2]) << endl;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/who_turn_is_it.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1914\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n, num1, num2, total;\n\tstring player1, player2, strat1, strat2;\n\n\tcin >> n;\n\n\twhile (n--) {\n\t\tcin >> player1 >> strat1 >> player2 >> strat2;\n\t\tcin >> num1 >> num2;\n\t\ttotal = num1 + num2;\n\n\t\tif (total % 2 == 0) {\n\t\t\tif (strat1 == \"PAR\") cout << player1 << endl;\n\t\t\telse cout << player2 << endl;\n\t\t} else {\n\t\t\tif (strat1 == \"IMPAR\") cout << player1 << endl;\n\t\t\telse cout << player2 << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/wills_message.cpp",
    "content": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n  string message, s;\n  int N, num;\n\n  while (cin >> s) {\n    cin >> N;\n    message = \"\";\n\n    while (N--) {\n      cin >> num;\n      message += s[num-1];\n    }\n\n    cout << message << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/world_cup.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1414\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\t\n\tint n1, n2, x, points=0, total;\n\tstring team;\n\n\twhile (cin >> n1 >> n2 && n1 + n2 != 0) {\n\t\ttotal = n2 * 3;\n\t\twhile (n1--) {\n\t\t\tcin >> team >> x;\n\t\t\tpoints += x;\n\t\t}\n\n\t\tcout << total - points << endl;\n\t\tpoints = 0;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uri/zero_means_zero.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1871\n\n#include <iostream>\n#include <vector>\n#include <math.h>\n\nusing namespace std;\n\nint main() {\n\n  long int n1, n2, total;\n  cin >> n1 >> n2;\n\n  vector<int> numbers;\n\n  while (n1 + n2 != 0) {\n\n    total = n1 + n2;\n\n    while (total != 0) {\n      numbers.push_back(total % 10);\n      total /= 10;\n    }\n\n    long int result = 0;\n    int aux = 0;\n\n    for (int i = 0; i < numbers.size(); i++) {\n      if (numbers[i]) {\n        result += numbers[i] * pow(10, aux);\n        aux++;\n      }\n    }\n\n    cout << result << endl;\n\n    cin >> n1 >> n2;\n    numbers.clear();\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/uri/zero_or_one.cpp",
    "content": "// https://www.urionlinejudge.com.br/judge/en/problems/view/1467\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\n\tint a, b, c;\n\n\twhile (scanf(\"%d %d %d\", &a, &b, &c) != EOF) {\n\t\tif (a == b && a == c) {\n\t\t\tcout << \"*\" << endl;\n\t\t} else {\n\t\t\tif (b == c) cout << \"A\" << endl;\n\t\t\telse if (a == c) cout << \"B\" << endl;\n\t\t\telse if (a == b) cout << \"C\" << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "competitive-programming/uva/280-vertex.cpp",
    "content": "// https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=666&page=show_problem&problem=216\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int, int> pii;\ntypedef vector<pii> vii;\ntypedef vector<int> vi;\n\nint VISITED = 1;\nint UNVISITED = 0;\n\nvoid dfs(int vertex, vector<vi> & AdjList, set<int> & reached, int dfs_num[]) {\n  dfs_num[vertex] = VISITED;\n  int edge;\n\n  for (int i = 0; i < AdjList[vertex].size(); i++) {\n    edge = AdjList[vertex][i];\n    reached.insert(edge);\n    if (dfs_num[edge] == UNVISITED) dfs(edge, AdjList, reached, dfs_num);\n  }\n}\n\nint main() {\n  int n, edge, starting_vertex, test, vertex;\n  vi V;\n  vector<vi> AdjList;\n\n  while (cin >> n && n) {\n    for (int i = 0; i <= n; i++) {\n      AdjList.push_back(V);\n    }\n\n    while (cin >> starting_vertex && starting_vertex) {\n      while (cin >> edge && edge) {\n        AdjList[starting_vertex].push_back(edge);\n      }\n    }\n\n    cin >> test;\n\n    while (test--) {\n      set<int> reached, unreached;\n      cin >> vertex;\n      int dfs_num[101];\n      bool a = false;\n\n      fill(dfs_num, dfs_num+101, 0);\n      dfs(vertex, AdjList, reached, dfs_num);\n\n      for (int i = 1; i <= n; i++) {\n        for (set<int>::iterator it = reached.begin(); it != reached.end(); it++) {\n          if (*it == i) a = true;\n        }\n\n        if (!a) unreached.insert(i);\n        a = false;\n      }\n\n      if (unreached.size()) {\n        cout << unreached.size();\n\n        for (set<int>::iterator it = unreached.begin(); it != unreached.end(); it++) {\n          cout << \" \" << *it;\n        }\n\n        cout << endl;\n      } else {\n        cout << unreached.size() << endl;\n      }\n    }\n\n    AdjList.clear();\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/01-object-to-array-of-objects/README.md",
    "content": "# Problem\n\nWhat if you have an object and you want to convert that to an array of objects to do whatever you need to do?\n\n## Example data\n\n```js\nconst ingredients = {\n  cheese: 0,\n  lettuce: 0,\n  bacon: 1,\n  meat: 4,\n};\n```\n\n## Expected output\n\n```js\nconst output = [\n  { name: 'lettuce', count: 0 },\n  { name: 'bacon', count: 0 },\n  { name: 'cheese', count: 1 },\n  { name: 'meat', count: 4 },\n];\n```\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/01-object-to-array-of-objects/soluition1.js",
    "content": "const ingredients = { lettuce: 0, bacon: 0, cheese: 1, meat: 4 };\n\nconst output = Object.entries(ingredients).map(([name, count]) => ({\n  name,\n  count,\n}));\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/02-my-likes/README.md",
    "content": "# Problem\n\nGiven an array of posts and an array of your likes, how could you effeciently check if you liked a particular post or not?\n\n## Example data\n\n```js\nconst posts = [\n  {\n    id: 5,\n    authorId: 1,\n    content: 'Post 5',\n  },\n  {\n    id: 6,\n    content: 'Post 6',\n    authorId: 12,\n  }\n  ...\n];\n\nconst likes = [\n  { id: 1, postId: 5 },\n  { id: 2, postId: 10 },\n  { id: 3, postId: 124 },\n  ...\n];\n```\n\n### Notes\n\n- The `posts` array may contain posts from various users\n- The `likes` array only contains **your** likes\n- It's possible that many different users can like the same post\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/02-my-likes/solution1.js",
    "content": "const posts = [\n  {\n    id: 5,\n    authorId: 1,\n    content: 'Post 5',\n  },\n  {\n    id: 6,\n    content: 'Post 6',\n    authorId: 12,\n  },\n];\n\nconst likes = [\n  { id: 1, postId: 5 },\n  { id: 2, postId: 10 },\n  { id: 3, postId: 124 },\n];\n\nconst isLiked = ({ id }, myLikes) => myLikes.some((like) => like.postId === id);\n\nconst likedPosts = posts.filter((post) => isLiked(post, likes));\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/02-my-likes/solution2.js",
    "content": "const posts = [\n  {\n    id: 5,\n    authorId: 1,\n    content: 'Post 5',\n  },\n  {\n    id: 6,\n    content: 'Post 6',\n    authorId: 12,\n  },\n];\n\nconst likes = [\n  { id: 1, postId: 5 },\n  { id: 2, postId: 10 },\n  { id: 3, postId: 124 },\n];\n\nconst postToLikeMapper = likes.reduce(\n  (mapper, { id, postId }) => ({ ...mapper, [postId]: id }),\n  {}\n);\n\nposts.filter(({ id }) => postToLikeMapper[id]);\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/03-ch-ch-ch-changes/README.md",
    "content": "# Problem\n\nThis is going to be a data structure problem, the kind of problem we often encounter with the data we have: namely, that the data structure is not in the format that we want! 😡 So, what to do?\n\nGiven the following data:\n\n```js\ndata = {\n  something: { title: 'something', copy: 'something', link: 'something' },\n  another: { title: 'another', copy: 'another', link: 'another' },\n};\n```\n\nCreate a **function** that will allow you to efficiently convert your data into the following format:\n\n```js\noutput = [\n  {\n    id: 'something',\n    title: 'something',\n    copy: 'something',\n    link: 'something',\n  },\n  {\n    id: 'another',\n    title: 'another',\n    copy: 'another',\n    link: 'another',\n  },\n];\n```\n\nAs you can see, the goal of this exercise is to convert your data into an array of objects where the `id` for each object in the new array maps to the keys of the original object.\n\n## Notes\n\n- As the original data is an object, all keys will be unique, so you don't have to worry about duplicate entries.\n- The data could be incredibly long or short so, as always, be mindful of time complexity.\n\n## Tips\n\n- There are various ways to solve this problem, and it is useful to explore each.\n- Try to think of a multitude of solutions, get each working -- and then consider the strengths and weaknesses of each.\n- After you have your final answer, think about how you can clean it up. That is, how can you make the code more readable while also being concise?\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/03-ch-ch-ch-changes/solution.js",
    "content": "const convertObjToArrayOfObjects = (data) =>\n  Object.entries(data).map(([key, values]) => ({\n    id: key,\n    ...values,\n  }));\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/07-zero-to-hero/README.md",
    "content": "# Problem\n\nThis problem is a fun one because there are so many different ways to solve it. Which means you can come up with multiple answers, practice multiple techniques and compare the relative strengths and weaknesses. That's a triple bonus for a weekend code challenge problem.\n\nSo, the question is this:\n\nGiven an array of integers, write a function that will return an array where all the zeros in that array are moved to the back of the array.\n\nFor instance, given the following array:\n\n```js\n[9, 0, 133, -1, 2, 0, 9];\n```\n\nThe correct output would look like this:\n\n```js\n[9, 133, -1, 2, 9, 0, 0];\n```\n\n## Notes\n\n- There are no limitations on what you can do to the array. Feel free to mutate it in place if you like\n- The best answer will be done in linear time, with constant space complexity\n- Consider edge cases like if all the items were zeros (e.g. `[0, 0, 0, 0, 0, 0, 0]`) or if there are zeros at the beginning and end of your array (e.g. `[0, 0, 1, 33, -2, 0, 0]`)\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/07-zero-to-hero/solution1.js",
    "content": "function zeroToHero(numbers) {\n  const allButZeros = numbers.filter((number) => number);\n  const zerosCount = numbers.filter((number) => !number).length;\n  const zeros = new Array(zerosCount).fill(0);\n\n  return [...allButZeros, ...zeros];\n}\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/08-first-non-repeat/README.md",
    "content": "# Problem\n\nThis is a popular string problem that is pretty fun to solve.\n\nGiven a string of characters without spaces like the following:\n\n```md\naaaccceeef\n```\n\nWrite a function that returns the first non-repeating character. In this case, the correct answer would be `f`, since it is the first character in the string that doesn't have a repeat.\n\nHere are a few other examples and the correct answer for your reference:\n\n```md\nabc0cb // correct answer is \"a\"\na01110abc // correct answer is \"b\"\naaaabbbccc // -1 since all are repeating\n```\n\n## Notes\n\n- You will always have at least 1 character in the string (i.e. don't worry about an empty string)\n- Characters will only consist of alphanumeric characters, aA-zZ, 0-9\n- If there are no non-repeating characters in the string, return `-1`\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/08-first-non-repeat/solution1.js",
    "content": "const getArrayOfChars = (string = '') => string.split('');\n\nconst buildCharsCounter = (arrayOfChars) => {\n  const charsCounter = {};\n  arrayOfChars.forEach((char) => {\n    if (char in charsCounter) {\n      charsCounter[char] += 1;\n    } else {\n      charsCounter[char] = 1;\n    }\n  });\n  return charsCounter;\n};\n\nconst getFirstNonRepeatingChar = (string = '') => {\n  const arrayOfChars = getArrayOfChars(string);\n  const charsCounter = buildCharsCounter(arrayOfChars);\n  const isNonRepeatingChar = (char) =>\n    char in charsCounter && charsCounter[char] === 1;\n\n  return arrayOfChars.find(isNonRepeatingChar) || -1;\n};\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/09-big-three/README.md",
    "content": "# Problem\n\nThis is a classic problem, and a variation on an even more classic problem, which is to find the largest value in an array.\n\nDifference here is that you need to find the 3 largest values in the array. And they need to be returned in ascending order.\n\nSo, to put it clearly, given an array of integers, write a function that will return an array of the 3 largest numbers from that array.\n\nSample input:\n\n```js\n[3, -100, 199, 10, 14, 555]\n```\n\nExpected output:\n\n```js\n[14, 199, 555]\n```\n\n## Notes:\n\n- The array will not be sorted, and you cannot sort it to solve this problem -- that would be too easy ;)\n- There will always be at least 3 values in the input array, and they will always be integers.\n- There may be duplicates of the same integers. Potentially all 3 values could be the same number if those are the largest integers in the array.\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/09-big-three/solution1.js",
    "content": "const getBigThree = (numbers) => {\n  let largest = -Infinity;\n  let secondLargest = -Infinity;\n  let thirdLargest = -Infinity;\n\n  numbers.forEach((number) => {\n    if (number > largest) {\n      thirdLargest = secondLargest;\n      secondLargest = largest;\n      largest = number;\n    } else if (number > secondLargest) {\n      thirdLargest = secondLargest;\n      secondLargest = number;\n    } else if (number > thirdLargest) {\n      thirdLargest = number;\n    }\n  });\n\n  return [thirdLargest, secondLargest, largest];\n};\n\ngetBigThree([3, -100, 199, 10, 14, 555, 133, 555, 143, 1000]);\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/09-big-three/solution2.js",
    "content": "const getLargestAndIndex = (numbers) => {\n  let largest = -Infinity;\n  let index;\n\n  numbers.forEach((number, numberIndex) => {\n    if (number > largest) {\n      largest = number;\n      index = numberIndex;\n    }\n  });\n\n  return [largest, index];\n};\n\nconst removeItemByIndex = (numbers, index) => {\n  return numbers.filter((_, numberIndex) => numberIndex !== index);\n};\n\nconst getBigThree = (numbers) => {\n  let largest;\n  let secondLargest;\n  let thirdLargest;\n  let index;\n  let numbersCopy;\n\n  [largest, index] = getLargestAndIndex(numbers);\n\n  numbersCopy = removeItemByIndex(numbers, index);\n  [secondLargest, index] = getLargestAndIndex(numbersCopy);\n\n  numbersCopy = removeItemByIndex(numbersCopy, index);\n  [thirdLargest] = getLargestAndIndex(numbersCopy);\n\n  return [thirdLargest, secondLargest, largest];\n};\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/10-get-the-photo/README.md",
    "content": "# Problem\n\nWe've focused mostly on a bunch of algorithm problems lately, so let's take a break from that for a little while.\n\nThis is going to be a slightly easier problem than the past few as well, so it is a good chance to take a breather, apply some of the concepts we've learned, and as usual, to think about a number of different ways we can solve this problem to find a truly great answer.\n\nSo, the problem is this:\n\nGiven an array of objects containing urls to an image of various sizes, write a function that will efficiently return an array of strings containing only the urls to the `large` image.\n\n## Example input\n\n```js\n[\n  {\n    tiny: '//imageurl.../50x50/image_1.png',\n    large: '//imageurl.../1200x1600/image_1.png',\n  },\n  {\n    tiny: '//imageurl.../50x50/image_2.png',\n    large: '//imageurl.../1200x1600/image_2.png',\n  },\n  {\n    tiny: '//imageurl.../50x50/image_3.png',\n    large: '//imageurl.../1200x1600/image_3.png',\n  },\n  {\n    tiny: '//imageurl.../50x50/image_4.png',\n    large: '//imageurl.../1200x1600/image_4.png',\n  },\n  {\n    tiny: '//imageurl.../50x50/image_5.png',\n    large: '//imageurl.../1200x1600/image_5.png',\n  },\n  ...\n];\n```\n\n## Expected output\n\n```js\n['//imageurl.../1200x1600/image_1.png', '//imageurl.../1200x1600/image_2.png', ...];\n```\n\n## Notes\n\n- The input array could be really long or really short\n- The input array will always be an array and it will always have at least one object\n- The object will always contain the key `large`, and you can ignore other keys if they are present\n\n## Tips\n\nAs I will often say on Weekend Code Challenge, it is really important to think of multiple solutions to each problem so as to avoid using the same techniques, which can become stale over time.\n\nApply a variety of methods and built-in functions and try to find a solution that is not only efficient, but also easy to read and understand.\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/10-get-the-photo/solution1.js",
    "content": "const getLargeImageUrls = (images) => images.map(({ large }) => large);\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/11-threes-a-crowd/README.md",
    "content": "# Problem\n\nThis is a simple real life problem that I recently encountered.\n\nGiven an array of n values, create a new array of two-value arrays containing the original values. Each two-value array will contain the largest and smallest value from the initial array, and each value will only appear once within the set.\n\nIf n is an odd number, the final array will include that additional value, making it the exception to the two-value rule.\n\n## Example input (given n = 7)\n\n```js\n[3, 7, 10, 5, 4, 4, 1];\n```\n\n## Expected output\n\n```js\n[\n  [10, 1],\n  [7, 3],\n  [5, 4, 4],\n];\n```\n\n## Notes\n\n## Tips\n"
  },
  {
    "path": "competitive-programming/weekend-code-challenge/11-threes-a-crowd/solution1.js",
    "content": "const buildArrayOfTwoValuesArrays = (numbers) => {\n  numbers.sort((a, b) => a - b);\n  const array = [];\n\n  for (let i = 0; i < numbers.length; i++) {\n    if (i + 3 === numbers.length - i) {\n      array.push([numbers[i + 2], numbers[i + 1], numbers[i]]);\n      break;\n    }\n\n    if (i + 2 === numbers.length - i) {\n      array.push([numbers[i + 1], numbers[i]]);\n      break;\n    }\n\n    array.push([numbers[numbers.length - 1 - i], numbers[i]]);\n  }\n\n  return array;\n};\n\nbuildArrayOfTwoValuesArrays([3, 7, 10, 5, 4, 4, 1]);\nbuildArrayOfTwoValuesArrays([3, 7, 10, 5, 4, 4]);\n"
  },
  {
    "path": "computer_science/README.md",
    "content": "<samp>\n\n# Computer Science\n\n## Algorithms & Data Structures\n\n- Big O Time Complexity\n- Linear Search\n- Binary Search\n- Bubble Sort\n- Linked List Data Structure\n- Queue Data Structure\n\n</samp>\n"
  },
  {
    "path": "computer_science/algorithms/binary-search/binary-search.js",
    "content": "function getMiddle(start, end) {\n  return Math.floor((start + end) / 2);\n}\n\nexport function binarySearch(numbers, target) {\n  let start = 0;\n  let end = numbers.length - 1;\n  let middle = getMiddle(start, end);\n  let found = false;\n\n  while (start <= end && !found) {\n    middle = getMiddle(start, end);\n    const middleNumber = numbers[middle];\n\n    if (middleNumber === target) found = true;\n    if (middleNumber > target) end = middle - 1;\n    if (middleNumber < target) start = middle + 1;\n  }\n\n  return found;\n}\n\nfunction logResult(list, target) {\n  console.log(binarySearch(list, target));\n}\n"
  },
  {
    "path": "computer_science/algorithms/binary-search/tests/binary-search.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { binarySearch } from '../binary-search';\n\ndescribe('binarySearch', () => {\n  const list = [1, 3, 4, 69, 71, 81, 90, 99, 420, 1337, 69420];\n  const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\n  it('passes the search', () => {\n    expect(binarySearch(list, 69)).toBeTruthy();\n    expect(binarySearch(list, 1336)).toBeFalsy();\n    expect(binarySearch(list, 69420)).toBeTruthy();\n    expect(binarySearch(list, 69421)).toBeFalsy();\n    expect(binarySearch(list, 1)).toBeTruthy();\n    expect(binarySearch(list, 0)).toBeFalsy();\n  });\n\n  it('passes the search', () => {\n    expect(binarySearch(numbers, 5)).toBeTruthy();\n    expect(binarySearch(numbers, 11)).toBeFalsy();\n    expect(binarySearch(numbers, -1)).toBeFalsy();\n    expect(binarySearch(numbers, 0)).toBeFalsy();\n    expect(binarySearch(numbers, 9)).toBeTruthy();\n    expect(binarySearch(numbers, 1)).toBeTruthy();\n  });\n});\n"
  },
  {
    "path": "computer_science/algorithms/bubble-sort/bubble-sort.js",
    "content": "export function bubbleSort(numbers) {\n  for (let N = 0; N < numbers.length; N++) {\n    for (let index = 0; index < numbers.length - N - 1; index++) {\n      if (numbers[index] > numbers[index + 1]) {\n        let number = numbers[index];\n        numbers[index] = numbers[index + 1];\n        numbers[index + 1] = number;\n      }\n    }\n  }\n\n  return numbers;\n}\n"
  },
  {
    "path": "computer_science/algorithms/bubble-sort/tests/bubble-sort.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { bubbleSort } from '../bubble-sort';\n\ndescribe('bubbleSort', () => {\n  it('sorts', () => {\n    expect(bubbleSort([8, 5, 2, 5, 7, 5])).toEqual([2, 5, 5, 5, 7, 8]);\n    expect(\n      bubbleSort([8, 33, 5, 2, 7, 8, 6, 3, 4, 99, 2, 5, 2, 5, 7, 5])\n    ).toEqual([2, 2, 2, 3, 4, 5, 5, 5, 5, 6, 7, 7, 8, 8, 33, 99]);\n  });\n});\n"
  },
  {
    "path": "computer_science/algorithms/dynamic_programming/factorial.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nunsigned long long factorial_dp(int n) {\n\tvector<unsigned long long> v(1000000);\n\tv[0] = 1;\n\t\n\tfor (int i = 1; i <= n; i++)\n\t\tv[i] = v[i - 1] * i;\t\t\t\n\n\treturn v[n];\n}\t\n\nint main() {\t\n\n\tcout << factorial_dp(0) << endl;\n\tcout << factorial_dp(1) << endl;\n\tcout << factorial_dp(5) << endl;\n\tcout << factorial_dp(50) << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "computer_science/algorithms/dynamic_programming/fibonacci.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nint fibonacci(int n) {\n  // exponation time - T(n) = T(n - 1) + T(n - 2) + const(1) --> O(2^(n/2))\n  if (n <= 2) return 1;\n\n  return fibonacci(n - 1) + fibonacci(n - 2);\n}\n\nint fibonacci_dp(int n) {\n  if (n == 0) return 0;\n  else if (n == 1) return 1;\n\n  map<int, int> fib;\n  fib[0] = 0;\n  fib[1] = 1;\n\n  for (int i = 2; i <= n; ++i)\n    fib[i] = fib[i-1] + fib[i-2];\n\n  return fib[n];\n}\n\nint main() {\n\n  int n = 5, m = 5;\n\n  // recursive algorithm without DP\n  cout << fibonacci(n) << endl;\n\n  // memoized DP algorithm: add in the map. If we have the element in the map, return the result\n  for(int i = 0; i < 20; i++)\n    cout << fibonacci_dp(i) << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "computer_science/algorithms/find_kth_element/find_kth_element_1.cpp",
    "content": "// Finding the kth element algorithm\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n\nusing namespace std;\n\nint find_kth_element(vector<int> &elements, int k) {\n\tsort(elements.begin(), elements.end());\n\treturn elements[k-1];\n}\n\nint main() {\n\tvector<int> elements;\n\telements.push_back(3);\n\telements.push_back(6);\n\telements.push_back(5);\n\telements.push_back(8);\n\telements.push_back(1);\n\telements.push_back(2);\n\telements.push_back(0);\n\n\tcout << find_kth_element(elements, 1) << endl;\n\tcout << find_kth_element(elements, 5) << endl;\n\tcout << find_kth_element(elements, 7) << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "computer_science/algorithms/graphs/bfs.cpp",
    "content": "#include <bits/stdcpp++.h>\n\nusing namespace std;\n\ntypedef pair<int, int> pii;\ntypedef vector<pii> vii;\ntypedef vector<int> vi;\n\nint VISITED = 1;\nint UNVISITED = 0;\nint vertices_number = 100;\nint INF = -1;\n\nvoid bfs(vii AdjList, int s) {\n  vi d(vertices_number, INF); d[s] = 0;\n  queue<int> q;\n  q.push(s);\n\n  while (!queue.empty()) {\n    int u = q.front(); q.pop();\n\n    for (int i = 0; i < AdjList[u].size(); i++) {\n      ii v = AdjList[u][i];\n\n      if (d[v.first] == INF) {\n        d[v.first] = d[u] + 1;\n        q.push(v.first);\n      }\n    }\n  }\n}\n\nint main() {\n  return 0;\n}\n"
  },
  {
    "path": "computer_science/algorithms/graphs/dfs.cpp",
    "content": "#include <bits/stdcpp++.h>\n\nusing namespace std;\n\ntypedef pair<int, int> pii;\ntypedef vector<pii> vii;\ntypedef vector<int> vi;\n\nint VISITED = 1;\nint UNVISITED = 0;\nint vertices_number = 100;\n\nvi dfs_num(vertices_number, 0);\n\nvoid dfs(int u) {\n  dfs_num[u] = VISITED;\n\n  for (int j = 0; j < AdjList[u].size(); j++) {\n    ii v = AdjList[u][j];\n    if (dfs_num[v.first] == UNVISITED) dfs(v.first);\n  }\n}\n\nint main() {\n  return 0;\n}\n"
  },
  {
    "path": "computer_science/algorithms/is-prime/is-prime.js",
    "content": "function isPrime(num) {\n  for (let i = 2, s = Math.sqrt(num); i <= s; i++) {\n    if (num % i === 0) return false;\n  }\n  return num > 1;\n}\n"
  },
  {
    "path": "computer_science/algorithms/kadane/kadane.js",
    "content": "function maxSubArray(nums) {\n  let maxSum = nums[0];\n  let localSum = nums[0];\n\n  for (let index = 1; index < nums.length; index++) {\n    localSum = Math.max(nums[index], localSum + nums[index]);\n    maxSum = Math.max(maxSum, localSum);\n  }\n\n  return maxSum;\n}\n"
  },
  {
    "path": "computer_science/algorithms/knapsack/knapsack1.cpp",
    "content": "#include <stdio.h>\n \nint max(int a, int b) { \n  return (a > b)? a : b; \n}\n \nint knapsack(int totalWeight, int weights[], int values[], int n) {  \n  int K[n+1][totalWeight+1];\n \n  for (int i = 0; i <= n; i++) {\n    for (int j = 0; j <= totalWeight; j++) {\n      if (i == 0 || j == 0) K[i][j] = 0;\n      else if (weights[i-1] <= j) K[i][j] = max(values[i-1] + K[i-1][j - weights[i-1]],  K[i-1][j]);\n      else K[i][j] = K[i-1][j];\n    }\n  }\n \n  return K[n][totalWeight];\n}\n \nint main() {  \n  int values[] = { 4, 1, 2, 5 };\n  int weighs[] = { 100, 100, 120, 80 };\n  int totalWeight = 200;\n  int n = sizeof(values) / sizeof(values[0]);\n  \n  printf(\"%d\\n\", knapsack(totalWeight, weighs, values, n));\n  \n  return 0;\n}"
  },
  {
    "path": "computer_science/algorithms/knapsack/knapsack2.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint max(int a, int b) { \n  return (a > b)? a : b; \n}\n \nint knapsack(int totalWeight, vector<int> &weights, vector<int> &values, int n) {  \n  int K[n+1][totalWeight+1];\n \n  for (int i = 0; i <= n; i++) {\n    for (int j = 0; j <= totalWeight; j++) {\n      if (i == 0 || j == 0) K[i][j] = 0;\n      else if (weights[i-1] <= j) K[i][j] = max(values[i-1] + K[i-1][j - weights[i-1]],  K[i-1][j]);\n      else K[i][j] = K[i-1][j];\n    }\n  }\n \n  return K[n][totalWeight];\n}\n \nint main() {  \n  int v[] = { 4, 1, 2, 5 };\n  int w[] = { 100, 100, 120, 80 };\n  \n  vector<int> values;\n  vector<int> weights;\n\n  for (int i = 0; i < 4; ++i)\n  \tvalues.push_back(v[i]);  \n\n  for (int i = 0; i < 4; ++i)\n\t  weights.push_back(w[i]);\n\n  int totalWeight = 200;\n  int n = values.size();\n  \n  cout << knapsack(totalWeight, weights, values, n) << endl;\n  \n  return 0;\n}"
  },
  {
    "path": "computer_science/algorithms/least_common_multiple/least_common_multiple.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint lcm(int num1, int num2) {\n    int remainder, n1 = num1, n2 = num2;\n\n    do {\n        remainder = n1 % n2;\n        n1 = n2;\n        n2 = remainder;\n    } while (remainder != 0);\n\n    return (num1 * num2) / n1;\n}\n\nint main() {\n\t\n\tcout << lcm(6, 3) << endl;\n\t\n\treturn 0;\n}"
  },
  {
    "path": "computer_science/algorithms/linear-search/linear-search.js",
    "content": "export function linearSearch(list, value) {\n  for (let item of list) {\n    if (item === value) {\n      return true;\n    }\n  }\n\n  return false;\n}\n"
  },
  {
    "path": "computer_science/algorithms/linear-search/tests/linear-search.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { linearSearch } from '../linear-search';\n\ndescribe('linearSearch', () => {\n  it('linear search array', () => {\n    const foo = [1, 3, 4, 69, 71, 81, 90, 99, 420, 1337, 69420];\n\n    expect(linearSearch(foo, 69)).toBeTruthy();\n    expect(linearSearch(foo, 1336)).toBeFalsy();\n    expect(linearSearch(foo, 69420)).toBeTruthy();\n    expect(linearSearch(foo, 69421)).toBeFalsy();\n    expect(linearSearch(foo, 1)).toBeTruthy();\n    expect(linearSearch(foo, 0)).toBeFalsy();\n  });\n});\n"
  },
  {
    "path": "computer_science/algorithms/maximum_subsequence_sum/maximum_subsequence_sum_1.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint maximum_subsequence_sum(int ar[], int n) {\n\tint sum = 0, result = 0;\n\n\tfor (int i = 0; i < n; i++) {\n\t\tif (sum + ar[i] > 0) sum += ar[i];\n\t\telse sum = 0;\n\t\tif (sum > result) result = sum;\n\t}\n\n\treturn result;\n}\n\nint main() {\n\tint n, result;\n\n\tint ar1[] = { 1, -3, 2, -5, 7, 6, -1, -4, 11, -23 };\n\tn = 10;\n\tresult = maximum_subsequence_sum(ar1, n);\n\tcout << result << endl;\n\n\tint ar2[] = { 1, -3, 2, -5, 7 };\n\tn = 5;\n\tresult = maximum_subsequence_sum(ar2, n);\n\tcout << result << endl;\n\n\tint ar3[] = { 1, -3, 6, -5, 7 };\n\tn = 5;\n\tresult = maximum_subsequence_sum(ar3, n);\n\tcout << result << endl;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "computer_science/algorithms/maximum_subsequence_sum/maximum_subsequence_sum_2.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint maximum_subsequence_sum(vector<int> &v) {\n\tint sum = 0, result = 0;\n\n\tfor (int i = 0; i < v.size(); i++) {\n\t\tif (sum + v[i] > 0) sum += v[i];\n\t\telse sum = 0;\n\t\tif (sum > result) result = sum;\n\t}\n\n\treturn result;\n}\n\nint main() {\n\tint result;\n\n\tint ar1[] = { 1, -3, 2, -5, 7, 6, -1, -4, 11, -23 };\n\tvector<int> v1(ar1, ar1 + sizeof(ar1) / sizeof(ar1[0]));\n\tresult = maximum_subsequence_sum(v1);\n\tcout << result << endl;\n\n\tint ar2[] = { 1, -3, 2, -5, 7 };\n\tvector<int> v2(ar2, ar2 + sizeof(ar2) / sizeof(ar2[0]));\n\tresult = maximum_subsequence_sum(v2);\n\tcout << result << endl;\n\n\tint ar3[] = { 1, -3, 6, -5, 7 };\n\tvector<int> v3(ar3, ar3 + sizeof(ar3) / sizeof(ar3[0]));\n\tresult = maximum_subsequence_sum(v3);\n\tcout << result << endl;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "computer_science/algorithms/min_and_max/minimax.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid minimax(int v[], int n, int &a, int &b) {\n\ta = v[0];\n\tb = v[0];\n\n\tfor (int i = 1; i < n; i++) {\n\t\tif (a > v[i]) a = v[i];\n\t\tif (b < v[i]) b = v[i];\n\t}\n}\n\nint main() {\n\n\tint v[] = { 1, 4, 6, 22 };\n\tint a, b;\n\n\tminimax(v, 4, a, b);\n\n\tcout << \"a: \" << a << endl;\n\tcout << \"b: \" << b << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "computer_science/algorithms/parse_strings/parse_strings.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nvector<string> parse_string(string line) {\n\tvector<string> v;\n\tstring word = \"\";\n\t\n\tfor (int i = 0; i < line.size(); i++) {\n\t\tif (line[i] == ' ') {\n\t\t\tv.push_back(word);\n\t\t\tword.clear();\n\t\t} else if (i == line.size() - 1) {\n\t\t\tword += line[i];\n\t\t\tv.push_back(word);\n\t\t\tword.clear();\n\t\t} else {\n\t\t\tword += line[i];\n\t\t}\n\t}\n\t\n\treturn v;\n}\n\nint main() {\n\t\n\tstring s = \"Top Coder comp Wedn at midnight\";\n\tvector<string> strings = parse_string(s);\n\t\t\n\tfor (int i = 0; i < strings.size(); i++) cout << strings[i] << endl;\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "computer_science/algorithms/pointers/pointer.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int n = 10;\n  int *p;\n  p = &n;\n\n  cout << \"N value: \" << n << endl;\n  cout << \"Address pointed by P: \" << p << endl;\n  cout << \"Value from the address pointed by P: \" << *p << endl;\n\n  *p = 20;\n\n  cout << \"Changed the value from the address pointed by P: \" << *p << endl;\n  cout << \"New N value: \" << n << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "computer_science/algorithms/prime_number/prime_number.cpp",
    "content": "#include <iostream>\n#include <math.h>\n\nusing namespace std;\n\nbool is_prime_number(int n) {\n\tif (n < 2) return false;\n  if (n == 2) return true;\n\tif ((n % 2) == 0) return false;\n\t\n  int s = sqrt(n);\n\t\n  for (int i = 3; i <= s; i += 2) \n    if (n % i == 0) return false;\n\t\n  return true;\n}\n\nint main() {\n  int n;\n  cin >> n;\n\n  while (n) {\n    if (is_prime_number(n)) cout << \"True\" << endl;\n    else cout << \"False\" << endl;\n    cin >> n;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "computer_science/algorithms/recursion/fibonacci/fibonacci.c",
    "content": "#include <stdio.h>\n#include <string.h>\n\nint fibonacciHelper(int n, int first, int second);\nint fibonacci(int n);\n\nint main() {\n  fibonacci(10);\n  return 0;\n}\n\nint fibonacciHelper(int n, int first, int second) {\n  if (n == 1) return 0;\n  if (n == 2) return 1;\n  printf(\"%d\\n\", second);\n  return fibonacciHelper(n - 1, second, first + second);\n}\n\nint fibonacci(int n) {\n  return fibonacciHelper(n, 1, 0);\n}\n"
  },
  {
    "path": "computer_science/algorithms/recursion/fibonacci/fibonacci.py",
    "content": "# Fibonacci Sequence: 0 1 1 2 3 5 8 13 ...\n\ndef fibonacci(num):\n    if num == 1:\n        return 0\n\n    if num == 2:\n        return 1\n\n    return fibonacci(num-1) + fibonacci(num-2)\n\n\nprint(fibonacci(1))\nprint(fibonacci(2))\nprint(fibonacci(3))\nprint(fibonacci(4))\nprint(fibonacci(5))\n"
  },
  {
    "path": "computer_science/algorithms/recursion/log_2.c",
    "content": "#include <stdio.h>\n#include <string.h>\n\nint log_2(int n);\n\nint main() {\n  int i;\n  for (i = 1; i <= 16; i++) printf(\"%d\\n\", log_2(i));\n  return 0;\n}\n\nint log_2(int n) {\n  if (n <= 1) return 0;\n  return 1 + log_2(n / 2);\n}\n"
  },
  {
    "path": "computer_science/algorithms/recursion/palindromo.c",
    "content": "#include <stdio.h>\n#include <string.h>\n\nint palindromo(char *n);\n\nint main() {\n  char num1[6] = { '3', '6', '9', '9', '6', '3' };\n  char *n1 = num1;\n\n  if (palindromo(n1)) printf(\"É palíndromo\\n\");\n  else printf(\"Não é palíndromo\\n\");\n\n  char num2[6] = { '3', '6', '0', '9', '6', '3' };\n  char *n2 = num2;\n\n  if (palindromo(n2)) printf(\"É palíndromo\\n\");\n  else printf(\"Não é palíndromo\\n\");\n\n  return 0;\n}\n\nint palindromo(char *n) {\n  if (strlen(n) <= 1) return 1;\n  char first = n[0], last = n[strlen(n)-1];\n  memmove(n, n+1, strlen(n));\n  n[strlen(n)-1] = 0;\n  return (first == last) * palindromo(n);\n}\n"
  },
  {
    "path": "computer_science/algorithms/recursion/regua.c",
    "content": "#include <stdio.h>\n\nvoid regua (int n) {\n  if (n == 1) printf(\"-\\n\");\n  else {\n    regua(n-1);\n    int i;\n    for (i=0; i<n; i++) printf(\"-\");\n    printf(\"\\n\");\n    regua(n-1);\n  }\n}\n\nint main() {\n  regua(5);\n}\n"
  },
  {
    "path": "computer_science/algorithms/recursion/reverse.c",
    "content": "#include <stdio.h>\n#include <string.h>\n\nint reverse(char *str);\n\nint main() {\n  char str[7] = { 'l', 'e', 'a', 'n', 'd', 'r', 'o' };\n  char *name = str;\n  reverse(name);\n  return 0;\n}\n\nint reverse(char *str) {\n  if (strlen(str) == 0) return 0;\n  printf(\"%c\", str[strlen(str)-1]);\n  str[strlen(str)-1] = 0;\n  return reverse(str);\n}\n"
  },
  {
    "path": "computer_science/algorithms/recursion/sum.py",
    "content": "def list_sum(list):\n    if len(list) == 1:\n        return list[0]\n    else:\n        return list[0] + list_sum(list[1:])\n\nlist = [1, 2, 3, 4, 5]\nprint(list_sum(list))\n\nlist = [0, 1, 0, 0, 0]\nprint(list_sum(list))\n\nlist = [1, 2, 1, 1, 10]\nprint(list_sum(list))\n"
  },
  {
    "path": "computer_science/algorithms/reverse-string/reverse-string-in-place.js",
    "content": "function reverseString(s) {\n  let pointer1 = 0;\n  let pointer2 = s.length - 1;\n  let auxiliaryChar;\n\n  while (pointer1 < pointer2) {\n    auxiliaryChar = s[pointer1];\n    s[pointer1] = s[pointer2];\n    s[pointer2] = auxiliaryChar;\n    pointer1++;\n    pointer2--;\n  }\n}\n"
  },
  {
    "path": "computer_science/algorithms/reverse-string/reverse-string.js",
    "content": "export function reverseString(s) {\n  const arraysOfChars = [];\n\n  for (let index = s.length - 1; index >= 0; index--) {\n    arraysOfChars.push(s[index]);\n  }\n\n  return arraysOfChars.join('');\n}\n"
  },
  {
    "path": "computer_science/algorithms/reverse-string/tests/reverse-string.test.js",
    "content": "import { it, test, expect } from 'vitest';\n\ntest('reverseString', () => {\n  it('returns the reversed string', () => {\n    expect(reverseString('asdfghjkl')).toEqual('lkjhgfdsa');\n  });\n\n  it('returns the reversed string', () => {\n    expect(reverseString('lkjhgfdsa')).toEqual('asdfghjkl');\n  });\n\n  it('returns the reversed string', () => {\n    expect(reverseString('')).toEqual('');\n  });\n});\n"
  },
  {
    "path": "computer_science/algorithms/search/binary_search.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint binary_search(vector<int> &v, int element) {\n\t\n\tint NOT_FOUND = -1;\n\tint low = 0, high = v.size()-1, mid;\n\n\twhile (low <= high) {\n\t\tmid = (low + high) / 2;\n\t\tif (v[mid] < element) low = mid + 1;\n\t\telse if (v[mid] > element) high = mid -1;\n\t\telse return mid;\n\t}\n\n\treturn NOT_FOUND;\n}\n\nint main() {\n\t\n\tint ar[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\n\tvector<int> v(ar, ar + sizeof(ar) / sizeof(ar[0]));\n\n\tint element = binary_search(v, 7);\n\tcout << element << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "computer_science/algorithms/search/binary_search.py",
    "content": "def binary_search(list, item):\n    first_index = 0\n    last_index = len(list)-1\n\n    while first_index <= last_index:\n        middle_index = (first_index + last_index) // 2\n\n        if item == list[middle_index]:\n            return True\n        elif item > list[middle_index]:\n            first_index = middle_index + 1\n        else:\n            last_index = middle_index - 1\n\n    return False\n\nlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nprint(binary_search(list, 8))\nprint(binary_search(list, 0))\nprint(binary_search(list, 10))\nprint(binary_search(list, 89))\n\nother_list = [0, 1, 2, 8, 13, 17, 19, 32, 42,]\nprint(binary_search(other_list, 3))\nprint(binary_search(other_list, 13))\n"
  },
  {
    "path": "computer_science/algorithms/search/recursive_binary_search.py",
    "content": "def binary_search(list, item):\n    if len(list) == 0:\n        return False\n\n    middle_index = (len(list) - 1) // 2\n\n    if item == list[middle_index]:\n        return True\n    elif item > list[middle_index]:\n        return binary_search(list[middle_index+1:], item)\n    else:\n        return binary_search(list[:middle_index-1], item)\n\nlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nprint(binary_search(list, 8))\nprint(binary_search(list, 0))\nprint(binary_search(list, 10))\nprint(binary_search(list, 89))\n\nother_list = [0, 1, 2, 8, 13, 17, 19, 32, 42,]\nprint(binary_search(other_list, 3))\nprint(binary_search(other_list, 13))\n"
  },
  {
    "path": "computer_science/algorithms/search/sequential_search.py",
    "content": "def sequential_search(list, item):\n    for element in list:\n        if element == item:\n            return True\n\n    return False\n\nlist = [1, 2, 32, 8, 17, 19, 42, 13, 0]\nprint(sequential_search(list, 3))\nprint(sequential_search(list, 13))\n"
  },
  {
    "path": "computer_science/algorithms/segment-tree/sum/lazy_update.cpp",
    "content": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define MAX_SIZE (1 << 20)\n\nint segtree[MAX_SIZE];\nint lazy[MAX_SIZE];\n\nvoid lazy_update(int p, int start, int end, int left, int right, int inc) {\n  if (lazy[p] != 0) {\n    segtree[p] = (end - start + 1) * lazy[p];\n\n    if (start != end) {\n      lazy[p * 2] = lazy[p];\n      lazy[p * 2] = lazy[p];\n    }\n\n    lazy[p] = 0;\n  }\n\n  if (end < left || start > right) return; // Totally out of range\n\n  if (start >= left && end <= right) { // Totally in the range\n    segtree[p] = (end - start + 1) * inc;\n\n    if (start != end) { // Not a leaf\n      lazy[p * 2] += inc;\n      lazy[p * 2 + 1] += inc;\n    }\n\n    return;\n  }\n\n  // Partially in the range\n  int middle = (start + end) / 2;\n  lazy_update(p * 2, start, middle, left, right, inc);\n  lazy_update(p * 2 + 1, middle + 1, end, left, right, inc);\n  segtree[p] = segtree[p * 2] + segtree[p * 2 + 1];\n}\n\nint main() {\n  return 0;\n}\n"
  },
  {
    "path": "computer_science/algorithms/sorting/bubble_sort/bubble_sort.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\n#define swap(a, b) { int x=a; a=b; b=x; }\n\nvoid bubble_sort(int v[], int n) {\n  for (int i = 1; i <= n - 1; i++) {\n    for (int j = 0; j < n - i; j++) {\n      if (v[j] > v[j+1]) swap(v[j], v[j+1]);\n    }\n  }\n}\n\nint main() {\n\tint ar[] = { 33,23,10,9,1 };\n\n\tfor (int i = 0; i < 5; i++) cout << ar[i] << \" \";\n\tcout << endl;\n\n\tbubble_sort(ar, 5);\n\n\tfor (int i = 0; i < 5; i++) cout << ar[i] << \" \";\n\tcout << endl;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "computer_science/algorithms/sorting/bubble_sort/bubble_sort.py",
    "content": "def bubble_sort(ar):\n    for i in range(len(ar)):\n        for k in range(i, len(ar)-1):\n            if ar[k] > ar[k+1]:\n                ar[k], ar[k+1] = ar[k+1], ar[k]\n"
  },
  {
    "path": "computer_science/algorithms/sorting/bubble_sort/test_bubble_sort.py",
    "content": "from bubble_sort import bubble_sort\n\nar = [4, 2, 3, 10, 22, 11, 9]\nbubble_sort(ar)\nprint(ar)\n"
  },
  {
    "path": "computer_science/algorithms/sorting/insertion_sort.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid insertion_sort(int n, int array[]) {\n\tint x, j;\n\tfor (int i = 1; i < n; i++) {\n\t\tx = array[i];\n\n\t\tfor (j = i - 1; j >= 0 && array[j] > x; j--)\n\t\t\tarray[j+1] = array[j];\n\n\t\tarray[j+1] = x;\n\t}\n}\n\nint main() {\n\n\tint array[] = { 17, 3, 2, 10 };\n\n\tinsertion_sort(4, array);\n\n\tfor (int i = 0; i < 4; i++) cout << array[i] << \" \";\n\n\treturn 0;\n}\n"
  },
  {
    "path": "computer_science/algorithms/sorting/merge_sort.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvector<int> merge(vector<int>& vec, const vector<int>& left, const vector<int>& right) {\n\n  vector<int> result;\n  unsigned left_it = 0, right_it = 0;\n\n  while (left_it < left.size() && right_it < right.size()) {\n    if (left[left_it] < right[right_it]) {\n      result.push_back(left[left_it]);\n      left_it++;\n    } else {\n      result.push_back(right[right_it]);\n      right_it++;\n    }\n  }\n\n  while (left_it < left.size()) {\n    result.push_back(left[left_it]);\n    left_it++;\n  }\n\n  while (right_it < right.size()) {\n    result.push_back(right[right_it]);\n    right_it++;\n  }\n\n  vec = result;\n  return vec;\n}\n\nvector<int> merge_sort(vector<int>& vec) {\n\n  if (vec.size() == 1) return vec;\n\n  vector<int>::iterator middle = vec.begin() + (vec.size() / 2);\n\n  vector<int> left(vec.begin(), middle);\n  vector<int> right(middle, vec.end());\n\n  left = merge_sort(left);\n  right = merge_sort(right);\n\n  return merge(vec, left, right);\n}\n\nint main() {\n\n   vector<int> v;\n\n   v.push_back(2);\n   v.push_back(3);\n   v.push_back(6);\n   v.push_back(4);\n   v.push_back(5);\n   v.push_back(8);\n   v.push_back(7);\n   v.push_back(1);\n\n   merge_sort(v);\n\n   for (int i = 0; i < v.size(); i++) cout << v[i] << \" \";\n\n   return 0;\n}\n"
  },
  {
    "path": "computer_science/algorithms/sorting/reverse_insertion_sort.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid reverse_insertion_sort(int n, int array[]) {\n\tint x, j;\n\tfor (int i = 1; i < n; i++) {\n\t\tx = array[i];\t\t\n\t\tfor (j = i - 1; j >= 0 && array[j] < x; j--) array[j+1] = array[j];\n\t\tarray[j+1] = x;\n\t}\n}\n\nint main() {\n\n\tint array[] = { 17, 3, 2, 10 };\n\n\treverse_insertion_sort(4, array);\n\n\tfor (int i = 0; i < 4; i++) cout << array[i] << \" \";\n\n\treturn 0;\n}"
  },
  {
    "path": "computer_science/algorithms/sorting/selection_sort.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\n#define swap(a, b) { int x=a; a=b; b=x; }\n\nvoid selection_sort(int v[], int n) {\n  for (int i = 0; i < n - 1; i++) {\n  \tint smaller_position = i;\n    for (int j = i + 1; j < n; j++) if (v[j] < v[smaller_position]) smaller_position = j;\n  \tif (smaller_position != i) swap(v[i], v[smaller_position]);\n  }\n}\n\nint main() {\n\tint ar[] = { 33,23,10,9,1 };\n\t\n\tfor (int i = 0; i < 5; i++) cout << ar[i] << \" \";\n\tcout << endl;\n\t\n\tselection_sort(ar, 5);\n\t\n\tfor (int i = 0; i < 5; i++) cout << ar[i] << \" \";\n\tcout << endl;\n\t\n\treturn 0;\n}"
  },
  {
    "path": "computer_science/algorithms/sorting/string_insertion_sort.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid insertion_sort(int n, char array[]) {\n  int i, j;\n  char x;\n\n  for (i = 1; i < n; i++) {\n    x = array[i];\n\n    for (j = i - 1; j >= 0 && array[j] - '0' > x - '0'; j--)\n      array[j+1] = array[j];\n\n    array[j+1] = x;\n  }\n}\n\nint main() {\n\n  char array[] = { 'l', 'e', 'a', 'n', 'd', 'r', 'o' };\n\n  insertion_sort(7, array);\n\n  for (int i = 0; i < 7; i++) cout << array[i];\n\n  return 0;\n}\n"
  },
  {
    "path": "computer_science/algorithms/string_to_int/string_to_int.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <math.h>\n\nusing namespace std;\n\nint to_digit_test(char digit) {\n  string numbers = \"0123456789\";\n  return numbers.find(digit);\n}\n\nint to_digit(char digit) {\n  return digit - '0';\n}\n\nint string_to_number(string n) {\n  if (n == \"\") {\n    return -1;\n  } else {\n    int num = 0;\n\n    for (int i = 0; i < n.size(); i++) {\n      num = num * 10 + to_digit(n[i]);\n    }\n\n    return num;\n  }\n}\n\nint string_to_int(string n) {\n\tint num = 0, digit, pot = n.size()-1;\n\n\tfor (int i = 0; i < n.size(); i++) {\n\t\tdigit = n[i] - 48;\n\t\tnum += pow(10, pot) * digit;\n\t\tpot--;\n\t}\n\n\treturn num;\n}\n\nint main() {\n\t\n\tstring n1 = \"2\", n2 = \"33\", n3 = \"457\", n4 = \"1023\", n5 = \"54739\";\n\n\tcout << string_to_int(n1) << endl;\n\tcout << string_to_int(n2) << endl;\n\tcout << string_to_int(n3) << endl;\n\tcout << string_to_int(n4) << endl;\n\tcout << string_to_int(n5) << endl;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "computer_science/algorithms/subset/subset.js",
    "content": "function getAllSubsets(subset, nums, output, index) {\n  if (index == nums.length) {\n    subset.push(output);\n    return;\n  }\n\n  getAllSubsets(subset, nums, [...output], index + 1);\n  output.push(nums[index]);\n  getAllSubsets(subset, nums, [...output], index + 1);\n}\n"
  },
  {
    "path": "computer_science/big_o/README.md",
    "content": "<samp>\n\n# Big O\n\nA generalize way to categorize an algorithm time and space based on input.\n\n- Growth based on input\n- Drop constants\n- Consider the worst case\n\n## Big O complexity\n\n- O(1)\n- O(logn)\n- O(n)\n- O(nlogn)\n- O(n^2)\n- O(n!)\n\n## Examples\n\n### O(n)\n\n```javascript\nfunction sumCharCodes(n) {\n  let sum = 0;\n\n  for (let i = 0; i < n.length; ++i) {\n    sum += n.charCodeAt(i);\n  }\n\n  for (let i = 0; i < n.length; ++i) {\n    sum += n.charCodeAt(i);\n  }\n\n  return sum;\n}\n```\n\n### O(n^2)\n\n```javascript\nfunction sumCharCodes(n) {\n  let sum = 0;\n\n  for (let i = 0; i < n.length; ++i) {\n    for (let j = 0; j < n.length; ++j) {\n      sum += charCode;\n    }\n  }\n\n  return sum;\n}\n```\n\n### O(n^3)\n\n```javascript\nfunction sumCharCodes(n) {\n  let sum = 0;\n\n  for (let i = 0; i < n.length; ++i) {\n    for (let j = 0; j < n.length; ++j) {\n      for (let k = 0; k < n.length; ++k) {\n        sum += charCode;\n      }\n    }\n  }\n\n  return sum;\n}\n```\n\n</samp>\n"
  },
  {
    "path": "computer_science/big_o/example1.py",
    "content": "def foo(array):\n    sum = 0\n    product = 1\n\n    for element in array:\n        sum += element\n\n    for element in array:\n        product *= element\n\n    print(\"%d, %d\" %(sum, product))\n\nfoo([1, 2, 3, 4, 5])\n\n# The complexity of the foo function is: O(N)\n# Initializing sum and product = 1 + 1 = 2\n# We iterate through the array two times = 2 * length(array) = 2 * N\n# Printing sum and product = 1\n# Conclusion: O(2N + 3) = O(N)\n"
  },
  {
    "path": "computer_science/big_o/example10.py",
    "content": "from math import sqrt\n\ndef is_prime(num):\n    if num < 2:\n        return False\n\n    if num == 2:\n        return True\n\n    if num % 2 == 0:\n        return False\n\n    for i in range(3, int(sqrt(num)) + 1, 2):\n        if num % i == 0:\n            return False\n\n    return True\n\nprint(is_prime(1)) # False\nprint(is_prime(2)) # True\nprint(is_prime(9)) # False\nprint(is_prime(17)) # True\nprint(is_prime(24)) # False\n\n# is prime function has complexity of O(sqrt(N))\n"
  },
  {
    "path": "computer_science/big_o/example11.py",
    "content": "def factorial(n):\n    if n < 0:\n        return -1\n\n    if n == 0:\n        return 1\n\n    return n * factorial(n - 1)\n\n# factorial function has a complexity of O(N)\n"
  },
  {
    "path": "computer_science/big_o/example12.py",
    "content": "def permutation(str):\n    handle_permutation(str, \"\")\n\ndef handle_permutation(str, prefix):\n    if len(str) == 0:\n        print(prefix)\n    else:\n        for i in range(len(str)):\n            rem = str[0:i] + str[i+1:]\n            handle_permutation(rem, prefix + str[i])\n\npermutation('abc')\n"
  },
  {
    "path": "computer_science/big_o/example13.py",
    "content": "def fib(n):\n    if n == 0:\n        return 0\n\n    if n == 1:\n        return 1\n\n    return fib(n - 1) + fib(n - 2)\n\nprint(fib(1))\nprint(fib(4))\nprint(fib(5))\nprint(fib(10))\n"
  },
  {
    "path": "computer_science/big_o/example14.py",
    "content": "def all_fib(n):\n    for i in range(n):\n        print(fib(i))\n\ndef fib(n):\n    if n == 0:\n        return 0\n\n    if n == 1:\n        return 1\n\n    return fib(n - 1) + fib(n - 2)\n\nall_fib(10)\n\n# Complexity: O(2 ^ (n+1))\n"
  },
  {
    "path": "computer_science/big_o/example15.py",
    "content": "def all_fib(n):\n    memo = []\n    memo.append(0)\n    memo.append(1)\n\n    for i in range(n):\n        print(\"%d: %d\" %(i, fib(i, memo)))\n\ndef fib(n, memo):\n    if n <= len(memo) - 1:\n        return memo[n]\n\n    memo.append(fib(n - 1, memo) + fib(n - 2, memo))\n    return memo[n]\n\nall_fib(7)\n\n# Complexity: O(N)\n# All previous actions are already computed\n"
  },
  {
    "path": "computer_science/big_o/example16.py",
    "content": "def powers_of_2(n):\n    if n <= 0:\n        return 0\n\n    if n == 1:\n        print(1)\n        return 1\n\n    previous = powers_of_2(n / 2)\n    current = previous * 2\n    print(current)\n    return current\n\npowers_of_2(4)\n\n# Complexity: O(log N)\n"
  },
  {
    "path": "computer_science/big_o/example17.py",
    "content": "def product(a, b):\n    sum = 0\n    for i in range(b):\n        sum += a\n\n    return sum\n\nprint(product(2, 4))\n\n# Complexity: O(b) | O(N)\n"
  },
  {
    "path": "computer_science/big_o/example18.py",
    "content": "def power(a, b):\n    if b < 0:\n        return 0\n    elif b == 0:\n        return 1\n    else:\n        return a * power(a, b - 1)\n\nprint(power(2, 2))\nprint(power(2, 10))\nprint(power(3, 2))\n\n# Complexity: O(B)\n"
  },
  {
    "path": "computer_science/big_o/example19.py",
    "content": "def mod(a, b):\n    if b > a:\n        return a\n\n    return mod(a - b, b)\n\nprint(mod(10, 2))\nprint(mod(10, 3))\nprint(mod(10, 4))\nprint(mod(10, 5))\nprint(mod(10, 6))\n\n# Complexity: O(a / b)\n\ndef mod(a, b):\n    if b <= 0:\n        return -1\n\n    div = a / b\n    return a - div * b\n\n# Complexity: O(1)\n"
  },
  {
    "path": "computer_science/big_o/example2.py",
    "content": "def print_pairs(array):\n    for i in array:\n        for j in array:\n            print(\"%d, %d\" %(i, j))\n\nprint_pairs([1, 2, 3, 4, 5])\n\n# The complexity of the print_pairs function is: O(N^2)\n# We do a nested loop = length(array) ^ 2 = N * 2\n# There are O(N^2) pairs\n# Conclusion: O(N^2)\n"
  },
  {
    "path": "computer_science/big_o/example20.py",
    "content": "def div(a, b):\n    count = 0\n    sum = b\n\n    while sum <= a:\n        sum += b\n        count += 1\n\n    return count\n\nprint(div(10, 5))\nprint(div(10, 2))\nprint(div(10, 3))\nprint(div(10, 11))\n\n# Complexity: O(a / b)\n"
  },
  {
    "path": "computer_science/big_o/example21.py",
    "content": "def sqrt(n):\n    return sqrt_helper(n, 1, n)\n\ndef sqrt_helper(n, min, max):\n    if min > max:\n        return -1\n\n    guess = (min + max) / 2\n\n    if guess * guess > n:\n        return sqrt_helper(n, min, guess - 1)\n    elif guess * guess < n:\n        return sqrt_helper(n, guess + 1, max)\n    else:\n        return guess\n\nprint(sqrt(100))\nprint(sqrt(9))\nprint(sqrt(25))\nprint(sqrt(3))\n\n# Complexity: O(log N) --> It is a binary search algorithm\n"
  },
  {
    "path": "computer_science/big_o/example22.py",
    "content": "from math import sqrt\n\ndef square_root(n):\n    for guess in range(int(sqrt(n))+1):\n        if guess * guess == n:\n            return guess\n\n    return -1\n\nprint(square_root(100))\nprint(square_root(9))\nprint(square_root(25))\nprint(square_root(3))\n\n# Complexity: O(log N) --> It is a binary search algorithm\n"
  },
  {
    "path": "computer_science/big_o/example3.py",
    "content": "def print_unordered_pairs(array):\n    for i in range(len(array)):\n        for j in range(i+1, len(array)):\n            print(\"%d, %d\" %(array[i], array[j]))\n\nprint_unordered_pairs([1, 2, 3, 4, 5])\n\n# The complexity of the print_unordered_pairs function is: O(N^2)\n# We do a nested loop = length(array) * (length(array) - 1) / 2 = (length(array) * 2 - length(array)) / 2 = (N^2 - N) / 2\n# There are O((N^2 - N) / 2) pairs\n# Conclusion: O(N^2)\n"
  },
  {
    "path": "computer_science/big_o/example4.py",
    "content": "def print_unordered_pairs(array_a, array_b):\n    for a in array_a:\n        for b in array_b:\n            if a < b:\n                print('%d, %d' %(a, b))\n\nprint_unordered_pairs([1, 2, 3, 4, 5], [3, 1, 2, 5, 4])\n\n# The complexity of the print_unordered_pairs function is: O(N^2)\n# We do a nested loop = length(array_a) * length(array_b) = N^2\n# There are O(N^2) pairs\n# Conclusion: O(N^2)\n"
  },
  {
    "path": "computer_science/big_o/example5.py",
    "content": "def print_unordered_pairs(array_a, array_b):\n    for a in array_a:\n        for b in array_b:\n            for i in range(1000000):\n                print('%d, %d' %(a, b))\n\nprint_unordered_pairs([1, 2, 3, 4, 5], [3, 1, 2, 5, 4])\n\n# The complexity of the print_unordered_pairs function is: O(N^2)\n# We do a nested loop = length(array_a) * length(array_b) * 1000000 = N^2 * 1000000\n# There are O(N^2 * 1000000) pairs\n# Conclusion: O(N^2)\n"
  },
  {
    "path": "computer_science/big_o/example6.py",
    "content": "def reverse(array):\n    for i in range(len(array) / 2):\n        index = len(array) - i - 1\n        temporary_num = array[index]\n        array[index] = array[i]\n        array[i] = temporary_num\n\n    return array\n\nnew_array = reverse(list(range(1, 6))\n\nfor i in new_array:\n    print(i)\n\n# The complexity of the reverse function is: O(N)\n# Even though we iterate only through half of the array (O(N/2)), we still consider this a O(N) complexity\n# Conclusion: O(N)\n"
  },
  {
    "path": "computer_science/big_o/example7.py",
    "content": "# O(N + P), if P < N / 2 --> O(N)\n# O(2N) --> O(N)\n# O(N + logN) --> O(N)\n# O(N + M), if N > M then O(N), otherwise O(M)\n"
  },
  {
    "path": "computer_science/big_o/example9.py",
    "content": "def sum(node):\n    if node is None:\n        return 0\n\n    return sum(node.left) + node.value + sum(node.right)\n\n# If we have N nodes in our tree, this will be O(N) complexity\n"
  },
  {
    "path": "computer_science/data_structures/array/array.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n  int A[4]; // 4 bytes x 4 integers = 16 bytes\n  A[0] = 0, A[1] = 1, A[2] = 2, A[3] = 3;\n  cout << A << endl; // address of A array first element\n  cout << *A << endl; // value of first element from A array | Same as A[0]\n\n  return 0;\n}\n"
  },
  {
    "path": "computer_science/data_structures/array/big_o.py",
    "content": "# Array Big O complexity\n\n# Append (insert/push): O(1) - Constant Time\n# Pop (remove): O(1) - Constant Time\n# Sort: O(N log N)\n# Reverse: O(N) - Linear Time\n"
  },
  {
    "path": "computer_science/data_structures/array/list.py",
    "content": "a = [1, 2, 3, 4, 5]\nprint(a)\n\na.append(6) # O(1)\nprint(a)\n\na.append('hello')\nprint(a)\n\na.append([1, 2])\nprint(a)\n\na.pop() # O(1)\nprint(a)\n\na.pop()\nprint(a)\n\nprint(a[0])\nprint(a[3])\n\na[2] = 33\n\n# immutable sorting\nsorted_a = sorted(a)\nprint(sorted_a)\n\n# in place sorting: O(N log N)\na.sort()\nprint(a)\n\n# in place reverse: O(N)\na.reverse()\nprint(a)\n\n# length of an array\nlength = len(a)\nprint(length)\n\n# min and max\nmin = min(a)\nmax = max(a)\nprint(min)\nprint(max)"
  },
  {
    "path": "computer_science/data_structures/array/vectors.cpp",
    "content": "#include <string>\n#include <vector>\n#include <iostream>\n#include <algorithm>\n\nusing namespace std;\n\n// passing vector as reference\nvoid desc_sort(vector<int> &v) {\n  sort(v.begin(), v.end(), greater<int>());\n}\n\n// passing vector as pointer\nvoid desc_sort(vector<int> *v) {\n  sort(v->begin(), v->end(), greater<int>());\n}\n\nint main() {\n  vector<int> v;\n  v.push_back(1);\n  v.push_back(2);\n  v.push_back(3);\n  v.push_back(4);\n  v.push_back(10);\n\n  for (int i = 0; i < v.size(); i++)\n    cout << v[i] << endl;\n\n  string arr[] = { \"bla\", \"ble\", \"bli\" };\n  vector<string> v3(arr, arr + sizeof(arr) / sizeof(arr[0]));\n\n  for (int i = 0; i < v3.size(); i++)\n    cout << v3[i] << endl;\n\n  int ar[] = { 1, 2, 3, 4, 5 };\n  vector<int> v2(ar, ar + sizeof(ar) / sizeof(ar[0]));\n\n  for (int i = 0; i < v2.size(); i++)\n    cout << v2[i] << endl;\n\n  cout << v.size() << endl;\n\n  // remove last element\n  v.pop_back();\n\n  // remove first element\n  v.erase(v.begin());\n\n  // remove first element\n  v.erase(v.begin()+0);\n\n  // remove the last element using erase\n  v.erase(v.begin() + v.size() - 1);\n\n  for (int i = 0; i < v.size(); i++)\n    cout << v[i] << endl;\n\n  cout << v.size() << endl;\n\n  // making a pair of integers in the vector\n  vector< pair<int, int> > pairs;\n  pairs.push_back(make_pair(4, 1));\n  pairs.push_back(make_pair(3, 1));\n  pairs.push_back(make_pair(2, 1));\n  pairs.push_back(make_pair(5, 1));\n  pairs.push_back(make_pair(7, 1));\n  pairs.push_back(make_pair(2, 1));\n\n  pairs[0].first = 0;\n  pairs.back().second++;\n\n  // sort vector of pairs based on the first element\n  sort(pairs.begin(), pairs.end());\n\n  for (int i = 0; i < pairs.size(); i++)\n    cout << pairs[i].first << \" \" << pairs[i].second << endl;\n\n  // sort from end to begin of the vector\n  vector<int> vetor;\n  vetor.push_back(1);\n  vetor.push_back(2);\n  vetor.push_back(3);\n  vetor.push_back(4);\n  vetor.push_back(10);\n\n  desc_sort(vetor);\n\n  for (int i = 0; i < vetor.size(); i++)\n    cout << vetor[i] << endl;\n\n  vector<int> vetorzin;\n  vetorzin.push_back(1);\n  vetorzin.push_back(2);\n  vetorzin.push_back(3);\n  vetorzin.push_back(4);\n  vetorzin.push_back(10);\n\n  desc_sort(&vetorzin);\n\n  int removing = 0;\n\n  vetorzin.erase(vetorzin.begin() + 1);\n  removing++;\n  vetorzin.erase(vetorzin.begin() + 2 - removing);\n\n  for (int i = 0; i < vetorzin.size(); i++)\n    cout << vetorzin[i] << endl;\n\n  // implement reverse\n  reverse(vetorzin.begin(), vetorzin.end());\n\n  // matrix\n  vector< vector<int> > matrix;\n  vector<int> v;\n\n  for (int i = 0; i < 10; i++) {\n    for (int j = 0; j < 10; j++) {\n      v.push_back(i);\n    }\n\n    matrix.push_back(v);\n    v.clear()\n  }\n\n  // iterators\n  vector<int> vec;\n  vec.push_back(100);\n  vec.push_back(99);\n\n  vec.begin();\n  vec.end();\n\n  // capacity\n  vec.size();\n  vec.empty();\n\n  // element access\n  cout << vec[0] << endl;\n  cout << vec[1] << endl;\n  cout << vec.at(0) << endl;\n  cout << vec.front() << endl;\n  cout << vec.back() << endl;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "computer_science/data_structures/binary-heap/README.md",
    "content": "# Binary Heap\n\n- A complete binary tree (all levels have both the left and right children)\n- It's a min or max heap\n- Min heap: quickly get the minimum value of the tree\n  - Root node holds the minimum value\n  - Every child node needs to be greater than or equal to the parent node\n- Max heap: quickly get the maximum value of the tree\n  - Root node holds the maximum value\n  - Every child node needs to be smaller than or equal to the parent node\n"
  },
  {
    "path": "computer_science/data_structures/binary-heap/min-heap.js",
    "content": "export class MinHeap {\n  constructor() {\n    this.heap = [];\n  }\n\n  insert(value) {\n    if (value != null) {\n      this.heap.push(value);\n      this.siftUp(this.heap.length - 1);\n      return true;\n    }\n    return false;\n  }\n\n  extract() {\n    if (this.isEmpty()) {\n      return undefined;\n    }\n\n    if (this.size() === 1) {\n      return this.heap.shift();\n    }\n\n    const removedValue = this.heap.shift();\n    this.siftDown(0);\n    return removedValue;\n  }\n\n  size() {\n    return this.heap.length;\n  }\n\n  isEmpty() {\n    return this.size() === 0;\n  }\n\n  findMinimum() {\n    return this.isEmpty() ? undefined : this.heap[0];\n  }\n\n  siftUp(index) {\n    let parentIndex = this.getParentIndex(index);\n    while (index > 0 && this.heap[index] < this.heap[parentIndex]) {\n      this.swap(parentIndex, index);\n      index = parentIndex;\n      parentIndex = this.getParentIndex(index);\n    }\n  }\n\n  siftDown(index) {\n    let elementIndex = index;\n    let leftIndex = this.getLeftIndex(index);\n    let rightIndex = this.getRightIndex(index);\n    let size = this.size();\n\n    if (leftIndex < size && this.heap[leftIndex] < this.heap[elementIndex]) {\n      elementIndex = leftIndex;\n    }\n\n    if (rightIndex < size && this.heap[rightIndex] < this.heap[elementIndex]) {\n      elementIndex = rightIndex;\n    }\n\n    if (index !== elementIndex) {\n      this.swap(index, elementIndex);\n      this.siftDown(elementIndex);\n    }\n  }\n\n  swap(a, b) {\n    const temp = this.heap[a];\n    this.heap[a] = this.heap[b];\n    this.heap[b] = temp;\n  }\n\n  getLeftIndex(index) {\n    return 2 * index + 1;\n  }\n\n  getRightIndex(index) {\n    return 2 * index + 2;\n  }\n\n  getParentIndex(index) {\n    return index === 0 ? undefined : Math.floor((index - 1) / 2);\n  }\n}\n"
  },
  {
    "path": "computer_science/data_structures/binary-heap/min-heap.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { MinHeap } from './min-heap';\n\ndescribe('MinHeap', () => {\n  it('findMinimum', () => {\n    const heap = new MinHeap();\n    heap.insert(2);\n    heap.insert(3);\n    heap.insert(4);\n    heap.insert(5);\n    heap.insert(1);\n\n    expect(heap.findMinimum()).toEqual(1);\n  });\n\n  it('size', () => {\n    const heap = new MinHeap();\n    for (let i = 1; i < 10; i++) {\n      heap.insert(i);\n    }\n\n    expect(heap.size()).toEqual(9);\n  });\n\n  it('integrate all methods', () => {\n    const heap = new MinHeap();\n\n    expect(heap.isEmpty()).toEqual(true);\n\n    heap.insert(2);\n    heap.insert(3);\n    heap.insert(4);\n    heap.insert(5);\n    heap.insert(1);\n\n    expect(heap.isEmpty()).toEqual(false);\n    expect(heap.size()).toEqual(5);\n    expect(heap.findMinimum()).toEqual(1);\n    expect(heap.extract()).toEqual(1);\n    expect(heap.size()).toEqual(4);\n\n    heap.insert(1);\n\n    expect(heap.size()).toEqual(5);\n    expect(heap.findMinimum()).toEqual(1);\n    expect(heap.extract()).toEqual(1);\n    expect(heap.extract()).toEqual(2);\n    expect(heap.extract()).toEqual(3);\n    expect(heap.extract()).toEqual(4);\n    expect(heap.extract()).toEqual(5);\n    expect(heap.size()).toEqual(0);\n    expect(heap.isEmpty()).toEqual(true);\n  });\n});\n"
  },
  {
    "path": "computer_science/data_structures/binary_search_tree/BinarySearchTree/index.js",
    "content": "import { Queue } from '../../queue/queue';\n\nexport class BinarySearchTree {\n  constructor(value) {\n    this.value = value;\n    this.left = null;\n    this.right = null;\n  }\n\n  insertLeft(value) {\n    if (this.left) {\n      const node = new BinarySearchTree(value);\n      node.left = this.left;\n      this.left = node;\n    } else {\n      this.left = new BinarySearchTree(value);\n    }\n  }\n\n  insertRight(value) {\n    if (this.right) {\n      const node = new BinarySearchTree(value);\n      node.right = this.right;\n      this.right = node;\n    } else {\n      this.right = new BinarySearchTree(value);\n    }\n  }\n\n  preOrder() {\n    console.log(this.value);\n    if (this.left) this.left.preOrder();\n    if (this.right) this.right.preOrder();\n  }\n\n  inOrder() {\n    if (this.left) this.left.inOrder();\n    console.log(this.value);\n    if (this.right) this.right.inOrder();\n  }\n\n  postOrder() {\n    if (this.left) this.left.postOrder();\n    if (this.right) this.right.postOrder();\n    console.log(this.value);\n  }\n\n  bfs() {\n    const queue = new Queue();\n    queue.enqueue(this);\n\n    while (!queue.isEmpty()) {\n      const node = queue.dequeue();\n      console.log(node.value);\n      if (node.left) queue.enqueue(node.left);\n      if (node.right) queue.enqueue(node.right);\n    }\n  }\n\n  insertNode(value) {\n    if (value <= this.value && this.left) {\n      this.left.insertNode(value);\n    } else if (value <= this.value) {\n      this.left = new BinarySearchTree(value);\n    } else if (value > this.value && this.right) {\n      this.right.insertNode(value);\n    } else {\n      this.right = new BinarySearchTree(value);\n    }\n  }\n\n  findNode(value) {\n    if (value < this.value && this.left) {\n      return this.left.findNode(value);\n    }\n\n    if (value > this.value && this.right) {\n      return this.right.findNode(value);\n    }\n\n    return this.value === value;\n  }\n\n  removeNode(value, parent) {\n    if (value < this.value && this.left) {\n      return this.left.removeNode(value, this);\n    }\n\n    if (value < this.value) {\n      return false;\n    }\n\n    if (value > this.value && this.right) {\n      return this.right.removeNode(value, this);\n    }\n\n    if (value > this.value) {\n      return false;\n    }\n\n    if (this.left === null && this.right === null && this == parent.left) {\n      parent.left = null;\n      this.clearNode();\n      return true;\n    }\n\n    if (this.left === null && this.right === null && this == parent.right) {\n      parent.right = null;\n      this.clearNode();\n      return true;\n    }\n\n    if (this.left && this.right === null && this == parent.left) {\n      parent.left = this.left;\n      this.clearNode();\n      return true;\n    }\n\n    if (this.left && this.right === null && this == parent.right) {\n      parent.right = this.left;\n      this.clearNode();\n      return true;\n    }\n\n    if (this.right && this.left === null && this == parent.left) {\n      parent.left = this.right;\n      this.clearNode();\n      return true;\n    }\n\n    if (this.right && this.left === null && this == parent.right) {\n      parent.right = this.right;\n      this.clearNode();\n      return true;\n    }\n\n    this.value = this.right.findMinimumValue();\n    this.right.removeNode(this.value, this);\n    return true;\n  }\n\n  clearNode() {\n    this.value = null;\n    this.left = null;\n    this.right = null;\n  }\n\n  findMinimumValue() {\n    if (this.left) return this.left.findMinimumValue();\n    return this.value;\n  }\n}\n"
  },
  {
    "path": "computer_science/data_structures/binary_search_tree/BinarySearchTree/index.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { BinarySearchTree } from '.';\n\nfunction buildBST() {\n  const tree = new BinarySearchTree(50);\n\n  tree.insertNode(21);\n  tree.insertNode(4);\n  tree.insertNode(32);\n  tree.insertNode(76);\n  tree.insertNode(64);\n  tree.insertNode(52);\n  tree.insertNode(100);\n\n  return tree;\n}\n\ndescribe('BinarySearchTree', () => {\n  it('instantiates a BinarySearchTree', () => {\n    const tree = new BinarySearchTree('a');\n    expect(tree.value).toEqual('a');\n    expect(tree.right).toEqual(null);\n    expect(tree.left).toEqual(null);\n  });\n\n  describe('inserts a left node', () => {\n    it('with a left child', () => {\n      const tree = new BinarySearchTree('a');\n      tree.left = new BinarySearchTree('b');\n      tree.insertLeft('c');\n      expect(tree.left.value).toEqual('c');\n      expect(tree.left.left.value).toEqual('b');\n    });\n\n    it('without a left child', () => {\n      const tree = new BinarySearchTree('a');\n      tree.insertLeft('b');\n      expect(tree.left.value).toEqual('b');\n    });\n  });\n\n  describe('inserts a right node', () => {\n    it('with a right child', () => {\n      const tree = new BinarySearchTree('a');\n      tree.right = new BinarySearchTree('b');\n      tree.insertRight('c');\n      expect(tree.right.value).toEqual('c');\n      expect(tree.right.right.value).toEqual('b');\n    });\n\n    it('without a right child', () => {\n      const tree = new BinarySearchTree('a');\n      tree.insertRight('b');\n      expect(tree.right.value).toEqual('b');\n    });\n  });\n\n  describe('traversal', () => {\n    const root = new BinarySearchTree(1);\n    const two = new BinarySearchTree(2);\n    const three = new BinarySearchTree(3);\n    const four = new BinarySearchTree(4);\n    const five = new BinarySearchTree(5);\n    const six = new BinarySearchTree(6);\n    const seven = new BinarySearchTree(7);\n\n    two.left = three;\n    two.right = four;\n\n    five.left = six;\n    five.right = seven;\n\n    root.left = two;\n    root.right = five;\n\n    it('traverses in pre order', () => {\n      console.log('====== pre order ======');\n      root.preOrder();\n      console.log('====== // ======');\n    });\n\n    it('traverses in order', () => {\n      console.log('====== in order ======');\n      root.inOrder();\n      console.log('====== // ======');\n    });\n\n    it('traverses in post order', () => {\n      console.log('====== post order ======');\n      root.postOrder();\n      console.log('====== // ======');\n    });\n\n    it('traverses via breadth first search', () => {\n      console.log('====== bfs ======');\n      root.bfs();\n      console.log('====== // ======');\n    });\n  });\n\n  it('inserts nodes to the BST', () => {\n    const tree = buildBST();\n\n    expect(tree.value).toEqual(50);\n    expect(tree.left.value).toEqual(21);\n    expect(tree.left.left.value).toEqual(4);\n    expect(tree.left.right.value).toEqual(32);\n    expect(tree.right.value).toEqual(76);\n    expect(tree.right.left.value).toEqual(64);\n    expect(tree.right.left.left.value).toEqual(52);\n    expect(tree.right.right.value).toEqual(100);\n  });\n\n  describe('findNode', () => {\n    it('finds the node in the tree', () => {\n      const tree = buildBST();\n\n      expect(tree.findNode(50)).toEqual(true);\n      expect(tree.findNode(21)).toEqual(true);\n      expect(tree.findNode(4)).toEqual(true);\n      expect(tree.findNode(32)).toEqual(true);\n      expect(tree.findNode(76)).toEqual(true);\n      expect(tree.findNode(64)).toEqual(true);\n      expect(tree.findNode(52)).toEqual(true);\n      expect(tree.findNode(100)).toEqual(true);\n      expect(tree.findNode(0)).toEqual(false);\n      expect(tree.findNode(999)).toEqual(false);\n    });\n  });\n\n  describe('removeNode', () => {\n    it('removes a node in the tree', () => {\n      const tree = buildBST();\n\n      expect(tree.findNode(4)).toEqual(true);\n      expect(tree.removeNode(4)).toEqual(true);\n      expect(tree.findNode(4)).toEqual(false);\n    });\n\n    it('removes a node in the middle of the left subtree', () => {\n      const tree = buildBST();\n\n      expect(tree.findNode(21)).toEqual(true);\n      expect(tree.removeNode(21)).toEqual(true);\n      expect(tree.findNode(21)).toEqual(false);\n\n      expect(tree.value).toEqual(50);\n      expect(tree.left.value).toEqual(32);\n      expect(tree.left.left.value).toEqual(4);\n      expect(tree.right.value).toEqual(76);\n      expect(tree.right.left.value).toEqual(64);\n      expect(tree.right.left.left.value).toEqual(52);\n      expect(tree.right.right.value).toEqual(100);\n    });\n\n    it('removes a node in the middle of the right subtree', () => {\n      const tree = buildBST();\n\n      expect(tree.findNode(76)).toEqual(true);\n      expect(tree.removeNode(76)).toEqual(true);\n      expect(tree.findNode(76)).toEqual(false);\n\n      expect(tree.value).toEqual(50);\n      expect(tree.left.value).toEqual(21);\n      expect(tree.left.left.value).toEqual(4);\n      expect(tree.left.right.value).toEqual(32);\n      expect(tree.right.value).toEqual(100);\n      expect(tree.right.left.value).toEqual(64);\n      expect(tree.right.left.left.value).toEqual(52);\n    });\n\n    it('removes the root node', () => {\n      const tree = buildBST();\n\n      expect(tree.findNode(50)).toEqual(true);\n      expect(tree.removeNode(50)).toEqual(true);\n      expect(tree.findNode(50)).toEqual(false);\n\n      expect(tree.value).toEqual(52);\n      expect(tree.left.value).toEqual(21);\n      expect(tree.left.left.value).toEqual(4);\n      expect(tree.left.right.value).toEqual(32);\n      expect(tree.right.value).toEqual(76);\n      expect(tree.right.right.value).toEqual(100);\n      expect(tree.right.left.value).toEqual(64);\n    });\n  });\n});\n"
  },
  {
    "path": "computer_science/data_structures/binary_search_tree/big_o.py",
    "content": "# insert: O(log(N)) - Logarithmic Time\n# find / search: O(log(N)) - Logarithmic Time\n# traversal: O(N) - Linear Time\n"
  },
  {
    "path": "computer_science/data_structures/binary_search_tree/binary_search_tree.py",
    "content": "from queue import Queue\n\n\nclass Node:\n    def __init__(self, value):\n        self.value = value\n        self.left_child = None\n        self.right_child = None\n\n\nclass BinarySearchTree:\n    def __init__(self):\n        self.root = None\n\n    def insert(self, value):\n        if self.root:\n            self.insert_node(self.root, value)\n        else:\n            self.root = Node(value)\n\n    def insert_node(self, current_node, value):\n        if value <= current_node.value and current_node.left_child:\n            self.insert_node(current_node.left_child, value)\n        elif value <= current_node.value:\n            current_node.left_child = Node(value)\n        elif current_node.right_child:\n            self.insert_node(current_node.right_child, value)\n        else:\n            current_node.right_child = Node(value)\n\n    def find(self, value):\n        return self.find_node(self.root, value)\n\n    def find_node(self, current_node, value):\n        if value < current_node.value and current_node.left_child:\n            return self.find_node(current_node.left_child, value)\n        if value > current_node.value and current_node.right_child:\n            return self.find_node(current_node.right_child, value)\n\n        return value == current_node.value\n\n    def pre_order(self):\n        if self.root:\n            self.pre_order_traversal(self.root)\n        else:\n            print('Tree empty')\n\n    def pre_order_traversal(self, current_node):\n        print(current_node.value)\n\n        if current_node.left_child:\n            self.pre_order_traversal(current_node.left_child)\n\n        if current_node.right_child:\n            self.pre_order_traversal(current_node.right_child)\n\n    def in_order(self):\n        if self.root:\n            self.in_order_traversal(self.root)\n        else:\n            print('Tree empty')\n\n    def in_order_traversal(self, current_node):\n        if current_node.left_child:\n            self.in_order_traversal(current_node.left_child)\n\n        print(current_node.value)\n\n        if current_node.right_child:\n            self.in_order_traversal(current_node.right_child)\n\n    def post_order(self):\n        if self.root:\n            self.post_order_traversal(self.root)\n        else:\n            print('Tree empty')\n\n    def post_order_traversal(self, current_node):\n        if current_node.left_child:\n            self.post_order_traversal(current_node.left_child)\n\n        if current_node.right_child:\n            self.post_order_traversal(current_node.right_child)\n\n        print(current_node.value)\n\n    def bfs(self):\n        queue = Queue()\n        queue.put(self.root)\n\n        while not queue.empty():\n            current_node = queue.get()\n            print(current_node.value)\n\n            if current_node.left_child:\n                queue.put(current_node.left_child)\n\n            if current_node.right_child:\n                queue.put(current_node.right_child)\n"
  },
  {
    "path": "computer_science/data_structures/binary_search_tree/test_binary_search_tree.py",
    "content": "from binary_search_tree import *\n\nbst = BinarySearchTree()\n\nbst.insert(15)\nbst.insert(10)\nbst.insert(8)\nbst.insert(12)\nbst.insert(20)\nbst.insert(17)\nbst.insert(25)\nbst.insert(19)\n\nprint('Find 15')\nprint(bst.find(15))\nprint('Find 10')\nprint(bst.find(10))\nprint('Find 8')\nprint(bst.find(8))\nprint('Find 12')\nprint(bst.find(12))\nprint('Find 20')\nprint(bst.find(20))\nprint('Find 17')\nprint(bst.find(17))\nprint('Find 25')\nprint(bst.find(25))\nprint('Find 19')\nprint(bst.find(19))\nprint('Find 0')\nprint(bst.find(0))\n\nprint()\n\nprint('Pre Order')\nbst.pre_order()\nprint()\n\nprint('In Order')\nbst.in_order()\nprint()\n\nprint('Post Order')\nbst.post_order()\nprint()\n\nprint('BFS')\nbst.bfs()\n"
  },
  {
    "path": "computer_science/data_structures/binary_search_tree/test_node.py",
    "content": "from binary_search_tree import Node\n\nnode = Node(1)\nprint(node.get())\nnode.set(2)\nprint(node.get())\n"
  },
  {
    "path": "computer_science/data_structures/binary_search_tree_without_node/binary_search_tree.py",
    "content": "class BinarySearchTree:\n    def __init__(self, value):\n        self.value = value\n        self.left_child = None\n        self.right_child = None\n\n    def insert_node(self, value):\n        if value <= self.value and self.left_child:\n            self.left_child.insert_node(value)\n        elif value <= self.value:\n            self.left_child = BinarySearchTree(value)\n        elif value > self.value and self.right_child:\n            self.right_child.insert_node(value)\n        else:\n            self.right_child = BinarySearchTree(value)\n\n    def find_node(self, value):\n        if value < self.value and self.left_child:\n            return self.left_child.find_node(value)\n        if value > self.value and self.right_child:\n            return self.right_child.find_node(value)\n\n        return value == self.value\n\n    def remove_node(self, value, parent):\n        if value < self.value and self.left_child:\n            return self.left_child.remove_node(value, self)\n        elif value < self.value:\n            return False\n        elif value > self.value and self.right_child:\n            return self.right_child.remove_node(value, self)\n        elif value > self.value:\n            return False\n        else:\n            if self.left_child is None and self.right_child is None and self == parent.left_child:\n                parent.left_child = None\n                self.clear_node()\n            elif self.left_child is None and self.right_child is None and self == parent.right_child:\n                parent.right_child = None\n                self.clear_node()\n            elif self.left_child and self.right_child is None and self == parent.left_child:\n                parent.left_child = self.left_child\n                self.clear_node()\n            elif self.left_child and self.right_child is None and self == parent.right_child:\n                parent.right_child = self.left_child\n                self.clear_node()\n            elif self.right_child and self.left_child is None and self == parent.left_child:\n                parent.left_child = self.right_child\n                self.clear_node()\n            elif self.right_child and self.left_child is None and self == parent.right_child:\n                parent.right_child = self.right_child\n                self.clear_node()\n            else:\n                self.value = self.right_child.find_minimum_value()\n                self.right_child.remove_node(self.value, self)\n\n            return True\n\n    def clear_node(self):\n        self.value = None\n        self.left_child = None\n        self.right_child = None\n\n    def find_minimum_value(self):\n        if self.left_child:\n            return self.left_child.find_minimum_value()\n        else:\n            return self.value\n\n    def pre_order_traversal(self):\n        print(self.value)\n\n        if self.left_child:\n            self.left_child.pre_order_traversal()\n\n        if self.right_child:\n            self.right_child.pre_order_traversal()\n\n    def in_order_traversal(self):\n        if self.left_child:\n            self.left_child.in_order_traversal()\n\n        print(self.value)\n\n        if self.right_child:\n            self.right_child.in_order_traversal()\n\n    def post_order_traversal(self):\n        if self.left_child:\n            self.left_child.post_order_traversal()\n\n        if self.right_child:\n            self.right_child.post_order_traversal()\n\n        print(self.value)\n"
  },
  {
    "path": "computer_science/data_structures/binary_search_tree_without_node/test_binary_search_tree.py",
    "content": "from binary_search_tree import *\n\nbst = BinarySearchTree(15)\n\nbst.insert_node(10)\nbst.insert_node(8)\nbst.insert_node(12)\nbst.insert_node(20)\nbst.insert_node(17)\nbst.insert_node(25)\nbst.insert_node(19)\n\nprint(bst.find_node(15)) # True\nprint(bst.find_node(10)) # True\nprint(bst.find_node(8)) # True\nprint(bst.find_node(12)) # True\nprint(bst.find_node(20)) # True\nprint(bst.find_node(17)) # True\nprint(bst.find_node(25)) # True\nprint(bst.find_node(19)) # True\n\nprint(bst.find_node(0)) # False\n\nprint\nprint(bst.find_minimum_value())\n\nprint\nbst.pre_order_traversal()\nprint\nbst.in_order_traversal()\nprint\nbst.post_order_traversal()\n\nprint\nprint(bst.remove_node(8, None))\nprint\nbst.pre_order_traversal()\n\nprint\nprint(bst.remove_node(17, None))\nprint\nbst.pre_order_traversal()\n\nprint\nprint(bst.remove_node(15, None))\nprint\nbst.pre_order_traversal()\n\nprint\nprint(bst.remove_node(20, None))\nprint\nbst.pre_order_traversal()\n"
  },
  {
    "path": "computer_science/data_structures/binary_tree/BinaryTree/index.js",
    "content": "import { Queue } from '../../queue/queue';\n\nexport class BinaryTree {\n  constructor(value) {\n    this.value = value;\n    this.left = null;\n    this.right = null;\n  }\n\n  insertLeft(value) {\n    if (this.left) {\n      const node = new BinaryTree(value);\n      node.left = this.left;\n      this.left = node;\n    } else {\n      this.left = new BinaryTree(value);\n    }\n  }\n\n  insertRight(value) {\n    if (this.right) {\n      const node = new BinaryTree(value);\n      node.right = this.right;\n      this.right = node;\n    } else {\n      this.right = new BinaryTree(value);\n    }\n  }\n\n  preOrder() {\n    console.log(this.value);\n    if (this.left) this.left.preOrder();\n    if (this.right) this.right.preOrder();\n  }\n\n  inOrder() {\n    if (this.left) this.left.inOrder();\n    console.log(this.value);\n    if (this.right) this.right.inOrder();\n  }\n\n  postOrder() {\n    if (this.left) this.left.postOrder();\n    if (this.right) this.right.postOrder();\n    console.log(this.value);\n  }\n\n  bfs() {\n    const queue = new Queue();\n    queue.enqueue(this);\n\n    while (!queue.isEmpty()) {\n      const node = queue.dequeue();\n      console.log(node.value);\n      if (node.left) queue.enqueue(node.left);\n      if (node.right) queue.enqueue(node.right);\n    }\n  }\n}\n"
  },
  {
    "path": "computer_science/data_structures/binary_tree/BinaryTree/index.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { BinaryTree } from '.';\n\ndescribe('BinaryTree', () => {\n  it('instantiates a BinaryTree', () => {\n    const tree = new BinaryTree('a');\n    expect(tree.value).toEqual('a');\n    expect(tree.right).toEqual(null);\n    expect(tree.left).toEqual(null);\n  });\n\n  describe('inserts a left node', () => {\n    it('with a left child', () => {\n      const tree = new BinaryTree('a');\n      tree.left = new BinaryTree('b');\n      tree.insertLeft('c');\n      expect(tree.left.value).toEqual('c');\n      expect(tree.left.left.value).toEqual('b');\n    });\n\n    it('without a left child', () => {\n      const tree = new BinaryTree('a');\n      tree.insertLeft('b');\n      expect(tree.left.value).toEqual('b');\n    });\n  });\n\n  describe('inserts a right node', () => {\n    it('with a right child', () => {\n      const tree = new BinaryTree('a');\n      tree.right = new BinaryTree('b');\n      tree.insertRight('c');\n      expect(tree.right.value).toEqual('c');\n      expect(tree.right.right.value).toEqual('b');\n    });\n\n    it('without a right child', () => {\n      const tree = new BinaryTree('a');\n      tree.insertRight('b');\n      expect(tree.right.value).toEqual('b');\n    });\n  });\n\n  describe('traversal', () => {\n    const root = new BinaryTree(1);\n    const two = new BinaryTree(2);\n    const three = new BinaryTree(3);\n    const four = new BinaryTree(4);\n    const five = new BinaryTree(5);\n    const six = new BinaryTree(6);\n    const seven = new BinaryTree(7);\n\n    two.left = three;\n    two.right = four;\n\n    five.left = six;\n    five.right = seven;\n\n    root.left = two;\n    root.right = five;\n\n    it('traverses in pre order', () => {\n      console.log('====== pre order ======');\n      root.preOrder();\n      console.log('====== // ======');\n    });\n\n    it('traverses in order', () => {\n      console.log('====== in order ======');\n      root.inOrder();\n      console.log('====== // ======');\n    });\n\n    it('traverses in post order', () => {\n      console.log('====== post order ======');\n      root.postOrder();\n      console.log('====== // ======');\n    });\n\n    it('traverses via breadth first search', () => {\n      console.log('====== bfs ======');\n      root.bfs();\n      console.log('====== // ======');\n    });\n  });\n});\n"
  },
  {
    "path": "computer_science/data_structures/binary_tree/big_o.py",
    "content": "# Binary Tree: Big O Complexity\n\n# Search: O(log N) - Logarithmic Time\n# Insert: O(log N) - Logarithmic Time\n# Delete: O(log N) - Logarithmic Time\n# Traversal: O(N) - Linear Time\n"
  },
  {
    "path": "computer_science/data_structures/binary_tree/binary_tree.py",
    "content": "from queue import Queue\n\n\nclass BinaryTree:\n    def __init__(self, value):\n        self.value = value\n        self.left_child = None\n        self.right_child = None\n\n    def insert_left(self, value):\n        if self.left_child:\n            self.left_child.insert_left(value)\n        else:\n            self.left_child = BinaryTree(value)\n\n    def insert_right(self, value):\n        if self.right_child:\n            self.right_child.insert_right(value)\n        else:\n            self.right_child = BinaryTree(value)\n\n    def pre_order(self):\n        print(self.value)\n\n        if self.left_child:\n            self.left_child.pre_order()\n\n        if self.right_child:\n            self.right_child.pre_order()\n\n    def post_order(self):\n        if self.left_child:\n            self.left_child.post_order()\n\n        if self.right_child:\n            self.right_child.post_order()\n\n        print(self.value)\n\n    def in_order(self):\n        if self.left_child:\n            self.left_child.in_order()\n\n        print(self.value)\n\n        if self.right_child:\n            self.right_child.in_order()\n\n    def bfs(self):\n        queue = Queue()\n        queue.put(self)\n\n        while not queue.empty():\n            current_node = queue.get()\n            print(current_node.value)\n\n            if current_node.left_child:\n                queue.put(current_node.left_child)\n\n            if current_node.right_child:\n                queue.put(current_node.right_child)\n"
  },
  {
    "path": "computer_science/data_structures/binary_tree/test_binary_tree.py",
    "content": "from binary_tree import BinaryTree\n\na_node = BinaryTree('a')\na_node.insert_left('b')\na_node.insert_right('c')\n\nb_node = a_node.left_child\nb_node.insert_right('d')\n\nc_node = a_node.right_child\nc_node.insert_left('e')\nc_node.insert_right('f')\n\nd_node = b_node.right_child\ne_node = c_node.left_child\nf_node = c_node.right_child\n\na = a_node.value\nb = b_node.value\nc = c_node.value\nd = d_node.value\ne = e_node.value\nf = f_node.value\n\nprint\nprint('---------------------------------------')\nprint\nprint(\"               |%s|\" % (a))\nprint(\"             /     \\\\\")\nprint(\"           |%s|     |%s|\" % (b, c))\nprint(\"              \\\\   /   \\\\\")\nprint(\"             |%s| |%s| |%s|\" % (d, e, f))\n\n# ------- Building this Tree -------\n#\n#               |a|\n#             /    \\\n#          |b|     |c|\n#           \\     /  \\\n#           |d| |e|  |f|\n\nprint\nprint('---------------------------------------')\nprint\n\ntree = a_node\n\nprint('Depth First: Pre Order')\nprint\ntree.pre_order()\nprint\n\nprint\nprint('---------------------------------------')\nprint\n\nprint('Depth First: Post Order')\nprint\ntree.post_order()\nprint\n\nprint\nprint('---------------------------------------')\nprint\n\nprint('Depth First: In Order')\nprint\ntree.in_order()\nprint\n\nprint\nprint('---------------------------------------')\nprint\n\nprint('Breadth First Search')\nprint\ntree.bfs()\nprint\n"
  },
  {
    "path": "computer_science/data_structures/graph/AdjacentListGraph/AdjacentListGraph.js",
    "content": "export function addNode(AdjacentListGraph, key) {\n  AdjacentListGraph.set(key, []);\n}\n\nexport function addEdge(AdjacentListGraph, origin, destination) {\n  AdjacentListGraph.get(origin).push(destination);\n  AdjacentListGraph.get(destination).push(origin);\n}\n\nexport function bfs(AdjacentListGraph, vertex) {\n  const visitedVertices = new Set();\n  const queue = [vertex];\n\n  while (queue.length) {\n    const origin = queue.shift();\n    const destinations = AdjacentListGraph.get(origin);\n\n    for (let destination of destinations) {\n      if (!visitedVertices.has(destination)) {\n        visitedVertices.add(destination);\n        queue.push(destination);\n      }\n    }\n  }\n}\n\nexport function dfs(AdjacentListGraph, vertex, visitedVertices = new Set()) {\n  const destinations = AdjacentListGraph.get(vertex);\n  visitedVertices.add(vertex);\n\n  for (let destination of destinations) {\n    if (!visitedVertices.has(destination)) {\n      dfs(AdjacentListGraph, destination, visitedVertices);\n    }\n  }\n}\n"
  },
  {
    "path": "computer_science/data_structures/graph/AdjacentListGraph/example.js",
    "content": "import { addNode, addEdge, bfs, dfs } from './AdjacentListGraph.js';\n\nconst airports = [\n  'PHX',\n  'BKK',\n  'JFK',\n  'LIM',\n  'MEX',\n  'OKC',\n  'LAX',\n  'EZE',\n  'HEL',\n  'LOS',\n  'LA',\n];\n\nconst routes = [\n  ['PHX', 'LA'],\n  ['PHX', 'JFK'],\n  ['JFK', 'OKC'],\n  ['JFK', 'LOS'],\n  ['JFK', 'HEL'],\n  ['MEX', 'LA'],\n  ['MEX', 'BKK'],\n  ['MEX', 'LIM'],\n  ['MEX', 'EZE'],\n  ['LIM', 'BKK'],\n];\n\nconst AdjacentListGraph = new Map();\n\nfor (let airport of airports) {\n  addNode(AdjacentListGraph, airport);\n}\n\nfor (let [origin, destination] of routes) {\n  addEdge(AdjacentListGraph, origin, destination);\n}\n\nbfs(AdjacentListGraph, 'PHX');\ndfs(AdjacentListGraph, 'PHX');\n"
  },
  {
    "path": "computer_science/data_structures/graph/README.md",
    "content": "# Graph\n\n## Breadth First Search (BFS)\n\n- Use the queue data structure to hold each vertex that needs to be visited in the future.\n- It should keep a visited data structure to store all the visited vertices.\n- Runtime: O(V+E) / V = vertices | E = edges.\n\n## Depth First Search (DFS)\n\n- Use the stack data structure or do recursive.\n- It should keep a visited data structure to store all the visited vertices.\n- Runtime: O(V+E) / V = vertices | E = edges.\n"
  },
  {
    "path": "computer_science/data_structures/graph/adjacency_list.cpp",
    "content": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int, int> pii;\ntypedef vector<pii> vii;\ntypedef vector<int> vi;\n\n#define pb push_back\n\nint main() {\n  vector<vii> AdjList;\n  vii vectorOfPairs;\n\n  vectorOfPairs.pb(make_pair(1, 50)); // Vertice 0 connected with vertice 1 and weight 50\n  AdjList.pb(vectorOfPairs);\n\n  vectorOfPairs.clear();\n  vectorOfPairs.pb(make_pair(0, 50)); // Vertice 0 connected with vertice 1 and weight 50\n  vectorOfPairs.pb(make_pair(2, 20)); // Vertice 1 connected with vertice 2 and weight 20\n  vectorOfPairs.pb(make_pair(3, 30)); // Vertice 1 connected with vertice 3 and weight 30\n  AdjList.pb(vectorOfPairs);\n\n  vectorOfPairs.clear();\n  vectorOfPairs.pb(make_pair(1, 20)); // Vertice 2 connected with vertice 1 and weight 20\n  vectorOfPairs.pb(make_pair(3, 40)); // Vertice 2 connected with vertice 3 and weight 40\n  AdjList.pb(vectorOfPairs);\n\n  vectorOfPairs.clear();\n  vectorOfPairs.pb(make_pair(1, 30)); // Vertice 3 connected with vertice 1 and weight 30\n  vectorOfPairs.pb(make_pair(2, 40)); // Vertice 2 connected with vertice 3 and weight 40\n  vectorOfPairs.pb(make_pair(4, 60)); // Vertice 3 connected with vertice 4 and weight 60\n  AdjList.pb(vectorOfPairs);\n\n  vectorOfPairs.clear();\n  vectorOfPairs.pb(make_pair(3, 60)); // Vertice 4 connected with vertice 3 and weight 60\n  AdjList.pb(vectorOfPairs);\n\n  for (int i = 0; i < AdjList.size(); i++) {\n    for (int j = 0; j < AdjList[i].size(); j++) {\n      cout << \"Vertice: \" << i;\n      cout << \" connected with vertice \" << AdjList[i][j].first;\n      cout << \" with weight \" << AdjList[i][j].second << endl;\n    }\n    cout << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "computer_science/data_structures/graph/graph.js",
    "content": "class Vertex {\n  constructor(key) {\n    this.key = key;\n    this.adjacent = [];\n  }\n\n  contains(key) {\n    for (let vertex of this.adjacent) {\n      if (vertex.key === key) {\n        return true;\n      }\n    }\n\n    return false;\n  }\n}\n\nclass Graph {\n  constructor() {\n    this.vertices = [];\n  }\n\n  addVertex(key) {\n    if (this.contains(key)) {\n      console.log(`Vertex ${key} not added because it's an existent key`);\n      return;\n    }\n\n    this.vertices.push(new Vertex(key));\n  }\n\n  contains(key) {\n    for (let vertex of this.vertices) {\n      if (vertex.key === key) {\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  addEdge(from, to) {\n    let fromVertex = this.getVertex(from);\n    let toVertex = this.getVertex(to);\n\n    if (!fromVertex) {\n      console.log(`Vertex ${from} doesn't exist in the graph`);\n      return;\n    }\n\n    if (!toVertex) {\n      console.log(`Vertex ${to} doesn't exist in the graph`);\n      return;\n    }\n\n    if (fromVertex.contains(to)) {\n      console.log(`Existing edge: ${from} --> ${to}`);\n      return;\n    }\n\n    fromVertex.adjacent.push(toVertex);\n  }\n\n  getVertex(key) {\n    for (let vertex of this.vertices) {\n      if (vertex.key === key) {\n        return vertex;\n      }\n    }\n  }\n\n  print() {\n    for (let vertex of this.vertices) {\n      let adjacent = vertex.adjacent.reduce(\n        (verticesString, vertex) => `${verticesString} ${vertex.key}`,\n        ''\n      );\n      console.log(`Vertice ${vertex.key}: ${adjacent}`);\n    }\n  }\n}\n\nconst graph = new Graph();\n\ngraph.addVertex(0);\n\nfor (let i = 1; i <= 4; i++) {\n  graph.addVertex(i);\n}\n\ngraph.addVertex(0);\ngraph.addVertex(0);\n\ngraph.addEdge(1, 2);\ngraph.addEdge(1, 3);\ngraph.addEdge(2, 3);\ngraph.addEdge(2, 4);\ngraph.addEdge(1, 2);\ngraph.addEdge(6, 2);\ngraph.addEdge(3, 2);\ngraph.addEdge(1, 1);\n\nconsole.log();\ngraph.print();\n"
  },
  {
    "path": "computer_science/data_structures/graph/graph.py",
    "content": "class Graph:\n    def __init__(self):\n        self.vertices = []\n\n    def add_vertex(self, key):\n        if self.contains(self.vertices, key):\n            print(\"Vertex\", key, \"not added because it is an existing key\")\n        else:\n            self.vertices.append(Vertex(key))\n\n    def print(self):\n        for vertex in self.vertices:\n            print(\"Vertex\", vertex.key)\n            for neighbor in vertex.adjacent:\n                print(neighbor.key)\n\n    def add_edge(self, from_key, to_key):\n        from_vertex = self.get_vertex(from_key)\n        to_vertex = self.get_vertex(to_key)\n\n        if from_vertex is None or to_vertex is None:\n            print(\"Invalid edge (\", from_key, \"-->\", to_key, \")\")\n            return\n        \n        if self.contains(from_vertex.adjacent, to_key):\n            print(\"Edge\", to_key, \"not added because it is already an existing neighbor\")\n            return\n\n        from_vertex.adjacent.append(to_vertex)\n\n    def get_vertex(self, key):\n        for vertex in self.vertices:\n            if vertex.key == key:\n                return vertex\n\n    def contains(self, vertices, key):\n        for vertex in vertices:\n            if vertex.key == key:\n                return True\n\n        return False\n\nclass Vertex:\n    def __init__(self, key):\n        self.key = key\n        self.adjacent = []\n"
  },
  {
    "path": "computer_science/data_structures/graph/test_graph.py",
    "content": "from graph import *\n\ng = Graph()\n\nfor i in range(5):\n    g.add_vertex(i)\n\ng.add_edge(1, 2)\ng.add_edge(1, 3)\ng.add_edge(2, 3)\ng.add_edge(2, 4)\ng.add_edge(1, 2)\ng.add_edge(6, 2)\ng.add_edge(3, 2)\ng.add_edge(1, 1)\ng.print()\n"
  },
  {
    "path": "computer_science/data_structures/hash_table/big_o.py",
    "content": "# Hash Table / Dictionaty Big O complexity\n\n# Insert: O(1) - Constant Time\n# Search: O(1) - Constant Time\n# Delete: O(1) - Constant Time\n"
  },
  {
    "path": "computer_science/data_structures/hash_table/dictionary.py",
    "content": "d1 = {}\nd2 = dict()\nd3 = { 'something': 10, 'other_thing': 11 }\n\nprint(d3['something'])\n\nd1[1] = 1\nd1[2] = 2\nd1[3] = 3\nd1[4] = 4\n\nfor key, value in d1.items():\n    print('key: %d | value: %d' %(key, value))\n\nd1[2] = -2\nprint(d1[2])\n"
  },
  {
    "path": "computer_science/data_structures/hash_table/maps.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <map>\n\nusing namespace std;\n\nint main() {\n\n  map<string, int> m;\n  m[\"one\"] = 1;\n  m[\"two\"] = 2;\n  m[\"three\"] = 3;\n\n  int one_plus_two = m[\"one\"] + m[\"two\"];\n\n  cout << one_plus_two << endl;\n\n  int total = 0;\n  for (map<string, int>::iterator it = m.begin(); it != m.end(); ++it)\n    total += it->second;\n\n  cout << total << endl;\n\n  if (m.find(\"two\") != m.end())\n    m.erase(m.find(\"two\"));\n\n  total = 0;\n  for (map<string, int>::iterator it = m.begin(); it != m.end(); ++it)\n    total += it->second;\n\n  cout << total << endl;\n\n  if (m.find(\"one\") != m.end()) {\n    cout << m.find(\"one\")->first << endl;\n    m.find(\"one\")->second++;\n    cout << m.find(\"one\")->second << endl;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "computer_science/data_structures/linked_list/big-o.js",
    "content": "/***\n=== Linked List Big O complexity ===\n\nPush Front: O(1) - Constant Time\nPush Back: O(N) - Linear Time\n  If it has the tail: O(1) - Constant Time\nPush in the middle: O(N) - Linear Time\nRemove: O(N) - Linear Time\n  Remove of head or tail: O(1) - Constant Time\nIs Empty: O(1) - Constant Time\nSize: O(N) - Linear Time\nSearch: O(N) - Linear Time\n  Get head or tail: O(1) - Constant Time\n***/\n"
  },
  {
    "path": "computer_science/data_structures/linked_list/big_o.py",
    "content": "# Linked List Big O complexity\n\n# Push Front: O(1) - Constant Time\n# Push Back: O(N) - Linear Time\n# Remove: O(N) - Linear Time\n# Is Empty: O(1) - Constant Time\n# Size: O(N) - Linear Time\n# Search: O(N) - Linear Time\n"
  },
  {
    "path": "computer_science/data_structures/linked_list/linked-list.js",
    "content": "export class Node {\n  constructor(value, next = null) {\n    this.value = value;\n    this.next = next;\n  }\n}\n\nexport class LinkedList {\n  constructor() {\n    this.head = null;\n  }\n\n  pushFront(value) {\n    this.head = new Node(value, this.head);\n  }\n\n  pushBack(value) {\n    if (this.isEmpty()) {\n      this.head = new Node(value);\n      return;\n    }\n\n    let currentNode = this.head;\n\n    while (currentNode && currentNode.next) {\n      currentNode = currentNode.next;\n    }\n\n    currentNode.next = new Node(value);\n  }\n\n  size() {\n    let count = 0;\n    let currentNode = this.head;\n\n    while (currentNode) {\n      count += 1;\n      currentNode = currentNode.next;\n    }\n\n    return count;\n  }\n\n  search(value) {\n    let currentNode = this.head;\n\n    while (currentNode && currentNode.value !== value) {\n      currentNode = currentNode.next;\n    }\n\n    return Boolean(currentNode);\n  }\n\n  remove(value) {\n    if (this.isEmpty()) {\n      return;\n    }\n\n    if (this.head.value === value) {\n      this.head = this.head.next;\n      return;\n    }\n\n    let currentNode = this.head;\n\n    while (currentNode.next) {\n      if (currentNode.next.value === value) {\n        currentNode.next = currentNode.next.next;\n        return;\n      }\n\n      currentNode = currentNode.next;\n    }\n  }\n\n  isEmpty() {\n    return this.head === null;\n  }\n}\n"
  },
  {
    "path": "computer_science/data_structures/linked_list/linked_list.py",
    "content": "class Node:\n    def __init__(self, data):\n        self.data = data\n        self.next = None\n\n\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n\n    def is_empty(self):\n        return self.head == None\n\n    def push_front(self, data):\n        new_node = Node(data)\n        new_node.next = self.head\n        self.head = new_node\n\n    def push_back(self, data):\n        new_node = Node(data)\n        current_node = self.head\n\n        while current_node.next:\n            current_node = current_node.next\n\n        current_node.next = new_node\n\n    def size(self):\n        current_node = self.head\n        count = 0\n\n        while current_node:\n            count += 1\n            current_node = current_node.next\n\n        return count\n\n    def search(self, item):\n        current_node = self.head\n\n        while current_node and not current_node.data == item:\n            current_node = current_node.next\n\n        return current_node != None and current_node.data == item\n\n    def remove(self, item):\n        if self.head == None:\n            print('List is empty')\n            return\n\n        current_node = self.head\n        previous_node = None\n\n        while current_node and current_node.data != item:\n            previous_node = current_node\n            current_node = current_node.next\n\n        if previous_node == None:\n            self.head = current_node.next\n        else:\n            previous_node.next = current_node.next\n"
  },
  {
    "path": "computer_science/data_structures/linked_list/test_linked_list.py",
    "content": "from linked_list import *\n\nprint('--- Instantiate Linked List ---')\nlinked_list = LinkedList()\nprint(linked_list)\n\nprint('--- Push Front & Size ---')\nlinked_list.push_front(10)\nlinked_list.push_front(9)\nlinked_list.push_front(8)\nprint(\"Current size: %i\" %(linked_list.size()))\n\nprint('--- Push Back ---')\nlinked_list.push_back(11)\nprint(\"Current size: %i\" %(linked_list.size()))\n\nprint('--- Printing all nodes data ---')\ncurrent_node = linked_list.head\nwhile current_node:\n    print(current_node.data)\n    current_node = current_node.next\n\nprint('--- Searching ---')\nprint(linked_list.search(10))\nprint(linked_list.search(0))\n\nprint('--- Removing ---')\nprint(\"Size: %i\" %(linked_list.size()))\nprint(\"Searching for 10 - Found: %r\" %(linked_list.search(10)))\nprint('Removing 10')\nlinked_list.remove(10)\nprint(\"Size: %i\" %(linked_list.size()))\nprint(\"Searching for 10 - Found: %r\" %(linked_list.search(10)))\nprint('Removing 9, 8, and 11')\nlinked_list.remove(11)\nlinked_list.remove(8)\nlinked_list.remove(9)\nprint(\"Size: %i\" %(linked_list.size()))\nprint('Trying to remove item from empty list')\nlinked_list.remove(0)\n"
  },
  {
    "path": "computer_science/data_structures/linked_list/test_node.py",
    "content": "from linked_list import Node\n\nnode = Node(9)\nprint(node)\nprint(node.get_data())\nnode.set_data(10)\nprint(node.get_data())\n\nprint(\"------------\")\n\nprint(node.get_next())\nother_node = Node(0)\n\nnode.set_next(other_node)\nprint(node.get_next())\nprint(node.get_next().get_data())\n"
  },
  {
    "path": "computer_science/data_structures/linked_list/tests/linked-list.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { LinkedList, Node } from '../linked-list';\n\ndescribe('LinkedList', () => {\n  it('verifies linked list behavior', () => {\n    const linkedList = new LinkedList();\n    expect(linkedList.isEmpty()).toBeTruthy();\n    expect(linkedList.size()).toEqual(0);\n\n    linkedList.pushFront(1);\n    expect(linkedList.isEmpty()).toBeFalsy();\n    expect(linkedList.size()).toEqual(1);\n    expect(linkedList.head).toEqual(new Node(1));\n\n    linkedList.pushBack(2);\n    linkedList.pushBack(3);\n    linkedList.pushBack(4);\n    expect(linkedList.size()).toEqual(4);\n\n    linkedList.pushFront(0);\n    expect(linkedList.size()).toEqual(5);\n\n    expect(linkedList.search(0)).toBeTruthy();\n    expect(linkedList.search(1)).toBeTruthy();\n    expect(linkedList.search(2)).toBeTruthy();\n    expect(linkedList.search(3)).toBeTruthy();\n    expect(linkedList.search(4)).toBeTruthy();\n    expect(linkedList.search(5)).toBeFalsy();\n\n    linkedList.remove(5);\n    expect(linkedList.size()).toEqual(5);\n\n    linkedList.remove(0);\n    expect(linkedList.size()).toEqual(4);\n\n    linkedList.remove(4);\n    expect(linkedList.size()).toEqual(3);\n\n    linkedList.remove(2);\n    expect(linkedList.size()).toEqual(2);\n\n    linkedList.remove(1);\n    expect(linkedList.size()).toEqual(1);\n\n    linkedList.remove(3);\n    expect(linkedList.size()).toEqual(0);\n    expect(linkedList.isEmpty()).toBeTruthy();\n  });\n});\n"
  },
  {
    "path": "computer_science/data_structures/queue/big_o.py",
    "content": "# Queue Big O complexity\n\n# Enqueue (push): O(1) - Constant Time\n# Dequeue (remove): O(1) - Constant Time\n# Front: O(1) - Constant Time\n# Back: O(1) - Constant Time\n# Is Empty: O(1) - Constant Time\n# Size: O(1) - Constant Time\n"
  },
  {
    "path": "computer_science/data_structures/queue/queue.js",
    "content": "export class Queue {\n  constructor() {\n    this.items = [];\n  }\n\n  enqueue(item) {\n    this.items.push(item);\n  }\n\n  dequeue() {\n    return this.items.shift();\n  }\n\n  isEmpty() {\n    return this.size() === 0;\n  }\n\n  front() {\n    return this.items[0];\n  }\n\n  back() {\n    return this.items.at(-1);\n  }\n\n  size() {\n    return this.items.length;\n  }\n}\n"
  },
  {
    "path": "computer_science/data_structures/queue/queue.py",
    "content": "# Queue Big O complexity\n\n# Enqueue (push): O(1) - Constant Time\n# Dequeue (remove): O(1) - Constant Time\n# Front: O(1) - Constant Time\n# Back: O(1) - Constant Time\n# Is Empty: O(1) - Constant Time\n# Size: O(1) - Constant Time\n\n\nclass Emptiness(Exception):\n    pass\n\n\nclass Queue:\n    def __init__(self):\n        self.items = []\n\n    def enqueue(self, item):\n        self.items.append(item)\n\n    def dequeue(self):\n        if self.is_empty():\n            raise Emptiness('The Queue is empty')\n\n        return self.items.pop(0)\n\n    def is_empty(self):\n        return self.size() == 0\n\n    def front(self):\n        if self.is_empty():\n            raise Emptiness('The Queue is empty')\n\n        return self.items[0]\n\n    def back(self):\n        if self.is_empty():\n            raise Emptiness('The Queue is empty')\n\n        return self.items[-1]\n\n    def size(self):\n        return len(self.items)\n\n\ndef test_enqueue(queue, item):\n    queue.enqueue(item)\n    print(queue.items)\n\n\ndef test_dequeue(queue):\n    queue.dequeue()\n    print(queue.items)\n\n\ndef test_emptiness(queue):\n    is_empty = queue.is_empty()\n    print(is_empty)\n\n\ndef test_size(queue):\n    size = queue.size()\n    print(size)\n\n\ndef test_front(queue):\n    front = queue.front()\n    print(front)\n\n\ndef test_back(queue):\n    back = queue.back()\n    print(back)\n\n\nqueue = Queue()\n\ntest_emptiness(queue)  # True\ntest_size(queue)  # 0\n\ntest_enqueue(queue, 1)  # [1]\ntest_enqueue(queue, 2)  # [1, 2]\ntest_enqueue(queue, 3)  # [1, 2, 3]\ntest_enqueue(queue, 4)  # [1, 2, 3, 4]\ntest_enqueue(queue, 5)  # [1, 2, 3, 4, 5]\n\ntest_emptiness(queue)  # False\ntest_size(queue)  # 5\ntest_front(queue)  # 1\ntest_back(queue)  # 5\n\ntest_dequeue(queue)  # [2, 3, 4, 5]\ntest_dequeue(queue)  # [3, 4, 5]\ntest_dequeue(queue)  # [4, 5]\ntest_dequeue(queue)  # [5]\n\ntest_emptiness(queue)  # False\ntest_size(queue)  # 1\ntest_front(queue)  # 5\ntest_back(queue)  # 5\n\ntest_dequeue(queue)  # []\n\ntest_emptiness(queue)  # True\ntest_size(queue)  # 0\n\n# Other test\nqueue = Queue()\nqueue.enqueue(1)\nqueue.enqueue(2)\nqueue.enqueue(3)\nqueue.enqueue(4)\nqueue.enqueue(5)\n\nfor item in queue.items:\n    print(item)\n\ntest_front(queue)\ntest_back(queue)\n\nqueue.dequeue()\ntest_front(queue)\n\nqueue.dequeue()\ntest_size(queue)\n\nwhile not queue.is_empty():\n    test_front(queue)\n    queue.dequeue()\n\ntest_size(queue)\n"
  },
  {
    "path": "computer_science/data_structures/queue/tests/queue.test.js",
    "content": "import { describe, expect, it } from 'vitest';\nimport { Queue } from '../queue';\n\ndescribe('Queue', () => {\n  it('', () => {\n    const queue = new Queue();\n\n    expect(queue.isEmpty()).toBeTruthy();\n    expect(queue.size()).toEqual(0);\n\n    queue.enqueue(1);\n    queue.enqueue(2);\n    queue.enqueue(3);\n    queue.enqueue(4);\n    queue.enqueue(5);\n\n    expect(queue.isEmpty()).toBeFalsy();\n    expect(queue.size()).toEqual(5);\n    expect(queue.front()).toEqual(1);\n    expect(queue.back()).toEqual(5);\n\n    expect(queue.items).toEqual([1, 2, 3, 4, 5]);\n\n    queue.dequeue();\n    expect(queue.items).toEqual([2, 3, 4, 5]);\n\n    queue.dequeue();\n    expect(queue.items).toEqual([3, 4, 5]);\n\n    queue.dequeue();\n    expect(queue.items).toEqual([4, 5]);\n\n    queue.dequeue();\n    expect(queue.items).toEqual([5]);\n\n    queue.dequeue();\n    expect(queue.isEmpty()).toBeTruthy();\n  });\n\n  it('', () => {\n    const queue = new Queue();\n\n    queue.enqueue(1);\n    queue.enqueue(2);\n    queue.enqueue(3);\n    queue.enqueue(4);\n    queue.enqueue(5);\n\n    expect(queue.items).toEqual([1, 2, 3, 4, 5]);\n    expect(queue.front()).toEqual(1);\n    expect(queue.back()).toEqual(5);\n\n    while (!queue.isEmpty()) {\n      queue.dequeue();\n    }\n\n    expect(queue.isEmpty()).toBeTruthy();\n  });\n});\n"
  },
  {
    "path": "computer_science/data_structures/segment_tree/frequency.cpp",
    "content": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define MAX_SIZE (1 << 20)\n\nint A[4];\nint segtree[MAX_SIZE];\nmap<int, int> frequencyMap;\n\nvoid initialize_frequency_map() {\n  for (int i = 0; i <= 4; i++) {\n    if (frequencyMap.find(A[i]) == frequencyMap.end()) frequencyMap[A[i]] = 1;\n    else frequencyMap[A[i]]++;\n  }\n}\n\nvoid build_segtree(int node, int start, int end) {\n  if (start == end) {\n    segtree[node] = A[start];\n  } else {\n    int middle = (start + end) / 2;\n    build_segtree(node * 2, start, middle);\n    build_segtree(node * 2 + 1, middle + 1, end);\n\n    if (frequencyMap[segtree[node * 2]] > frequencyMap[segtree[node * 2 + 1]]) segtree[node] = segtree[node * 2];\n    else if (frequencyMap[segtree[node * 2]] < frequencyMap[segtree[node * 2 + 1]]) segtree[node] = segtree[node * 2 + 1];\n    else segtree[node] = max(segtree[node * 2], segtree[node * 2 + 1]);\n  }\n}\n\nint main() {\n  A[0] = 1;\n  A[1] = 3;\n  A[2] = 3;\n  A[3] = 1;\n  A[4] = 1;\n\n  initialize_frequency_map();\n\n  build_segtree(1, 0, 4);\n\n  for (int i = 1; i < 10; i++) cout << segtree[i] << \" \";\n\n  return 0;\n}\n"
  },
  {
    "path": "computer_science/data_structures/segment_tree/max.cpp",
    "content": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define MAX_SIZE (1 << 20)\n\nint A[4];\nint segtree[MAX_SIZE];\n\nvoid build_segtree(int node, int start, int end) {\n  if (start == end) {\n    segtree[node] = A[start];\n  } else {\n    int middle = (start + end) / 2;\n    build_segtree(node * 2, start, middle);\n    build_segtree(node * 2 + 1, middle + 1, end);\n    segtree[node] = max(segtree[node * 2], segtree[node * 2 + 1]);\n  }\n}\n\nint main() {\n  A[0] = 1;\n  A[1] = 3;\n  A[2] = 3;\n  A[3] = 1;\n  A[4] = 1;\n\n  build_segtree(1, 0, 4);\n\n  for (int i = 1; i < 10; i++) cout << segtree[i] << \" \";\n\n  return 0;\n}\n"
  },
  {
    "path": "computer_science/data_structures/segment_tree/min.cpp",
    "content": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define MAX_SIZE (1 << 20)\n\nint A[4];\nint segtree[MAX_SIZE];\n\nvoid build_segtree(int node, int start, int end) {\n  if (start == end) {\n    segtree[node] = A[start];\n  } else {\n    int middle = (start + end) / 2;\n    build_segtree(node * 2, start, middle);\n    build_segtree(node * 2 + 1, middle + 1, end);\n    segtree[node] = min(segtree[node * 2], segtree[node * 2 + 1]);\n  }\n}\n\nint main() {\n  A[0] = 1;\n  A[1] = 3;\n  A[2] = 3;\n  A[3] = 1;\n  A[4] = 1;\n\n  build_segtree(1, 0, 4);\n\n  for (int i = 1; i < 10; i++) cout << segtree[i] << \" \";\n\n  return 0;\n}\n"
  },
  {
    "path": "computer_science/data_structures/segment_tree/sum.cpp",
    "content": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define MAX_SIZE (1 << 20)\n\nint A[4];\nint segtree[MAX_SIZE];\n\nvoid build_segtree(int node, int start, int end) {\n  if (start == end) {\n    segtree[node] = A[start];\n  } else {\n    int middle = (start + end) / 2;\n    build_segtree(node * 2, start, middle);\n    build_segtree(node * 2 + 1, middle + 1, end);\n    segtree[node] = segtree[node * 2] + segtree[node * 2 + 1];\n  }\n}\n\nint main() {\n  A[0] = 1;\n  A[1] = 3;\n  A[2] = 3;\n  A[3] = 1;\n  A[4] = 1;\n\n  build_segtree(1, 0, 4);\n\n  for (int i = 1; i < 10; i++) cout << segtree[i] << \" \";\n\n  return 0;\n}\n"
  },
  {
    "path": "computer_science/data_structures/set/set.js",
    "content": "export class Set {\n  constructor() {\n    this.items = {};\n  }\n\n  add(item) {\n    if (!this.has(item)) {\n      this.items[item] = item;\n    }\n    return this;\n  }\n\n  delete(item) {\n    if (this.has(item)) {\n      delete this.items[item];\n      return true;\n    }\n\n    return false;\n  }\n\n  has(item) {\n    return this.items.hasOwnProperty(item);\n  }\n\n  clear() {\n    this.items = {};\n  }\n\n  size() {\n    return Object.keys(this.items).length;\n  }\n\n  values() {\n    return Object.values(this.items);\n  }\n\n  union(otherSet) {\n    const unionSet = new Set();\n\n    this.values().forEach((value) => unionSet.add(value));\n    otherSet.values().forEach((value) => unionSet.add(value));\n\n    return unionSet;\n  }\n\n  intersection(otherSet) {\n    const intersectionSet = new Set();\n\n    for (let value of this.values()) {\n      if (otherSet.has(value)) {\n        intersectionSet.add(value);\n      }\n    }\n\n    return intersectionSet;\n  }\n\n  difference(otherSet) {\n    const differenceSet = new Set();\n\n    for (let value of this.values()) {\n      if (!otherSet.has(value)) {\n        differenceSet.add(value);\n      }\n    }\n\n    return differenceSet;\n  }\n\n  isSubsetOf(otherSet) {\n    for (let value of this.values()) {\n      if (!otherSet.has(value)) {\n        return false;\n      }\n    }\n\n    return true;\n  }\n}\n"
  },
  {
    "path": "computer_science/data_structures/set/sets.cpp",
    "content": "// add an element, but do not allow duples [duplicates?]\n// remove elements\n// get count of elements (distinct elements)\n// check whether elements are present in set\n\n#include <iostream>\n#include <vector>\n#include <set>\n\nusing namespace std;\n\nint main() {\n\n  set<int> s;\n\n  // adding elements to set\n  for (int i = 0; i <= 100; i++)\n    s.insert(i);\n\n  // set doesn't accept duplicate elements\n  s.insert(50);\n\n  // need to be 101 (100 elements + 0 number)\n  cout << s.size() << endl;\n\n  // remove even numbers\n  for (int i = 0; i <= 100; i+=2)\n    s.erase(i);\n\n  // need to be 50\n  cout << s.size() << endl;\n\n  // calculate the sum of set elements\n  int total = 0;\n  for (set<int>::const_iterator iterator = s.begin(); iterator != s.end(); iterator++)\n    total += *iterator;\n\n  cout << total << endl;\n\n  // removing the duplicates from a vector\n  vector<int> v;\n  for (int i = 10; i > 0; i--)\n    v.push_back(i);\n\n  v.push_back(5);\n\n  set<int> s2;\n  for (int i = 1; i <= 10; i++)\n    s2.insert(v[i]);\n\n  vector<int> v2;\n  for (set<int>::const_iterator iterator = s2.begin(); iterator != s2.end(); iterator++)\n    v2.push_back(*iterator);\n\n  for (int i = 0; i < 10; i++)\n    cout << v2[i] << endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "computer_science/data_structures/set/tests/set.test.js",
    "content": "import { describe, it, expect } from 'vitest';\nimport { Set } from '../set';\n\ndescribe('Set', () => {\n  it('performs all behaviors correctly', () => {\n    const set = new Set();\n    set.add(1);\n    expect(set.values()).toEqual([1]);\n    expect(set.has(1)).toEqual(true);\n    expect(set.size()).toEqual(1);\n    set.add(2);\n    expect(set.values()).toEqual([1, 2]);\n    expect(set.has(2)).toEqual(true);\n    expect(set.size()).toEqual(2);\n    set.delete(1);\n    expect(set.values()).toEqual([2]);\n    set.delete(2);\n    expect(set.values()).toEqual([]);\n  });\n\n  it('union sets', () => {\n    const setA = new Set();\n    setA.add(1);\n    setA.add(2);\n    setA.add(3);\n\n    const setB = new Set();\n    setB.add(3);\n    setB.add(4);\n    setB.add(5);\n    setB.add(6);\n\n    const unionAB = setA.union(setB);\n    expect(unionAB.values()).toEqual([1, 2, 3, 4, 5, 6]);\n  });\n\n  it('intersection sets', () => {\n    const setA = new Set();\n    setA.add(1);\n    setA.add(2);\n    setA.add(3);\n\n    const setB = new Set();\n    setB.add(2);\n    setB.add(3);\n    setB.add(4);\n\n    const intersectionAB = setA.intersection(setB);\n    expect(intersectionAB.values()).toEqual([2, 3]);\n  });\n\n  it('difference sets', () => {\n    const setA = new Set();\n    setA.add(1);\n    setA.add(2);\n    setA.add(3);\n\n    const setB = new Set();\n    setB.add(2);\n    setB.add(3);\n    setB.add(4);\n\n    const differenceAB = setA.difference(setB);\n    expect(differenceAB.values()).toEqual([1]);\n  });\n\n  it('is subset of', () => {\n    const setA = new Set();\n    setA.add(1);\n    setA.add(2);\n\n    const setB = new Set();\n    setB.add(1);\n    setB.add(2);\n    setB.add(3);\n\n    const setC = new Set();\n    setC.add(2);\n    setC.add(3);\n    setC.add(4);\n\n    expect(setA.isSubsetOf(setB)).toEqual(true);\n    expect(setA.isSubsetOf(setC)).toEqual(false);\n  });\n});\n"
  },
  {
    "path": "computer_science/data_structures/stack/deque_api.py",
    "content": "from collections import deque\n\nq = deque()\nq.append(1)\nq.append(2)\nq.append(3)\n\nprint(q)\n\nprint(q.pop())\nprint(q.pop())\nprint(q.pop())\n"
  },
  {
    "path": "computer_science/data_structures/stack/stack.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\n#define MAX_STACK_SIZE 10\n\nclass Stack {\nprivate:\n\tint container[MAX_STACK_SIZE];\n\tint numberOfElements;\n\npublic:\n\tStack() {\n\t\tnumberOfElements = 0;\n\t}\n\n\tvoid push(int element) {\n\t\tif (numberOfElements > MAX_STACK_SIZE) {\n\t\t\tcout << \"Error: Stack Overflow\";\n\t\t} else {\n\t\t\tcontainer[numberOfElements] = element;\n\t\t\tnumberOfElements++;\n\t\t}\n\t}\n\n\tint pop() {\n\t\tif (isEmpty()) {\n\t\t\tcout << \"Error: No element to pop\";\n\t\t} else {\n\t\t\tnumberOfElements--;\n\t\t\treturn container[numberOfElements];\n\t\t}\n\t}\n\n\tint top() {\n\t\treturn container[numberOfElements-1];\n\t}\n\n\tbool isEmpty() {\n\t\treturn numberOfElements == 0;\n\t}\n};\n\nint main() {\n\tStack stack;\n\n\tif (stack.isEmpty()) cout << \"Stack is empty\" << endl;\n\n\tstack.push(1);\n\tstack.push(2);\n\tstack.push(3);\n\n\tcout << stack.pop() << endl;\n\n\tstack.push(10);\n\n\tcout << stack.top() << endl;\n\n\tif (!stack.isEmpty()) cout << \"Stack is not empty\" << endl;\n\n\treturn 0;\n}"
  },
  {
    "path": "computer_science/data_structures/stack/stack.js",
    "content": "const push = (stack, item) => [item, ...stack];\n\nconst pop = (stack) => stack.slice(1);\n\nconst top = (stack) => stack[0];\n\nconst isEmpty = (stack) => size(stack) === 0;\n\nconst size = (stack) => stack.length;\n\n// testing\nlet stack = [];\n\nconsole.log(isEmpty(stack));\n\nstack = push(stack, 1);\nconsole.log(stack);\nstack = push(stack, 2);\nconsole.log(stack);\nstack = push(stack, 3);\nconsole.log(stack);\nstack = push(stack, 4);\nconsole.log(stack);\nstack = push(stack, 5);\nconsole.log(stack);\n\nconsole.log(top(stack));\nconsole.log(size(stack));\nconsole.log(isEmpty(stack));\n\nstack = pop(stack);\nstack = pop(stack);\nstack = pop(stack);\nstack = pop(stack);\n\nconsole.log(isEmpty(stack));\nconsole.log(top(stack));\nstack = pop(stack);\nconsole.log(isEmpty(stack));\nconsole.log(size(stack));\n"
  },
  {
    "path": "computer_science/data_structures/stack/stack.py",
    "content": "# Stack Big O complexity\n\n# Push: O(1) - Constant Time\n# Pop (remove): O(1) - Constant Time\n# Top (top): O(1) - Constant Time\n# Is Empty: O(1) - Constant Time\n# Size: O(1) - Constant Time\n\n\nclass Emptiness(Exception):\n    pass\n\n\nclass Stack:\n    def __init__(self):\n        self.items = []\n\n    def push(self, item):\n        self.items.append(item)\n\n    def pop(self):\n        if self.is_empty():\n            raise Emptiness('The Stack is empty')\n\n        return self.items.pop()\n\n    def is_empty(self):\n        return self.size() == 0\n\n    def top(self):\n        if self.is_empty():\n            raise Emptiness('The Stack is empty')\n\n        return self.items[-1]\n\n    def size(self):\n        return len(self.items)\n\n\nstack = Stack()\n\nprint(stack.is_empty())\n\nstack.push(1)\nprint(stack.items)\nstack.push(2)\nprint(stack.items)\nstack.push(3)\nprint(stack.items)\nstack.push(4)\nprint(stack.items)\nstack.push(5)\nprint(stack.items)\n\nprint(stack.is_empty())\nprint(stack.top())\n\nprint(stack.pop())\nprint(stack.pop())\nprint(stack.pop())\nprint(stack.pop())\n\nprint(stack.is_empty())\n\nprint(stack.pop())\n\nprint(stack.is_empty())\n\n# reversing a list\n\n\ndef reverse(bookshelf):\n    stack = Stack()\n\n    for book in bookshelf:\n        stack.push(book)\n\n    reversed_bookshelf = []\n\n    while not stack.is_empty():\n        reversed_bookshelf.append(stack.pop())\n\n    return reversed_bookshelf\n\n\nbookshelf = [\n    'Harry Potter',\n    'Atomic Habits',\n    'Leonardo da Vinci',\n    'Sapiens',\n    'Peak'\n]\n\nreversed_bookshelf = reverse(bookshelf)\n\nprint(reversed_bookshelf)\n"
  },
  {
    "path": "computer_science/data_structures/stack/stack_class.js",
    "content": "class Stack {\n  constructor() {\n    this.items = [];\n  }\n\n  push(item) {\n    this.items.push(item);\n  }\n\n  pop() {\n    return this.items.pop();\n  }\n\n  top() {\n    return this.items[this.items.length - 1];\n  }\n\n  isEmpty() {\n    return this.size() === 0;\n  }\n\n  size() {\n    return this.items.length;\n  }\n}\n\n// testing\nconst stack = new Stack();\n\nconsole.log(stack.isEmpty());\n\nstack.push(1);\nconsole.log(stack.items);\nstack.push(2);\nconsole.log(stack.items);\nstack.push(3);\nconsole.log(stack.items);\nstack.push(4);\nconsole.log(stack.items);\nstack.push(5);\nconsole.log(stack.items);\n\nconsole.log(stack.isEmpty());\nconsole.log(stack.top());\n\nstack.pop();\nconsole.log(stack.items);\nstack.pop();\nconsole.log(stack.items);\nstack.pop();\nconsole.log(stack.items);\nstack.pop();\nconsole.log(stack.items);\n\nconsole.log(stack.isEmpty());\n\nstack.pop();\nconsole.log(stack.items);\n\nconsole.log(stack.isEmpty());\nconsole.log(stack.top());\n\n// Reversing a list with the stack data structure\nfunction reverse(list) {\n  const stack = new Stack();\n\n  for (item of list) {\n    stack.push(item);\n  }\n\n  const reversedList = [];\n\n  while (!stack.isEmpty()) {\n    reversedList.push(stack.pop());\n  }\n\n  return reversedList;\n}\n\nconst reversedBooks = reverse([\n  'Harry Potter',\n  'Atomic Habits',\n  'Leonardo da Vinci',\n  'Sapiens',\n  'Peak',\n]);\n\nconsole.log(reversedBooks);\n"
  },
  {
    "path": "computer_science/data_structures/stack/stack_closure.js",
    "content": "const createStack = () => {\n  let items = [];\n\n  const push = (item) => items = [item, ...items];\n  const pop = () => items = items.slice(1);\n  const top = () => items[0];\n  const isEmpty = () => size() === 0;\n  const size = () => items.length;\n  const getItems = () => items;\n\n  return {\n    push,\n    pop,\n    top,\n    isEmpty,\n    size,\n    getItems\n  };\n};\n\n// testing\nconst stack = createStack();\n\nconsole.log(stack.isEmpty());\n\nstack.push(1);\nconsole.log(stack.getItems());\nstack.push(2);\nconsole.log(stack.getItems());\nstack.push(3);\nconsole.log(stack.getItems());\nstack.push(4);\nconsole.log(stack.getItems());\nstack.push(5);\nconsole.log(stack.getItems());\n\nconsole.log(stack.top());\nconsole.log(stack.size());\nconsole.log(stack.isEmpty());\n\nstack.pop();\nconsole.log(stack.getItems());\nstack.pop();\nconsole.log(stack.getItems());\nstack.pop();\nconsole.log(stack.getItems());\nstack.pop();\nconsole.log(stack.getItems());\n\nconsole.log(stack.isEmpty());\nconsole.log(stack.top());\nstack.pop();\nconsole.log(stack.getItems());\nconsole.log(stack.isEmpty());\nconsole.log(stack.size());\n"
  },
  {
    "path": "computer_science/data_structures/string/strings.cpp",
    "content": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main() {\n\n\t// defining strings\n\tstring string1 = \"hello world\";\n\tstring string2;\n\n\t// printing strings\n\tcout << string1 << endl;\n\n\t// finding letter(s) in a string\n\t// return npos --> -1 if don't find the element\n\tcout << string1.find(\"e\") << endl;\n\n\t// using input for string\n\tcin >> string2;\n\tcout << string2 << endl;\n\n\t// size\n\tcout << string1.size() << endl;\n\tcout << string2.size() << endl;\n\n\t// substrings\n\tcout << string1.substr(0, 5) << endl;\n\tcout << string1.substr(6, string1.size() - 1) << endl;\n\n\tstring palavra = \"lalala.lololo\";\n\tcout << palavra.substr(6, 1) << endl;\n\tcout << palavra.substr(0, 6 - 0) << endl;\n\tcout << palavra.substr(6+1, palavra.size()-6) << endl;\n\n\t// string to integer\n\tstring um = \"1\";\n\tcout << stoi(um) << \" - deu certo!\" << endl;\n\n\tstring vinte = \"20\";\n\tcout << stoi(vinte) << \" - deu certo.. de novo!\" << endl;\n\n\t// last element of string\n\tstring word = \"Leandro\";\n\tcout << palavra.back() << endl;\n\n\t// we can iterate a string: each char\n\tfor (int i = 0; i < word; i++) cout << word[i] << \" \";\n\tcout << endl;\n\n\t// compare string letter with char\n\tfor (int i = 0; i < word.size(); i++) if (word[i] == 'a') cout << word[i] << \" \";\n\tcout << endl;\n\n\t// use cin to get string\n\t// use getline(cin, string) to get a line of strings\n\n\treturn 0;\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"algorithms\",\n  \"scripts\": {\n    \"test\": \"vitest\"\n  },\n  \"devDependencies\": {\n    \"vitest\": \"0.34.5\"\n  },\n  \"type\": \"module\"\n}\n"
  },
  {
    "path": "problem-solving.md",
    "content": "# Algorithm Problem Solving\n\n0. Start with the naive solution. It shows you understand the problem.\n1. Think out loud, even if it's quiet. It lets the interviewer help out if you get stuck.\n2. Write your own test cases. Write at least 3 test cases to show you understand the problem.\n3. Outline your algorithm on the IDE. It makes it easier for everyone to follow along.\n4. Refer back to each step of your algorithm as you're coding. This shows you can walk the walk.\n5. Dry run your code line by line against your test cases. Dont wait for the interviewer to ask you to do it.\n6. Offer to optimize the algorithm. Point out the bottleneck first then explain what you need to do differently.\n7. Solve for the running time. Solve it throughout your code then explain your nested for loop makes it O(n^2)\n8. Use good variable names. Thing1 and thing2 aren't good things to write.\n9. Abstract functions away. Don't spend the entire interview on a parsing function that isn't important to the algorithm\n10. Do it for the interviewer. Keep checking in with the interviewer if they understand what's going on or if you need to walk them through your ideas.\n"
  },
  {
    "path": "system-design.md",
    "content": "# System Design\n\n- [Preparing to System Design](https://qr.ae/TSJEwu)\n- [InterviewBit System Design course](https://www.interviewbit.com/courses/system-design/)\n- [System Design Primer](https://github.com/donnemartin/system-design-primer)\n- [The System Design Process](https://www.hiredintech.com/classrooms/system-design/lesson/55)\n- [High Scalability](http://highscalability.com/)\n- [System Design Template](https://leetcode.com/discuss/career/229177/My-System-Design-Template)\n"
  }
]