[
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/documentation_request.yml",
    "content": "name: Docs request\ndescription: Suggest lesson, propose new data-structure and algorithms, discuss new ideas\ntitle: \"new lesson: <name-of-the-lesson>\"\nlabels: [\"⭐ goal: addition\"]\nbody:\n  - type: textarea\n    id: requesttype\n    attributes:\n      label: ⭐ Request Type\n      description: describe the name of the lesson or section you want to add.\n    validations:\n      required: true\n  - type: textarea\n    id: location\n    attributes:\n      label: 💻 Location\n      description: |\n        Where you think your lesson should be placed(location) so that there will be ease in understanding for new comers.\n    validations:\n      required: true\n  - type: textarea\n    id: addtionalinfo\n    attributes:\n      label: ❌ Additional Info\n      description: |\n        If you have any additional information that you think will help the community.\n    validations:\n      required: false\n  - type: markdown\n    attributes:\n      value: |\n        You can also join the Discord community [here](#)\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/improvement_request.yml",
    "content": "name: Improvement request\ndescription: propose improvements, adding new code, or any new features\ntitle: \"improve: <name-of-the-lesson>\"\nlabels: [\"⭐ goal: addition\"]\nbody:\n  - type: textarea\n    id: summary\n    attributes:\n      label: ⭐ Summary\n      description: A brief summary of what you'd like to see added or improved.\n    validations:\n      required: true\n  - type: textarea\n    id: location\n    attributes:\n      label: 💻 Location\n      description: |\n        Describe where or in which section/lesson you want to do improvements.\n    validations:\n      required: true\n  - type: textarea\n    id: additionalinfo\n    attributes:\n      label: ❌ Additional Info\n      description: |\n        Any additional information you'd like to provide.\n    validations:\n      required: false\n  - type: markdown\n    attributes:\n      value: |\n        You can also join the Discord community [here](#)\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/other.yml",
    "content": "name: Other\ndescription: Use this for any other issues. PLEASE do not create blank issues\ntitle: \"[OTHER]\"\nlabels: [\"🛠 status: fix\"]\nbody:\n  - type: markdown\n    attributes:\n      value: \"# Other issue\"\n  - type: textarea\n    id: issuedescription\n    attributes:\n      label: Other\n      description: Provide a clear and concise explanation of your issue.\n    validations:\n      required: true\n  - type: textarea\n    id: extrainfo\n    attributes:\n      label: Additional information\n      description: Is there anything else we should know about this issue?\n    validations:\n      required: false\n"
  },
  {
    "path": ".github/pull_request-template.md",
    "content": "<!--\n(Thanks for sending a pull request! If you have fixed any kind of typo or grammatical error then please Name your pull request in the format of \"fixed typo: <name-of-the-lesson>\".)\n-->\n\n<!-- Add the issue number that is fixed by this PR (In the form Fixes #123) -->\n\nFixes #\n\n#### Short description of what this resolves:\n\n<!--- issue name --->\n\n#### What Changes proposed in this pull request:\n\n-\n-\n-\n\n#### Checklist\n\n<!-- Remove items that do not apply. For completed items, change [ ] to [x]. -->\n\n- [ ] Added description of change\n- [ ] Added file name matches [File name guidelines](https://github.com/Utkarsh1504/DSA-Java/blob/main/CONTRIBUTING.md#requesting-a-lesson)\n- [ ] Added code examples, test must pass\n- [ ] Added documentation so that the program is self-explanatory and educational.\n- [ ] Relevant documentation/comments is changed or added\n- [ ] PR title follows semantic [commit guidelines](https://github.com/Utkarsh1504/DSA-Java/blob/main/CONTRIBUTING.md#requesting-a-lesson)\n- [ ] Search previous suggestions before making a new one, as yours may be a duplicate.\n- [ ] I acknowledge that all my contributions will be made under the project's license.\n\nNotes: <!-- Please add a one-line description for developers or pull request viewers -->\n"
  },
  {
    "path": ".github/workflows/gatsby.yml",
    "content": "name: Deploy Gatsby Site to GitHub Pages\n\non:\n  push:\n    branches:\n      - main\n\njobs:\n  deploy:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@master\n      - name: npm install, build, and csv\n        run: |\n          npm install\n          npm run build\n          npm run csv\n      - name: Deploy site to gh-pages branch\n        uses: crazy-max/ghaction-github-pages@v2\n        with:\n          target_branch: gh-pages\n          build_dir: public\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n"
  },
  {
    "path": ".gitignore",
    "content": "# Project dependencies\n# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git\nnode_modules\n.cache/\n# Build directory\npublic/\n.DS_Store\nyarn-error.log\n\n\n/.idea\n"
  },
  {
    "path": ".prettierrc",
    "content": "{}\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as\ncontributors and maintainers pledge to making participation in our project and\nour community a harassment-free experience for everyone, regardless of age, body\nsize, disability, ethnicity, sex characteristics, gender identity and expression,\nlevel of experience, education, socio-economic status, nationality, personal\nappearance, race, religion, or sexual identity and orientation.\n\n## Our Standards\n\nExamples of behavior that contributes to creating a positive environment\ninclude:\n\n- Using welcoming and inclusive language\n- Being respectful of differing viewpoints and experiences\n- Gracefully accepting constructive criticism\n- Focusing on what is best for the community\n- Showing empathy towards other community members\n\nExamples of unacceptable behavior by participants include:\n\n- The use of sexualized language or imagery and unwelcome sexual attention or\n  advances\n- Trolling, insulting/derogatory comments, and personal or political attacks\n- Public or private harassment\n- Publishing others' private information, such as a physical or electronic\n  address, without explicit permission\n- Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n## Our Responsibilities\n\nProject maintainers are responsible for clarifying the standards of acceptable\nbehavior and are expected to take appropriate and fair corrective action in\nresponse to any instances of unacceptable behavior.\n\nProject maintainers have the right and responsibility to remove, edit, or\nreject comments, commits, code, wiki edits, issues, and other contributions\nthat are not aligned to this Code of Conduct, or to ban temporarily or\npermanently any contributor for other behaviors that they deem inappropriate,\nthreatening, offensive, or harmful.\n\n## Scope\n\nThis Code of Conduct applies both within project spaces and in public spaces\nwhen an individual is representing the project or its community. Examples of\nrepresenting a project or community include using an official project e-mail\naddress, posting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event. Representation of a project may be\nfurther defined and clarified by project maintainers.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported by contacting a maintainer of the [project team members](https://github.com/orgs/dsa-java)\nor write a email to 'utkarshmishra73444@gmail.com'. All complaints will be reviewed and investigated and will result\nin a response that is deemed necessary and appropriate to the circumstances. The project team is\nobligated to maintain confidentiality with regard to the reporter of an incident.\nFurther details of specific enforcement policies may be posted separately.\n\nProject maintainers who do not follow or enforce the Code of Conduct in good\nfaith may face temporary or permanent repercussions as determined by other\nmembers of the project's leadership.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,\navailable at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see\nhttps://www.contributor-covenant.org/faq\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to DSA-Java\n\nFirst of all, thanks for taking the time to contribute! This project can only grow and live by your countless contributions. To keep this project maintainable, we have developed some guidelines for our contributors.\n\nPlease note that by participating, you are expected to uphold the [Contributor Covenant Code of Conduct](CODE_OF_CONDUCT.md).\n\n## Table of Content\n\n- [Terms](#terms)\n- [Lesson](#lesson)\n- [Requesting A Lesson](#requesting-a-lesson)\n- [Fixing Typos](#fixing-typos)\n- [Improving Lesson](#improving-lesson)\n- [Our Standards](#our-standards)\n- [Markdown Format](#markdown-format)\n- [Communication](#communication)\n\n---\n\n## Terms\n\nHere are some terms that we will use in this repo:\n\n- `path` needs a leading slash. This will be slug of the lesson\n- `title`- will be the title displayed on the `Table of Contents` and on the page itself\n- `order`- the order of which the item should appear in the table of contents. It should be in `<Number><Capital-letter>` format where the number corresponds to the section itself and the letter corresponds to the order of the lesson inside the section, e.g. 3B means under the section 3 and the order of the lesson will be B(second)\n- `section` - the title of the section that the article is in. Only the first lesson for each section will be used.\n- `description` - a one-to-three sentence summary of the lesson. Used for the meta tag for social shares and SEO. If no description is given, the siteMetadata.description for the site is used.\n- `icon` the Font Awesome icon you want for the home page of the site\n\n## Lesson\n\nThe crux of this site is are the `lesson`. Provided are two examples. Each lesson needs a frontmatter path, order, and title. Generally you should make the path and the file name match for ease of finding it.\n\n- In `Lesson` directory there are various sections. You can start contributing from there.\n- Inside each of the sections `lesson` present in the form of markdown. If you wanted to add a new lesson make a new file with `.md` extension and add at the top it.\n\n```yml\n\n    ---\n    path: \"/pathName\"\n    title: \"TitleName\"\n    order: \"<Number><CapitalLetter>\"\n    section: \"SectionName\"\n    description: \"Learn DSA-Java\"\n    ---\n```\n\n- Modify this according to your contribution and go ahead\n- For writing concepts, take a look at the other [lessons]('lesson/Learn-Programming-Language/operator.md') markdown and make sure it is written in a similar way.\n\n## Requesting A Lesson\n\nfor requesting a lesson simply raise a new issue in the `Issues` section.\n\n- Search for other issues already requesting the lesson.\n- If an issue doesn't exist, create an issue naming it `new lesson: <name-of-the-lesson>`\n- provide description as mentioned in issue template.\n- Please create separate issues for any concept or lesson that you want to add.\n\n## Fixing Typos\n\nfor fixing typo just make a pull request with your fixes, naming it:\n\n- `fixed typo: <name-of-the-lesson>`\n- provide description as mentioned in pull request template.\n\n## Improving lesson\n\nfor any improvement in the lesson raise a new issue in the <code>Issues</code> section, Naming it:\n\n- `improvement: <name-of-the-lesson>`\n- provide description as mentioned in issue template.\n- also one thing to keep in mind, if you wanted to do improvement in the lesson, It should be clear and easy to understand.\n\n## Our Standards\n\nBefore you submit your PR, please ensure that they meet the following standard:\n\n- For writing the concept, take a look at the other [lessons]('lesson/Learn-Programming-Language/operator.md') markdown and make sure it is written in a similar way.\n- Content inside the lesson should not be copied or plagarized from any other resources, you need to write your own content using your understanding about the concept.\n- Code example should not copied from anywhere else, you should set example by your own.\n- for adding images and gifs related to the lesson, make sure it is copyright free and not used for commercial purpose. but in case you don't find any image or gif on internet, you can use the [draw.io](draw.io) to make your own images. Images and gif used should be kept in `lesson/images/` directory.\n\n## Markdown Format\n\nHere are some guidelines for writing markdown, In the same fashion you have to write the markdown for the lessons:\n\n- All the main headings should be in `##` or `<h2>` format.\n- please do not use any heading at the start of the lesson, it will be used by default by the frontmatters, so don't start writing your lesson with a heading.\n- All the subheadings should be in `###` or `<h3>` or `####`, `<h4>` format and so on.\n\n## Communication\n\nWe are running a communication channel. You can go here to talk, discuss, and more with the maintainers and other people, too. Here's the invitation: [discord](#)\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright {yyyy} {name of copyright owner}\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License."
  },
  {
    "path": "README.md",
    "content": "<h1 align=\"center\">Getting Started with Data Structures and Algorithms</h1> \n<br>\n\n<div align=\"center\">\n\n[![Welcome to my profile](https://img.shields.io/badge/Hello,Programmer!-Welcome-blue.svg?style=flat&logo=github)](https://github.com/utkarsh1504)\n[![Open Source Love](https://badges.frapsoft.com/os/v2/open-source.svg?v=103)](https://github.com/utkarsh1504/DSA-Java)\n![Lines of code](https://img.shields.io/tokei/lines/github/utkarsh1504/DSA-Java?color=red&label=Lines%20of%20Code)\n![License](https://img.shields.io/badge/License-Apache-red.svg)\n![Stars](https://img.shields.io/github/stars/utkarsh1504/DSA-Java?style=flat&logo=github)\n![Forks](https://img.shields.io/github/forks/utkarsh1504/DSA-Java?style=flat&logo=github)\n\n</div>\n\n<div align=\"center\">\n  <img src=\"./static/r.svg\" alt=\"ds-algo\">\n</div>\n\n<br>\n\n<div align=\"center\">\n  <img src=\"https://forthebadge.com/images/badges/for-you.svg\" />\n  <img src=\"https://forthebadge.com/images/badges/uses-html.svg\" alt=\"html\">\n  <img src=\"https://forthebadge.com/images/badges/made-with-markdown.svg\" alt=\"css\">\n  <img src=\"https://forthebadge.com/images/badges/made-with-c-plus-plus.svg\" alt=\"C++\">\n  <img src=\"https://forthebadge.com/images/badges/made-with-javascript.svg\" alt=\"js\">\n  <img src=\"https://forthebadge.com/images/badges/open-source.svg\" alt=\"os\">\n  <img src=\"https://forthebadge.com/images/badges/check-it-out.svg\" alt=\"check\">\n  <img src=\"\" alt=\"\">\n  <img src=\"https://forthebadge.com/images/badges/built-by-developers.svg\" />\n</div>\n\n<p align=\"center\">\n  <b>A learning purpose website for everyone to learn Data Structures and Algorithms at one place in a very simple way using the language Java.</b>\n</p>\n\n<h2>Table of Contents</h2>\n<ol>\n    <li><a href=\"#about\">About</a></li>\n    <li><a href=\"#getting-started\">Getting Started</a></li>\n    <li><a href=\"#request-docs\">Lesson Requests</a></li>\n    <li><a href=\"#contribute\">Contributing</a></li>\n    <li><a href=\"#prs\">Pull Requests</a></li>\n    <li><a href=\"#license\">License</a></li>\n</ol>\n\n## **About**\n\nWe are building a site which will contain all the DS-Algo related things. It will contain just the relevent concepts which are needed to get started from scratch to go upto its hard parts. It will also contains some assigment question from different-different platforms. It is completely free, open-sourced, everyone can use it to learn, taking notes, doing revision, making tutorial etc. That's all the goal is.\n\n## **Getting Started**\n\nYou are just 11 step away from making your contribution to this repo.\nFor the quick start, you can follow the steps below:\n\n1. Star <a href=\"https://github.com/utkarsh1504/DSA-Java\" title=\"this\">this</a> repository.\n2. Fork <a href=\"https://github.com/utkarsh1504/DSA-Java\" title=\"this\">this</a> repository.\n3. Clone the **forked** repository.\n\n```yml\ngit clone https://github.com/<your-github-username>/DSA-Java\n```\n\n4. Set <a href=\"https://github.com/utkarsh1504/DSA-Java\" title=\"this\">this</a> repository as upstream repository.\n\n```yml\ngit remote add upstream https://github.com/Utkarsh1504/DSA-Java.git\n```\n\n5. Navigate to the project directory.\n\n```yml\ncd DSA-Java\n```\n\n6. Pull upstream commits(changes). Always keep your **main** branch updated with the project's **main/master** branch(updated repository).\n\n```yml\ngit pull upstream main\n```\n\n7. Create a new branch.\n\n```yml\ngit checkout -b <your_branch_name>\n```\n\n#### **Project Setup:**\n\nRun the following command to install the required dependencies.\n\n1. `npm install --global gatsby-cli` - make sure you're on Gatsby v2+\n   - See [docs here](https://next.gatsbyjs.org/docs/) if you need help\n2. `npm install` - install the required dependencies\n3. `npm run dev` - start the development server\n4. Open http://localhost:8000 in your browser\n\n5. <a href=\"/CONTRIBUTING.md\">Contribute</a>\n\n<br>\n\n8. Stage your changes.\n\n```yml\ngit add .\n```\n\n9. Commit your changes.\n\n```yml\ngit commit -m \"<your_commit_message>\"\n```\n\n10. Push your local commits to the remote repo.\n\n```yml\ngit push -u origin <your_branch_name>\n```\n\n11. Create a <a href=\"https://docs.github.com/en/github/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request\" title=\"Pull Request\">Pull-Request</a> to `main`.\n\n12. Congratulations! 🎉 you've made your contribution to <a href=\"https://github.com/utkarsh1504/DSA-Java\" title=\"DSA-Java\">DSA-Java</a>. ✌️ ❤️ 💥\n\n<h2 id=\"contribute\">Contributing</h2>\n<p>\n   Thank you for your interest in contributing to our Repo! Pull requests are welcome. For fixing typos, please make a PR with your fixes. For other contributions, we suggest you to read our <a href=\"/CONTRIBUTING.md\">contribution guidelines</a> to see how you can contribute to this project. We are happy for every contribution. \n    \n</p>\n\n<h2 id=\"prs\">Issues & Pull Requests</h2>\n\nBefore making pull requests please look at our contributing guidelines. You can start working on the issue which are mentioned in issues section. Just drop a comment before working on the issue. Thank you!\n\n<h2 id=\"license\">License</h2>\n\nThe **code** is this repo is licensed under the Apache 2.0 license. Feel free to use and share it as per the license.\n\n## Thanks to all the contributors ❤️\n\n<a href = \"https://github.com/Utkarsh1504/DSA-Java/graphs/contributors\">\n<img src = \"https://contrib.rocks/image?repo=Utkarsh1504/DSA-Java\"/>\n</a>\n<br>\n\n<div align=\"center\">\n <img src=\"https://forthebadge.com/images/badges/built-with-love.svg\" alt=\"love\" />\n <img src=\"https://forthebadge.com/images/badges/thats-how-they-get-you.svg\" alt=\"how\">\n</div>\n"
  },
  {
    "path": "csv.js",
    "content": "const fs = require(\"fs\").promises;\nconst path = require(\"path\");\nconst fm = require(\"front-matter\");\nconst isUrl = require(\"is-url-superb\");\nconst parseLinks = require(\"parse-markdown-links\");\nconst { sorter } = require(\"./src/util/helpers\");\nconst mdDir = process.env.MARKDOWN_DIR || path.join(__dirname, \"lessons/\");\nconst outputPath =\n  process.env.OUTPUT_CSV_PATH || path.join(__dirname, \"public/lessons.csv\");\nconst linksOutputPath =\n  process.env.LINKS_CSV_PATH || path.join(__dirname, \"public/links.csv\");\n\nasync function createCsv() {\n  console.log(`making the markdown files into a CSV from ${mdDir}`);\n\n  // get paths\n  const allFiles = await fs.readdir(mdDir);\n  const files = allFiles.filter(filePath => filePath.endsWith(\".md\"));\n\n  // read paths, get buffers\n  const buffers = await Promise.all(\n    files.map(filePath => fs.readFile(path.join(mdDir, filePath)))\n  );\n\n  // make buffers strings\n  const contents = buffers.map(content => content.toString());\n\n  // make strings objects\n  let frontmatters = contents.map(fm);\n\n  // find all attribute keys\n  const seenAttributes = new Set();\n  frontmatters.forEach(item => {\n    Object.keys(item.attributes).forEach(attr => seenAttributes.add(attr));\n  });\n  const attributes = Array.from(seenAttributes.values());\n\n  if (attributes.includes(\"order\")) {\n    frontmatters = frontmatters.sort(sorter);\n  }\n\n  // get all data into an array\n  let rows = frontmatters.map(item => {\n    const row = attributes.map(attr =>\n      item.attributes[attr] ? JSON.stringify(item.attributes[attr]) : \"\"\n    );\n    return row;\n  });\n\n  // header row must be first row\n  rows.unshift(attributes);\n\n  // join into CSV string\n  const csv = rows.map(row => row.join(\",\")).join(\"\\n\");\n\n  // write file out\n  await fs.writeFile(outputPath, csv);\n\n  console.log(`Wrote ${rows.length} rows to ${outputPath}`);\n\n  // make links csv\n  let longestLength = 0;\n  let linksArray = frontmatters.map(row => {\n    const links = parseLinks(row.body).filter(isUrl);\n    longestLength = longestLength > links.length ? longestLength : links.length;\n    const newRow = [row.attributes.order, row.attributes.title, ...links];\n    return newRow;\n  });\n\n  if (longestLength) {\n    // add title row\n    linksArray = linksArray.map(array => {\n      const lengthToFill = longestLength + 2 - array.length;\n      return array.concat(Array.from({ length: lengthToFill }).fill(\"\"));\n    });\n\n    linksArray.unshift(\n      [\"order\", \"title\"].concat(\n        Array.from({ length: longestLength }).map((_, index) => `link${index}`)\n      )\n    );\n\n    // join into CSV string\n    const linksCsv = linksArray.map(row => row.join(\",\")).join(\"\\n\");\n\n    // write file out\n    await fs.writeFile(linksOutputPath, linksCsv);\n\n    console.log(`Wrote ${linksArray.length} rows to ${linksOutputPath}`);\n  }\n}\n\ncreateCsv();\n"
  },
  {
    "path": "gatsby-config.js",
    "content": "module.exports = {\n  siteMetadata: {\n    title: \"Data Structures & Algorithms\",\n    subtitle: \"Using Java\",\n    courseImage: \"algorithms.png\", // this also should go in /static\n    twitter: \"https://twitter.com/umishra1504\", // make empty string to omit socials\n    linkedin: \"https://www.linkedin.com/in/umishra-1504\",\n    github: \"https://github.com/utkarsh1504\",\n    description:\n      \"Learn all the data-structures and algorithm using the language Java\",\n    keywords: [\"java\", \"markdown\", \"algorithms\", \"data-structures\"],\n  },\n  pathPrefix: \"/DSA-Java\", // if you're using GitHub Pages, put the name of the repo here with a leading slash\n  plugins: [\n    {\n      resolve: \"gatsby-plugin-react-svg\",\n      options: {\n        rule: {\n          include: /src/,\n        },\n      },\n    },\n    `gatsby-plugin-sharp`,\n    `gatsby-plugin-layout`,\n    {\n      resolve: `gatsby-source-filesystem`,\n      options: {\n        path: `${__dirname}/lessons`,\n        name: \"markdown-pages\",\n      },\n    },\n    `gatsby-plugin-react-helmet`,\n    {\n      resolve: `gatsby-transformer-remark`,\n      options: {\n        plugins: [\n          `gatsby-remark-autolink-headers`,\n          `gatsby-remark-copy-linked-files`,\n          `gatsby-remark-prismjs`,\n          {\n            resolve: `gatsby-remark-images`,\n            options: {\n              maxWidth: 800,\n              linkImagesToOriginal: true,\n              sizeByPixelDensity: false,\n            },\n          },\n        ],\n      },\n    },\n  ],\n};\n"
  },
  {
    "path": "gatsby-node.js",
    "content": "const path = require(\"path\");\n\nexports.createPages = ({ actions, graphql }) => {\n  const { createPage } = actions;\n\n  const lessonTemplate = path.resolve(`src/templates/lessonTemplate.js`);\n\n  return graphql(`\n    {\n      allMarkdownRemark(\n        sort: { order: DESC, fields: [frontmatter___order] }\n        limit: 1000\n      ) {\n        edges {\n          node {\n            excerpt(pruneLength: 250)\n            html\n            id\n            frontmatter {\n              order\n              path\n              title\n            }\n          }\n        }\n      }\n    }\n  `).then(result => {\n    if (result.errors) {\n      return Promise.reject(result.errors);\n    }\n\n    result.data.allMarkdownRemark.edges.forEach(({ node }) => {\n      createPage({\n        path: node.frontmatter.path,\n        component: lessonTemplate\n      });\n    });\n  });\n};\n"
  },
  {
    "path": "lessons/arraylist.md",
    "content": "---\npath: \"/arraylist\"\ntitle: \"ArrayList In Java\"\norder: \"4B\"\nsection: \"Arrays\"\ndescription: \"learn arrays\"\n---\n\nThe ArrayList class is in implementation of the list interface that allow us to create resizable array. In simple term we can say that ArrayList in java is dynamic array for storing the elements. It is just like the vector in c++.\n\n\n## Creating An ArrayList\n\n```java\n ArrayList<type>arraylist = new ArrayList<> ; \n //here type define any type of ArrayList. \nExample:\n   ArrayList<Integer> arrlist = new ArrayList<Integer>(n);\n\n```\n\n## Code Snippet to demonstrate the working of ArrayList in Java\n```java\nimport java.io.*;\nimport java.util.*;\n\nclass ArrayListExample {\n\tpublic static void main(String[] args)\n\t{\n\t\t//create array\n\t\tArrayList<Integer> arr = new ArrayList<Integer>(n);\n\n\t\tarr.add(1);\n\t\tarr.add(2);\n\t\tarr.add(3);\n\t\tarr.add(4);\n        System.out.println(\"List: \" + arr );\n\t}\n}\n\n```\n\n## Output\n```java\nList : [1, 2, 3, 4] \n```\n \n## Methods OF ArrayList :\nSome Commonly used Methods\n\n  Method       |  Detail\n------------- | -------------\nsize()        | give the size of the ArrayList\nsort()        | to sort the elements in the list\nisEmpty()\t  | Checks if the arraylist is empty.\nindexOf()\t  | to find index of any element.\n\n\n\n## Basic Operation in Java ArrayList :\nThe ArrayList class have some methods to perform different operations on arraylists. Let's see some of most used methods.\n\n- Add elements\n- Access elements\n- Change elements\n- Remove elements\n\n### Add Elements:\n - add() : This is the method to insert any elements at the end of the list.\n```java\nimport java.util.ArrayList;\n\nclass Main {\n  public static void main(String[] args){\n  \n    ArrayList<String> playerName = new ArrayList<>();\n\n    // add() method \n    playerName.add(\"Virat\");\n    playerName.add(\"Dhoni\");\n    playerName.add(\"Sachin\");\n\t//print \n    System.out.println(\"ArrayList: \" + playerName);\n  }\n}\n```\n### Output:\n\n```\nArrayList : [Virat,Dhoni,Sachin]\n```\n\n- get() : This method is used to acess the elements from the list.\n\n```java\nimport java.util.ArrayList;\n\nclass Main {\n  public static void main(String[] args){\n    \n    ArrayList<String> playerName = new ArrayList<>();\n\n   \n    playerName.add(\"Virat\");\n    playerName.add(\"Dhoni\");\n    playerName.add(\"Sachin\");\n    System.out.println(\"ArrayList: \" + playerName);\n\n\t// get() method\n    String name1 = playerName.get(1);\n    System.out.println(name1);\n  }\n}\n\n```\n### Output:\n```\nArrayList : [Virat,Dhoni,Sachin];\nDhoni\n```\n- set(): This method is used to set any elements at any position.\n\n```java\nimport java.util.ArrayList;\n\nclass Main {\n  public static void main(String[] args) {\n    ArrayList<String> playerName = new ArrayList<>();\n\n    // add() method without the index parameter\n    playerName.add(\"Virat\");\n    playerName.add(\"Dhoni\");\n    playerName.add(\"Sachin\");\n    System.out.println(\"ArrayList: \" + playerName);\n\n\n    // change the element of the array list\n    playerName.set(2, \"Rohit\");\n    System.out.println(\"New ArrayList: \" + playerName);\n  }\n}\n```\n### Output:\n```\nArrayList : [Virat,Dhoni,Sachin]\nNew ArrayList : [Virat,Dhoni,Rohit]\n\n```\n- remove() : To remove the elements from the list\n\n```java\nimport java.util.ArrayList;\n\nclass Main {\n  public static void main(String[] args) {\n    ArrayList<String> playerName = new ArrayList<>();\n\n\n    // add() method without the index parameter\n    playerName.add(\"Virat\");\n    playerName.add(\"Dhoni\");\n    playerName.add(\"Sachin\");\n    System.out.println(\"ArrayList: \" + playerName);\n\n    // remove element \n    String name1 = playerName.remove(2);\n\t//print list after removal\n    System.out.println(\"New ArrayList: \" + playerName);\n\t//removed elements\n    System.out.println(\"Removed: \" + name1);\n  }\n}\n```\n### Output:\n```\nArrayList : [Virat,Dhoni,Sachin]\nNew ArrayList : [Virat,Dhoni]\nRemoved: Sachin\n```\n## Some remembering points about ArrayList\n\n- It comes under java.util package.\n- This class maintains insertion order.\n- It allows random access.\n- ArrayList is not Synchronized  \n- To convert ArrayList into an array we use toArray() method.\n- To convert array into an arraylist we use asList() method.\t\n"
  },
  {
    "path": "lessons/arrays.md",
    "content": "---\npath: \"/arrays\"\ntitle: \"Introduction to Arrays\"\norder: \"4A\"\nsection: \"Arrays\"\ndescription: \"arrays\"\nicon: \"map\"\n---\n\nIt was simple when we used to store just a couple of numbers, we just make some variables for that and store respectively. But what if we want to store 50 numbers? Ofcource, we can make 50 variables and store but that would be very childish approach and inappropriate. And now assume we have to 5000 numbers, we can't make just 5000 variables.\n\nTo handle this situation, in almost all programming languages we have a data structure called `Arrays`. \n\n## **What is an Array ?**\nAn array is a data structure used to store a collection of data of the same data type. Normally, an array is a collection of similar type of elements which has contiguous memory location.\n\nJava array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.\n\nArray in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on.\n\n![Array Indicing.png](https://github.com/shoebxsiddiqui/DSA-Java/blob/shoebxsiddiqui-Arrays/lessons/images/Array%20Indicing.png)\n\nUnlike C/C++, we can get the length of the array using the `length` member. In C/C++, we need to use the `sizeof` operator.\n\nIn Java, array is an object of a dynamically generated class. Java array inherits the Object class, and implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.\n\nMoreover, Java provides the feature of anonymous arrays which is not available in C/C++.\n\n```java\ndatatype[] variablename = new datatype[size];\n```\neg, we want to store roll numbers:\n```java\nint[] rollnos = new int[5];\n\n         OR\n\nint[] rollnos = {51, 82, 13, 15, 16};\n```\n`int` represents the type of data, all the elements in the array should be of same data type, here it is int so the elements in the should be of int data type.\n```java\nint[] rollnow; //declaration of arrays\n\n//rollnos get defined in stack\n```\nThere are `two types` of Arrays:\n* Single Dimensional Arrays\n* Multidimentional Arrays\n\nLet's understand these in detail:\n\n## **1.One-Dimensional Arrays**\nThe general form of a one-dimensional array declaration is\n```java\ntype var-name[];\nOR\ntype[] var-name;\n```\nAn array declaration has two components: the type and the name. type declares the element type of the array. The element type determines the data type of each element that comprises the array. Like an array of integers, we can also create an array of other primitive data types like char, float, double, etc. or user-defined data types (objects of a class). Thus, the element type for the array determines what type of data the array will hold\nExample:\n```java\n// both are valid declarations\nint intArray[]; \nor int[] intArray; \n\nbyte[] byteArray;\nshort[] shortsArray;\nboolean[] booleanArray;\nlong[] longArray;\nfloat[] floatArray;\ndouble[] doubleArray;\nchar[] charArray;\n\n// an array of references to objects of\n// the class MyClass (a class created by\n// user)\nMyClass myClassArray[]; \n\nObject[]  ao,        // array of Object\nCollection[] ca;  // array of Collection\n                     // of unknown type\n```\nAlthough the first declaration above establishes the fact that intArray is an array variable, no actual array exists. It merely tells the compiler that this variable (intArray) will hold an array of the integer type. To link intArray with an actual, physical array of integers, you must allocate one using new and assign it to intArray.\n\n### **Instantiating an Array in Java**\nWhen an array is declared, only a reference of array is created. To actually create or give memory to array, you create an array like this:The general form of new as it applies to one-dimensional arrays appears as follows:\n```java\nvar-name = new type [size];\n```\nHere, type specifies the type of data being allocated, size specifies the number of elements in the array, and var-name is the name of array variable that is linked to the array. That is, to use new to allocate an array, you must specify the type and number of elements to allocate.\n\n### **Example:**\n```java\nint intArray[];    //declaring array\nintArray = new int[20];  // allocating memory to array\nOR\n\nint[] intArray = new int[20]; // combining both statements in one\n```\n\n![One Dimensional Array.jpeg](https://github.com/shoebxsiddiqui/DSA-Java/blob/shoebxsiddiqui-Arrays/lessons/images/One%20Dimensional%20Array.jpeg)\n### **Note :**\n1. The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types).Refer Default array values in Java\n2. Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory that will hold the array, using new, and assign it to the array variable. Thus, in Java all arrays are dynamically allocated.\n\n```java\nrollnos = new int[5]; //initialisation\n\n//Actual memory allocation happens here. Here, Object is being created in Heap memory.\n```\n\n```java\nDeclaration of \n  array               Initialisation\n(compile time)          (run-time)\n      |                     |\n ____\\ /_____           ___\\ /____\n|           |          |          |\n int[]   arr     =      new int[5];\n   ^      ^               ^\n  / \\    / \\             / \\\n   |      |               |\n   |      |               |\n   |   ref var            |\n   |                      |\n   |           creating Object in Heap memory\nDataType\n```\nThis above concept is known as `Dynamic memory allocation` which means at runtime OR execution time is allocated.\n### **Array Literal**\nIn a situation, where the size of the array and variables of array are already known, array literals can be used.\n```java\n int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 }; \n // Declaring array literal\n ```\n* The length of this array determines the length of the created array.\n* There is no need to write the new int[] part in the latest versions of Java\n### **Accessing Java Array Elements using for Loop**\nEach element in the array is accessed via its index. The index begins with 0 and ends at (total array size)-1. All the elements of array can be accessed using Java for Loop.\n```java\n// accessing the elements of the specified array\nfor (int i = 0; i < arr.length; i++)\n  System.out.println(\"Element at index \" + i + \n                                \" : \"+ arr[i]);\n\n```\n```java\n// Java program to illustrate creating an array\n// of integers,  puts some values in the array,\n// and prints each value to standard output.\n  \nclass Main \n{\n    public static void main (String[] args) \n    {         \n      // declares an Array of integers.\n      int[] arr;\n          \n      // allocating memory for 5 integers.\n      arr = new int[5];\n          \n      // initialize the first elements of the array\n      arr[0] = 10;\n          \n      // initialize the second elements of the array\n      arr[1] = 20;\n          \n      //so on...\n      arr[2] = 30;\n      arr[3] = 40;\n      arr[4] = 50;\n          \n      // accessing the elements of the specified array\n      for (int i = 0; i < arr.length; i++)\n         System.out.println(\"Element at index \" + i + \n                                      \" : \"+ arr[i]);          \n    }\n}\n```\n### **Output:**\n```\nElement at index 0 : 10\nElement at index 1 : 20\nElement at index 2 : 30\nElement at index 3 : 40\nElement at index 4 : 50\n```\n### **Arrays of Objects**\nAn array of objects is created just like an array of primitive type data items in the following way.\n```java\n Student[] arr = new Student[7]; //student is a user-defined class\n```\nThe Student array `arr` contains seven memory spaces each of the size of student class in which the address of seven Student objects can be stored. The Student objects have to be instantiated using the constructor of the Student class and their references should be assigned to the array elements in the following way.\n```java\nStudent[] arr = new Student[5];\n```\n```java\n// Java program to illustrate creating an array of\n// objects\n  \nclass Student\n{\n    public int roll_no;\n    public String name;\n    Student(int roll_no, String name)\n    {\n        this.roll_no = roll_no;\n        this.name = name;\n    }\n}\n  \n// Elements of the array are objects of a class Student.\npublic class GFG\n{\n    public static void main (String[] args)\n    {\n        // declares an Array of integers.\n        Student[] arr;\n  \n        // allocating memory for 5 objects of type Student.\n        arr = new Student[5];\n  \n        // initialize the first elements of the array\n        arr[0] = new Student(1,\"aman\");\n  \n        // initialize the second elements of the array\n        arr[1] = new Student(2,\"vaibhav\");\n  \n        // so on...\n        arr[2] = new Student(3,\"shikar\");\n        arr[3] = new Student(4,\"dharmesh\");\n        arr[4] = new Student(5,\"mohit\");\n  \n        // accessing the elements of the specified array\n        for (int i = 0; i < arr.length; i++)\n            System.out.println(\"Element at \" + i + \" : \" +\n                        arr[i].roll_no +\" \"+ arr[i].name);\n    }\n}\n```\n### **Output:**\n```\nElement at 0 : 1 aman\nElement at 1 : 2 vaibhav\nElement at 2 : 3 shikar\nElement at 3 : 4 dharmesh\nElement at 4 : 5 mohit\n```\n### **What happens if we try to access element outside the array size?**\n\nJVM throws **ArrayIndexOutOfBoundsException** to indicate that array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of an array.\n\n```java\nclass GFG\n{\n    public static void main (String[] args)\n    {\n        int[] arr = new int[2];\n        arr[0] = 10;\n        arr[1] = 20;\n  \n        for (int i = 0; i <= arr.length; i++)\n            System.out.println(arr[i]);\n    }\n}\n```\n### **Runtime error**\n```\nException in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: 2\n    at GFG.main(File.java:12)\n```\n### **Output:**\n```\n10\n20\n```\n## **2. Multidimensional Arrays**\n\nMultidimensional arrays are arrays of arrays with each element of the array holding the reference of other array. These are also known as Jagged Arrays. A multidimensional array is created by appending one set of square brackets ([]) per dimension. Examples:\n```java\nint[][] intArray = new int[10][20]; //a 2D array or matrix\nint[][][] intArray = new int[10][20][10]; //a 3D array\n```\n\n![Two Dimensional Array.jpeg](https://github.com/shoebxsiddiqui/DSA-Java/blob/shoebxsiddiqui-Arrays/lessons/images/Two%20Dimensional%20Array.jpeg)\n\n```java\nclass multiDimensional\n{\n    public static void main(String args[])\n    {\n        // declaring and initializing 2D array\n        int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };\n  \n        // printing 2D array\n        for (int i=0; i< 3 ; i++)\n        {\n            for (int j=0; j < 3 ; j++)\n                System.out.print(arr[i][j] + \" \");\n  \n            System.out.println();\n        }\n    }\n}\n```\n### **Output:**\n```\n2 7 9 \n3 6 1 \n7 4 2 \n```\n### **Passing Arrays to Methods**\nLike variables, we can also pass arrays to methods.For example, below program pass array to method sum for calculating sum of array’s values.\n\n```java\n// Java program to demonstrate \n// passing of array to method\n  \nclass Test\n{    \n    // Driver method\n    public static void main(String args[]) \n    {\n        int arr[] = {3, 1, 2, 5, 4};\n          \n        // passing array to method m1\n        sum(arr);\n      \n    }\n  \n    public static void sum(int[] arr) \n    {\n        // getting sum of array values\n        int sum = 0;\n          \n        for (int i = 0; i < arr.length; i++)\n            sum+=arr[i];\n          \n        System.out.println(\"sum of array values : \" + sum);\n    }\n}\n```\n### **Output :**\n```\nsum of array values : 15\n```\n### **Returning Arrays from Methods**\n\nAs usual, a method can also return an array. For example, below program returns an array from method m1.\n\n```java\n// Java program to demonstrate \n// return of array from method\n  \nclass Test\n{    \n    // Driver method\n    public static void main(String args[]) \n    {\n        int arr[] = m1();\n          \n        for (int i = 0; i < arr.length; i++)\n            System.out.print(arr[i]+\" \");\n      \n    }\n  \n    public static int[] m1() \n    {\n        // returning  array\n        return new int[]{1,2,3};\n    }\n}\n```\n### **Output:**\n```\n1 2 3\n```\n### **Class Objects for Arrays**\n\nEvery array has an associated Class object, shared with all other arrays with the same component type.\n\n```java\n// Java program to demonstrate \n// Class Objects for Arrays\n  \nclass Test\n{ \n    public static void main(String args[]) \n    {\n        int intArray[] = new int[3];\n        byte byteArray[] = new byte[3];\n        short shortsArray[] = new short[3];\n          \n        // array of Strings\n        String[] strArray = new String[3];\n          \n        System.out.println(intArray.getClass());\n        System.out.println(intArray.getClass().getSuperclass());\n        System.out.println(byteArray.getClass());\n        System.out.println(shortsArray.getClass());\n        System.out.println(strArray.getClass());\n    }\n}\n```\n### **Output:**\n```\nclass [I\nclass java.lang.Object\nclass [B\nclass [S\nclass [Ljava.lang.String;\n```\n### **Explanation :**\n\n1. The string “[I” is the run-time type signature for the class object “array with component type int“.\n2. The only direct superclass of any array type is java.lang.Object.\n3. The string “[B” is the run-time type signature for the class object “array with component type byte“.\n4. The string “[S” is the run-time type signature for the class object “array with component type short“.\n5. The string “[L” is the run-time type signature for the class object “array with component type of a Class”. The Class name is then followed.\n---\n"
  },
  {
    "path": "lessons/assignment.md",
    "content": "---\npath: \"/assignment\"\ntitle: \"Assignments\"\norder: \"24A\"\nsection: \"Assignments & Practise Question\"\ndescription: \"practise some standard question\"\nicon: \"question\"\n---\n\nThis section will consist some leetcode questions and some practise questions.\nAll the solutions will be in [LeetCode](https://github.com/utkarsh1504/leetcode-solutions) repository.\n\n## Leetcode Question\n\nThe following is a list of leetcode questions.\n\n### Arrays -\n\n- [1. Two Sum](https://leetcode.com/problems/two-sum/)\n"
  },
  {
    "path": "lessons/backtrack-maze.md",
    "content": "---\npath: \"/backtrack-maze\"\ntitle: \"Maze Problems\"\norder: \"9E\"\nsection: \"BackTracking In Java\"\ndescription: \"learn about backtracking algorithms\"\n---\n"
  },
  {
    "path": "lessons/backtrack-nknight.md",
    "content": "---\npath: \"/backtrack-nknight\"\ntitle: \"N Knights\"\norder: \"9D\"\nsection: \"BackTracking In Java\"\ndescription: \"learn about backtracking algorithms\"\n---\n"
  },
  {
    "path": "lessons/backtrack-sudoku.md",
    "content": "---\npath: \"/backtrack-sudoku\"\ntitle: \"Sudoku Solver\"\norder: \"9B\"\nsection: \"BackTracking In Java\"\ndescription: \"learn about backtracking algorithms\"\n---\n"
  },
  {
    "path": "lessons/backtracking.md",
    "content": "---\npath: \"/backtracking\"\ntitle: \"Introduction to Backtracking\"\norder: \"9A\"\nsection: \"BackTracking In Java\"\ndescription: \"learn about backtracking algorithms\"\nicon: \"sitemap\"\n---\n"
  },
  {
    "path": "lessons/binarysearch.md",
    "content": "---\npath: \"/binarysearch\"\ntitle: \"Binary Search\"\norder: \"5B\"\nsection: \"Searching & Sorting\"\ndescription: \"learn Searching algorithms\"\n---\n"
  },
  {
    "path": "lessons/bitwise-operator.md",
    "content": "---\npath: \"/bitwise-operator\"\ntitle: \"Complete Bitwise Operators\"\norder: \"10B\"\nsection: \"Maths for DSA\"\ndescription: \"learn maths required in DSA\"\n---\nIn this lesson, we are going to learn about the bit-wise operators, and some Bit-manipulation techniques to get optimized solutions. These concepts are very important from competitive programming as well as interviews point of view. Okay, so let's learn these techniques:\nIn this lesson, we are going to learn about the bit-wise operators, and some Bit-manipulation techniques to get optimized solutions. These concepts are very important from competitive programming as well as interviews point of view. Okay, so let's learn these techniques:\n## Bit Manipulation\n\nBit manipulation is the process of applying logical operations on a sequence of bits, the smallest form of data in a computer, to achieve a required result. Bit manipulation has constant time complexity and process in parallel, meaning it is very efficient on all systems.\n\nMost programming languages will have you work with abstractions, like objects or variables, rather than the bits they represent. However, direct bit manipulation is needed to improve performance and reduce error in certain situations.\n\nBit manipulation requires a strong knowledge of binary and binary conversion.\n\nHere’s a few examples of tasks that require bit manipulation:\n\n * Low-level device control\n * Error detection and correction algorithms\n * Data compression\n * Encryption algorithms\n * Optimization\n\n## Bitwise Manipulation and Coding Interviews\nBit manipulation is also a common topic in coding interviews, especially with FAANG companies. These interviewers expect you to have a basic understanding of bits, fundamental bit operators, and generally understand the thought process behind bit manipulation.\n> Having this knowledge demonstrates that you’re a well-rounded developer who understands both the specific tools and the foundation of computer science.\n\nIf you’re applying for a role that will work with embedded systems or other low-level systems, you’ll encounter more bit questions. In short, the closer your role is to machine level, the more bit manipulation questions you’ll encounter.\n\nThe best way to prepare for bit manipulation questions is to practice using each bitwise operator and brush up on your binary to decimal conversions.\n## Bitwise Operators In Java\nYou are no doubt familiar with the arithmetic operators such as + - * / or %. You are also aware of logical operators such as & or |. Turns out there is another, a slightly less known set of operators, which manipulate numbers on bit level. Internally, every number is stored in a binary format - that is 0 and 1. Bitwise operators are used for performing manipulation of bits of a number. These can be used with any type of integer data types (char, short, int, etc). \n\nThese operators can be performed on integer types -\n\n * byte (8 bit)\n * short (16 bit)\n * int (32 bit)\n * long (64 bit), and even\n * char (16 bit)\n \nNow let's see its type one by one:\n ## 1. Unary bitwise complement [~]\nThis fancy name basically means bit negation. It takes every single bit of the number and flips its value,i.e, ~0 becomes 1 and vice versa. It is the 1's complement of the number. Unary means that it needs just one operand. The operator is `~` and it is just placed before the number:\n```java\na = 5 = 0101 (In Binary)\n\nBitwise Complement Operation of 5\n\n~ 0101\n ________\n  1010  = 10 (In decimal)\n```\n## 2. Bitwise AND [&]\nUnlike bitwise complement operator, other bitwise operators need two operands.\n\nA & B means that all the bits of both numbers are compared one by one and the resulting number is calculated based on values of the bits from numbers A and B. Bitwise AND is similar to logical AND in a sense that it results in 1 only when the two compared bits are both equal to 1. Otherwise, it results in 0.\n\nFor example: 1010 & 1100 would result in 1000 as the first bit from the left is the only one where both operands contain 1.\n```java\na = 5 = 0101 (In Binary)\nb = 7 = 0111 (In Binary)\n\nBitwise AND Operation of 5 and 7\n  0101\n& 0111\n ________\n  0101  = 5 (In decimal)\n```\n## 3. Bitwise OR [ | ]\nBitwise OR results in 1 when at least one of the compared bits is 1 (or both), otherwise it results in 0.\n```java\na = 5 = 0101 (In Binary)\nb = 7 = 0111 (In Binary)\n\nBitwise OR Operation of 5 and 7\n  0101\n| 0111\n ________\n  0111  = 7 (In decimal) \n```\n## 4. Bitwise Exclusive OR (XOR) [^]\nxclusive OR (XOR) results in 1 only if both the compared bits have a different value, otherwise, it results in 0.\n```java\na = 5 = 0101 (In Binary)\nb = 7 = 0111 (In Binary)\n\nBitwise XOR Operation of 5 and 7\n  0101\n^ 0111\n ________\n  0010  = 2 (In decimal) \n```\n|A\t  |B   |A AND B   |A    B   |A XOR B   |\n|-----|----|----------|---------|----------|\n|1\t  |0   |0         |1        |1         |\n|0\t  |1   |0         |1        |1         |\n|1\t  |1   |1         |1        |0         |\n|0    |0   |0         |0        |0         |\n\n```java\n// Java program to illustrate\n// bitwise operators\npublic class operators {\n    public static void main(String[] args)\n    {\n        // Initial values\n        int a = 5;\n        int b = 7;\n \n        // bitwise and\n        // 0101 & 0111=0101 = 5\n        System.out.println(\"a&b = \" + (a & b));\n \n        // bitwise or\n        // 0101 | 0111=0111 = 7\n        System.out.println(\"a|b = \" + (a | b));\n \n        // bitwise xor\n        // 0101 ^ 0111=0010 = 2\n        System.out.println(\"a^b = \" + (a ^ b));\n \n        // bitwise not\n        // ~0101=1010\n        // will give 2's complement of 1010 = -6\n        System.out.println(\"~a = \" + ~a);\n \n        // can also be combined with\n        // assignment operator to provide shorthand\n        // assignment\n        // a=a&b\n        a &= b;\n        System.out.println(\"a= \" + a);\n    }\n}\n```\n### Output:\n```\na&b = 5\na|b = 7\na^b = 2\n~a = -6\na= 5\n```\n## 5. Signed Left Shift [<<]\nSigned Left Shift takes two operands. It takes the bit pattern of the first operand and shifts it to the left by the number of places given by the second operand. For example 5 << 3: What happens in this case - Every bit in the binary representation of the integer 5 is shifted by 3 positions to the left. All the places on the left are padded by zeros. That is: `00000101` becomes `00101000`. \n\nYou can note that the integer result of 5 << 3 is 40. That shows that shifting a number by one is equivalent to multiplying it by 2, or more generally left shifting a number by n positions is equivalent to multiplication by `2^n`. In this case, it is 5*2^3 = 40.\n\n * Even though you can use shifting of byte, short or char, they are promoted to 32-bit integer before the shifting\n * Bit-shift operators never throw an exception\n * The right operand (the number of positions to shift) is reduced to modulo 32. That is 5 <<35 is equivalent to 5 << 3.\n```java\na = 5 = 0000 0101\nb = -10 = 1111 0110\n\na << 1 = 0000 1010 = 10\na << 2 = 0001 0100 = 20 \n\nb << 1 = 1110 1100 = -20\nb << 2 = 1101 1000 = -40 \n```\n## 6. Signed Right Shift [>>]\nSigned right shift moves all the bits by given number of positions to the right. However, it preserves the sign. Positive numbers remain positive and negative ones remain negative. Similar to left shift, the right shift of n positions is equivalent to division by 2^n. Or division by 2^n -1 in case of odd numbers.\n```java\na = 10\na>>1 = 5 \n\nExample 2:\na = -10 \na>>1 = -5\nWe preserve the sign bit.\n```\n## 7. Unsigned Right Shift [>>>]\nUnlike the signed shift, the unsigned one does not take sign bits into consideration, it just shifts all the bits to the right and pads the result with zeros from the left. That means that for negative numbers, the result is always positive. Signed and unsigned right shifts have the same result for positive numbers.\n```java\na = 10\na>>>1 = 5\n\na = -10 \na>>>1 = 2147483643\nDOES NOT preserve the sign bit. \n```\nThis operator shifts the first operand to the specified number of bits to the right. Excess bits shifted off to the right are `discarded`. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is `always non-negative`. Unlike the other bitwise operators, zero-fill right shift returns an unsigned 32-bit integer.\n\nFor non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result. For example, 9 >>> 2 yields 2, the same as 9 >> 2:\n## 8. Unsigned Left Shift [<<<]\nUnlike unsigned Right Shift, there is no “<<<” operator in Java, because the logical (<<) and arithmetic left-shift (<<<) operations are identical. \n```java\n9 (base 10): 00000000000000000000000000001001 (base 2)\n9 >>> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)\n```\nHowever, this is not the case for negative numbers. For example, -9 >>> 2 yields 1073741821, which is different than -9 >> 2 (which yields -3):\n```java\n-9 (base 10): 11111111111111111111111111110111 (base 2)\n-9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)\n```\n\n|Operator  |Example     |Is equivalent to  |\n|----------|------------|------------------|\n|OR=\t      |x OR= 5\t    |x = x OR 5        |\n|^=\t       |x ^= 5\t     |x = x ^ 5         |\n|&=\t       |x &= 5      |x = x & 5         |\n|<<=\t      |x <<= 5\t    |x = x << 5        |\n|>>=\t      |x >>= 5\t    |x = x >> 5        |\n|>>>=\t     |x >>>= 5  \t |x = x >>> 5       |\n\n```java\n// Java program to illustrate\n// shift operators\npublic class operators {\n    public static void main(String[] args)\n    {\n \n        int a = 5;\n        int b = -10;\n \n        // left shift operator\n        // 0000 0101<<2 =0001 0100(20)\n        // similar to 5*(2^2)\n        System.out.println(\"a<<2 = \" + (a << 2));\n \n        // right shift operator\n        // 0000 0101 >> 2 =0000 0001(1)\n        // similar to 5/(2^2)\n        System.out.println(\"b>>2 = \" + (b >> 2));\n \n        // unsigned right shift operator\n        System.out.println(\"b>>>2 = \" + (b >>> 2));\n    }\n}\n```\n### Output:\n```\na<<2 = 20\nb>>2 = -3\nb>>>2 = 1073741821\n```\n## Bitwise Tricks And Some Questions\nNow, let’s look at a few tricks you can do using bitwise operators.\n\nThese are often used as interview questions to check if you’ve reviewed basic bit manipulation and can apply it to day-to-day coding tasks.\n### Q1. Check for EVEN / ODD\nTo check a number is even or odd, we need to look at the number in its binary form first, lets take an eg, 4 ,i.e, `0100`, if we look carefully then we will find out that the 1 present in the number is at `power of 2` position, lets take another example now, 6 ,i.e, `0110`, here both the 1's are at `power of 2` position and now we can conclude that in binary form if the number is at power of 2 position the it is even. Lets check for odd no. now, eg, 5 ,i.e, `0101` here the least significant digit(or `LSD`) is `not` at the `power of 2` position and thus it is odd.\n\nNow, lets look how to solve this,\n\nif we and a number with one then we know we get back that original number, so if we and the last digit with one and if we get 1 then it would be a odd number else it would be even.\n```java\nif (x & 1 ) == 0\n  return true;\nelse\n  return false;\n```\n### Q2. Convert characters to Uppercase/Lowercase\nThis trick tests your knowledge of uppercase and lowercase characters in binary. You can convert any character, `ch`, to the opposite case using `ch ^= 32`.\n\nThis is because the binary representation of lowercase and uppercase letters are nearly identical, with only 1 bit of difference.\n\nUsing the XOR operation lets us toggle that single bit and swap it to the opposite value, therefore making a lowercase character uppercase or vice versa.\n```java\npublic class Test \n{ \n      \n    static int x=32; \n      \n    // tOGGLE cASE = swaps CAPS to lower \n    // case and lower case to CAPS \n    static String toggleCase(char[] a) \n    { \n        for (int i=0; i<a.length; i++) { \n        \n            // Bitwise XOR with 32 \n            a[i]^=32; \n        } \n        return new String(a); \n    } \n      \n    /* Driver program */\n    public static void main(String[] args)  \n    { \n        String str = \"CheRrY\"; \n        System.out.print(\"Toggle case: \"); \n        str = toggleCase(str.toCharArray()); \n        System.out.println(str); \n          \n        System.out.print(\"Original string: \"); \n        str = toggleCase(str.toCharArray()); \n        System.out.println(str);     \n    } \n} \n```\n### Output:\n```\nToggle case: cHErRy\nOriginal string: CheRrY\n```\n### Q3. Find Number of Setbits\n```java\nclass CountSetBit {\n    private static int helper(int n) {\n        int count = 0;\n        while (n > 0) {\n            n &= (n - 1);\n            count++;\n        }\n        return count;\n    }\n \n    public static void main(String[] args) {\n        int number = 125;\n        System.out.println(\"SetBit Count is : \" + helper(number));\n    }\n}\n```\n### Output:\n```\nSetBit Count is : 6\n```\n\nIn this approach, we count only the set bits. So,\n\n * If a number has 2 set bits, then the while loop runs two times.\n * If a number has 4 set bits, then the while loop runs four times.\n### Q4. Single Number\nYou are given an array in which every number appears twice except one number, return that number.\n```java\nclass SingleNumber {\n    private static int singleNumber(int[] nums) {\n        int xor = 0;\n        for (int num : nums) {\n            xor ^= num;\n        }\n        return xor;\n    }\n \n    public static void main(String[] args) {\n        int[] nums = {4, 1, 2, 9, 1, 4, 2};\n        System.out.println(\"Element appearing one time is \" + singleNumber(nums));\n    }\n}\n```\n### Output:\n```\nElement appearing one time is 9\n```\nThis solution relies on the following logic:\n\n * If we take XOR of zero and some bit, it will return that bit: a ^ 0 = a\n * If we take XOR of two same bits, it will return 0: a ^ a = 0\n * For n numbers, the below math can be applied: a ^ b ^ a = (a ^ a) ^ b = 0 ^ b = b\n\nTherefore, we can XOR all bits together to find the unique number.\n### Q5. Get First Set Bit\n```java\nclass FirstSetBitPosition {\n    private static int helper(int n) {\n        if (n == 0) {\n            return 0;\n        }\n \n        int k = 1;\n \n        while (true) {\n            if ((n & (1 << (k - 1))) == 0) {\n                k++;\n            } else {\n                return k;\n            }\n        }\n    }\n \n    public static void main(String[] args) {\n        System.out.println(\"First setbit position for number: 18 is -> \" + helper(18));\n        System.out.println(\"First setbit position for number: 5 is -> \" + helper(5));\n        System.out.println(\"First setbit position for number: 32 is -> \" + helper(32));\n    }\n}\n```\n### Output:\n```\nFirst setbit position for number: 18 is -> 2\nFirst setbit position for number: 5 is -> 1\nFirst setbit position for number: 32 is -> 6\n```\nThe logic of this solution relies on a combination of left shifting and the AND operation.\n\nEssentially, we first check if the rightmost significant bit is the set bet using `bit & 1`. If not, we keep shifting left and checking until we find the bit that makes our AND operation yield 1.\n\nThe number of shifts is tracked by our pointer, k. Once we do find the set bit, we return k as our answer.\n\n---\n"
  },
  {
    "path": "lessons/bmmv-algorithm.md",
    "content": "---\npath: \"/bmmv-algorithm\"\ntitle: \"Boyer-Moore Majority Voting Algorithm\"\norder: \"4D\"\nsection: \"Arrays\"\ndescription: \"arrays\"\nicon: \"map\"\n---\n\nThe Boyer-Moore voting algorithm is used to find the majority element among the given elements that have more than N/2 occurrences. \n\nThis algorithm works on the fact that if an element occurs more than N/2 times, it means that the remaining elements other than this would definitely be less than N/2.\nFor finding the majority element it takes exactly 2 traversals over the given elements, and works in O(N) time complexity and O(1) space complexity.\nIt's also quite simple to implement, though a little trickier to understand how it works.\n\n## Working\n\nThis algorithm processes each element one at a time.\nWe first choose a candidate from the given set of elements. If it is same as the candidate element, increase the votes. Otherwise decrease the votes. If votes become 0, take another new element as the new candidate.\n\n## Pseudo Code\n\n1. Traverse through array and assume first element of array is the majority element.\n2. Take a counter variable to count frequency of majority element.\n3. As you traverse through array, if the current element of the array is same as majority element, increment the counter variable.\n4. If the current element is not same as majority element, decrement the counter variable. This is done so that one vote of the majority element gets nullified.\n5. If counter reaches 0, then change the majority element to current element and set the counter variable to 1.\n6. Now again traverse through the array and find the count of majority element found.\n7. If the counter is greater than half the size of the array, that is the majority element. Print the element.\n8. Else print that there is no majority element.\n\n## Algorithm\n\n```java\nmajorityElement(int[] nums)\nmaj_ele = nums[0], count = 0, i=0\nTraverse through the array from i=0 to i< nums.length using loop \nif count = 0, \n   maj_ele = nums[i], \n   count = 1\nelse if current element == maj_ele\n   count++\nelse \n   count--\nTraverse through the array from start to end using loop\nif count > N/2\n   return maj_ele  \nelse return -1\n```\n\n## Understand through Example\n\n``` nums[ ]:       1, 1, 1, 1, 2, 3, 5 ```\n\n``` count = 0:     1, 2, 3, 4, 3, 2, 1 ``` \n\n``` maj_ele = 1:   1, 1, 1, 1, 1, 1, 1 ```\n\nmaj_ele = 1 after first traversal and count is\n\n``` count:         1, 2, 3, 4, 4, 4, 4 ```\n\nmaj_ele = 1\n\ncount > 7/2 i.e 3\n\nSo majority element is 1.\n\n## Code Implementation\n\n```java\nimport java.io.*;\nclass Main\n{\n// Function to find majority element \npublic static int majorityElement(int nums[])\n{\n\tint count = 0, maj_ele = nums[0];\n\t// Finding majority element\n\tfor (int i = 0; i < nums.length; i++) {\n\tif (count == 0) {\n       maj_ele = nums[i];\n\t\tcount = 1;\n\t}\n\telse {\n\t\tif (nums[i] == maj_ele)\n\t\tcount++;\n\t\telse\n\t\tcount--;\n\t}\n\t}\n\t// Checking if majority element occurs more than N/2 times\n\tfor (int i = 0; i < nums.length; i++) {\n\tif (nums[i] == maj_ele)\n\t\tcount++;\n\t}\n\tif (count > (nums.length / 2))\n\treturn maj_ele;\n\treturn -1;\n}\n// Driver code\npublic static void main(String[] args)\n{\n\tint arr[] = { 1, 1, 1, 1, 2, 3, 5 };\n\tint majority = majorityElement(arr);\n\tSystem.out.println(\" The majority element is \" + majority);\n\t}\n}\n```\n\n### Output\n\nThe majority element is 1\n\n## Complexity Analysis\n\n### Time Complexity\n\nTwo traversal through the array has occured, so the time complexity is linear i.e O(n).\n\n### Space Complexity\n\nNo extra space is required so space complexity is O(1).\n\n## Problems Based on Boyer-Moore Majority Voting Algorithm\n\n- Majority Element : \n  https://leetcode.com/problems/majority-element/solution/\n- Majority Element II : \n  https://leetcode.com/problems/majority-element-ii/\n  \n"
  },
  {
    "path": "lessons/bracktrack-nqueen.md",
    "content": "---\npath: \"/backtrack-nqueen\"\ntitle: \"N Queens\"\norder: \"9C\"\nsection: \"BackTracking In Java\"\ndescription: \"learn about backtracking algorithms\"\n---\n"
  },
  {
    "path": "lessons/bubblesort.md",
    "content": "---\npath: \"/bubblesort\"\ntitle: \"Bubble Sort\"\norder: \"5C\"\nsection: \"Searching & Sorting\"\ndescription: \"learn Searching n sorting algorithms\"\n---\n\n\nSorting is an everyday tool for programmers.We need to sort many things for many reasons.Like sorting to age,price etc.So\nthere are many sorting algorithms  like Merge Sort , Quick Sort, Bubble sort etc. \n## **Stable & Unstable Sorting**\nIf Two elements in  array has same value, After sorting two things can happen. \n1. They  exchange their relative position.\n2. They don't exchange their relative position.\n![Stable Sorting](./images/stableSort.jpeg)\n\nFrom this example we can see that two '26' doesn't replace their relative positions.Hence it is \nstable sorting algorithms. \nMerge Sort ,Bubble Sort, insertion sort are actually stable sorting algorithm.\nOn the other hand,Heap Sort, Quick Sort etc are unstable sorting algorithms.\n\n## **Bubble Sort** \nBubble Sort is the simplest algorithm. This is named Bubble Sort because its element just swap\none by one.\nIt doesn't have any special use in sorting.It is actually used for educational purposes to introduces\nsorting algorithms. I'm actually sorry if I disappointed you. Sort your emotions then. \n\n\n<ul>\nSuppose we have an array of 3 numbers [3,6,2] which should be sorted in incrementing order. We can use Bubble Sort\nAlgorithms to do so. \n<li>\nAt first, we have to take the first element of the array and compare it to the rest of the\nelements.If we get any elements lower than it, we will swap the position.\nComparison 1:  3 > 6 ->NO \n</li>\n\n<li>\nComparison 2:  3 > 2\n->YES swap the positions Then the array will be [2,6,3]\n\n</li>\n<li>\nComparison 3: 6>3 -> YES swap the positions Then the array will be [2,3,6] \n\n</li>\n</ul>\nBoom, We have sorted the array.Now let's try to do this in Java.\n\n## **Bubble Sort Function**\n```java \nvoid bubbleSort(int array[], int length){\n\n    for(int i = 0; i < length-1; i++){\n        for(int j = i+1; j < length-1; j++){\n            //first loop is used to check to the (length-1)th index of the aray\n            //second loop is used to check the following items of the arrays\n            int temp;\n            if(array[i]<array[j]){\n                temp = array[i];\n                array[i]=array[j];\n                array[j]=temp;\n        }\n    }\n }\n\n```\n\n## **Complete Program In Java**\n```java \npublic class Main {\n  static int array[] = {2, 1, 6, 5, 4};\n\n\n    public static void main(String[] args) {\n\n        int length = array.length;\n        System.out.println(\"Unsorted Array\");\n\n        for (int i = 0; i < length; i++) {\n            System.out.println(array[i]);\n        }\n        \n        System.out.println(\"Unsorted Array\");\n        bubbleSort(array, length);\n    }\n\n    public static void bubbleSort(int array[], int length) {\n\n        for (int i = 0; i < length - 1; i++) {\n            for (int j = i + 1; j < length ; j++) {\n                //first loop is used to check to the (length-1)th index of the aray\n                //second loop is used to check the following items of the arrays\n                int temp;\n                if (array[i] > array[j]) {\n                    temp = array[i];\n                    array[i] = array[j];\n                    array[j] = temp;\n                }\n            }\n        }\n        //for printing\n\n        for (int i = 0; i < length; i++) {\n            System.out.println(array[i]);\n        }\n    }\n}\n\n```\n## **Time Complexity**\nNow talk about the time complexity of this algorithm.From the coding algorithm that is clear that we have to use a loop and \na nested loop. So the complexity becomes O(n*n).\n\nNow, let's see the time complexity of bubble sort in the best case, average case, and worst case. We will also see the space complexity of bubble sort.\n\n- Best Case Complexity - This case occurs when no sorting is needed, i.e. the array is already sorted. The best-case time complexity of bubble sort is O(n).\n- Average Case Complexity - It occurs when the array elements are in jumbled order that is not properly ascending and not properly descending. The average case time complexity of bubble sort is O(n^2).\n- Worst Case Complexity - It occurs when the array elements are required to be sorted in reverse order. That means suppose you have to sort the array elements in ascending order, but its elements are in descending order. The worst-case time complexity of bubble sort is O(n^2).\n\n## **Space Complexity**\nHere Space complexity is O(1). We just have to make a temp variable which is updated throughout the loop and doesn't need to\ncreate anything new.\n\n## Bubble short is majorly used where -\n\n- complexity does not matter\n- simple and shortcode is preferred\n\nNow, let's discuss the optimized bubble sort algorithm.\n\n## **Optimized Bubble sort Algorithm**\nIn the bubble sort algorithm, comparisons are made even when the array is already sorted. Because of that, the execution time increases.\n\nTo solve it, we can use an extra variable swapped. It is set to true if swapping requires; otherwise, it is set to false.\n\nIt will be helpful, as suppose after an iteration, if there is no swapping required, the value of variable swapped will be false. It means that the elements are already sorted, and no further iterations are required.\nThis method will reduce the execution time and also optimizes the bubble sort.\n\n## Program for optimized implementation of bubble sort in Java.\n\npublic class Bubble {\n    static void print(int a[]) // function to print array elements\n    {\n        int n = a.length;\n        int i;\n        for (i = 0; i < n; i++) {\n            System.out.print(a[i] + \" \");\n        }\n    }\n\n    static void bubbleSort(int a[]) // function to implement bubble sort\n    {\n        int n = a.length;\n        int i, j, temp;\n        for (i = 0; i < n; i++) {\n            for (j = i + 1; j < n; j++) {\n                if (a[j] < a[i]) {\n                    temp = a[i];\n                    a[i] = a[j];\n                    a[j] = temp;\n                }\n            }\n        }\n    }\n\n    public static void main(String[] args) {\n        int a[] = { 35, 10, 31, 11, 26 };\n        Bubble b1 = new Bubble();\n        System.out.println(\"Before sorting array elements are - \");\n        b1.print(a);\n        b1.bubbleSort(a);\n        System.out.println();\n        System.out.println(\"After sorting array elements are - \");\n        b1.print(a);\n    }\n}\n```\n## Usage:-\n- Due to its simplicity, bubble sort is often used to introduce the concept of a sorting algorithm. \n- In computer graphics it is popular for its capability to detect a very small error (like swap of just two elements) in almost-sorted arrays and fix it with just linear complexity (2n). For example, it is used in a polygon filling algorithm, where bounding lines are sorted by their x coordinate at a specific scan line (a line parallel to x axis) and with incrementing y their order changes (two elements are swapped) only at intersections of two lines"
  },
  {
    "path": "lessons/countsort.md",
    "content": "---\npath: \"/countsort\"\ntitle: \"Count Sort\"\norder: \"5F\"\nsection: \"Searching & Sorting\"\ndescription: \"learn Sorting algorithms\"\n---\n\nCounting sort is a sorting algorithm that sorts the elements of an array by counting the number of occurrences of each unique element in the array. In Counting sort, we maintain an auxiliary array which drastically increases space requirement for the algorithm implementation.\n\nIt works just like hashing, first, we calculate the max value in the input array, the array to be sorted. Then we count the number of occurrences of each array element from 0 to length-1 and assign it into the auxiliary array. This array is used again to retrieve the sorted version of the input array.\n\nIt actually has linear time complexity but we can’t say that it’s the best algorithm because the space complexity is quite high and it is only suitable to use in a scenario where input array element range is close to the size of the array.\n\n## **Pseudo-Code**\n\n1. Iterate the input array and find the maximum value present in it.\n2. Declare a new array of size max+1 with value 0\n3. Count each and every element in the array and increment its value at the corresponding index in the auxiliary array created\n4. Find cumulative sum is the auxiliary array we adding curr and prev frequency\n5. Now the cumulative value actually signifies the actual location of the element in the sorted input array\n6. Start iterating auxiliary array from 0 to max\n7. Put 0 at the corresponding index and reduce the count by 1, which will signify the second position of the element if it exists in the input array\n8. Now transfer array received in the above step in the actual input array\n\n## **Algorithm**\n\n```java\ncountingSort(array, size)\n  max <- find largest element in array\n  initialize count array with all zeros\n  for j <- 0 to size\n    find the total count of each unique element and \n    store the count at jth index in count array\n  for i <- 1 to max\n    find the cumulative sum and store it in count array itself\n  for j <- size down to 1\n    restore the elements to array\n    decrease count of each element restored by 1\n```\n## **Example for better understanding**\n\nConsider the data in the range 0 to 9.\n\n  Input data: 1, 4, 1, 2, 7, 5, 2\n\n  1. Take a count array to store the count of each unique object.\n    \n    Index:     0  1  2  3  4  5  6  7  8  9\n    Count:     0  2  2  0  1  1  0  1  0  0\n\n  2. Modify the count array such that each element at each index \n  stores the sum of previous counts. \n    \n    Index:     0  1  2  3  4  5  6  7  8  9\n    Count:     0  2  4  4  5  6  6  7  7  7\n\nThe modified count array indicates the position of each object in \nthe output sequence.\n\n   3. Rotate the array clockwise for one time.\n    \n    Index:     0 1 2 3 4 5 6 7 8 9\n    Count:     0 0 2 4 4 5 6 6 7 7\n\n   4. Output each object from the input sequence followed by \n      increasing its count by 1.\n    \nProcess the input data: 1, 4, 1, 2, 7, 5, 2. Position of 1 is 0.\n\n  Put data 1 at index 0 in output. Increase count by 1 to place \n  next data 1 at an index 1 greater than this index.\n\n\n## **Code Implementation**\n\n```java\n// Counting sort in Java\n\nimport java.util.*;\n\nclass Solution {\n\n\tstatic void countSort(int[] arr)\n\t{\n\t\tint max = Arrays.stream(arr).max().getAsInt();\n\t\tint min = Arrays.stream(arr).min().getAsInt();\n\t\tint range = max - min + 1;\n\t\tint count[] = new int[range];\n\t\tint output[] = new int[arr.length];\n\t\tfor (int i = 0; i < arr.length; i++) {\n\t\t\tcount[arr[i] - min]++;\n\t\t}\n\n\t\tfor (int i = 1; i < count.length; i++) {\n\t\t\tcount[i] += count[i - 1];\n\t\t}\n\n\t\tfor (int i = arr.length - 1; i >= 0; i--) {\n\t\t\toutput[count[arr[i] - min] - 1] = arr[i];\n\t\t\tcount[arr[i] - min]--;\n\t\t}\n\n\t\tfor (int i = 0; i < arr.length; i++) {\n\t\t\tarr[i] = output[i];\n\t\t}\n\t}\n\n\tstatic void printArray(int[] arr)\n\t{\n\t\tfor (int i = 0; i < arr.length; i++) {\n\t\t\tSystem.out.print(arr[i] + \" \");\n\t\t}\n\t\tSystem.out.println(\"\");\n\t}\n\n\t// Driver code\n\tpublic static void main(String[] args)\n\t{\n\t\tint[] arr = { -5, -10, 0, -3, 8, 5, -1, 10 };\n\t\tcountSort(arr);\n\t\tprintArray(arr);\n\t}\n}\n\n```\n### **Output**\n\n    -10 -5 -3 -1 0 5 8 10\n\n## **Limitations of Count Sort**\n\n1. It is effective when range is not greater than number of object.\n2. It is not comparison based complexity.\n3. It is also used as sub-algorithm for different algorithm.\n4. It uses partial hashing technique to count the occurrence.\n\n## **Complexity Analysis**\n\n### Time Complexity\n\t\t\t\t\t \n    Best : O(n+k)\n\t\t\t\n    Worst : O(n+k)\n\t\t\t\n    Average : O(n+k)\n\t\t\t\n    Stability : Yes\n\nIn all cases, the complexity is the same because no matter how the elements are placed in the array, the algorithm goes through n+k times, where k is the range of input. \n\nThere is no comparison between any elements, so it is better than comparison based sorting techniques. But, it is bad if the integers are very large because the array of that size should be made.\n\n### Space Complexity\n\nThe space complexity of Counting Sort is O(max). Larger the range of elements, larger is the space complexity.\n\n## **Problems Based on Count Sort**\n\n1. Shil and Birthday Present : https://www.hackerearth.com/problem/algorithm/shil-and-birthday-present/\n2. Finding Pairs : https://www.hackerearth.com/problem/algorithm/finding-pairs-4/\n3. Counting Sort : https://practice.geeksforgeeks.org/problems/counting-sort/1\n"
  },
  {
    "path": "lessons/cyclesort.md",
    "content": "---\npath: \"/cyclesort\"\ntitle: \"Cyclic Sort\"\norder: \"5H\"\nsection: \"Searching & Sorting\"\ndescription: \"learn Sorting algorithms\"\n---\n\nCycle sort is a comparison sorting algorithm which forces array to be factored into the number of cycles where each of them can be rotated to produce a sorted array. It is theoretically optimal in the sense that it reduces the number of writes to the original array.\n\nIt is an in-place and unstable sorting algorithm.\n\nIt is optimal in terms of number of memory writes. It minimizes the number of memory writes to sort. Each value is either written zero times, if it’s already in its correct position, or written one time to its correct position.\n\n## Algorithm\n\nConsider an array of `n` distinct elements. An element `a` is given, index of `a` can be calculated by counting the number of elements that are smaller than `a`.\n\n1.  If the element is found to be at its correct position, simply leave it as it is.\n2.  Otherwise, find the correct position of `a` by counting the total number of elements that are less than `a` . where it must be present in the sorted array. The other element `b` which is replaced is to be moved to its correct position. This process continues until we got an element at the original position of `a`.\n\n## Code Implementation\n\n```java\n//Java program for implementation of Cyclic Sort\nimport java.util.Arrays;\n\npublic class CyclicSort {\n    public static void main(String[] args) {\n        int[] arr = {5, 4, 3, 2, 1};\n        sort(arr);\n        System.out.println(Arrays.toString(arr));\n    }\n\n\n     //Function to sort array using Cyclic sort\n   public static void sort(int[] arr) {\n        int i = 0;\n        while (i < arr.length) {\n            int correct = arr[i] - 1;\n            if (arr[i] != arr[correct]) {\n                swap(arr, i , correct);\n            } else {\n                i++;\n            }\n        }\n    }\n   //Function to swap two elements\n   public static void swap(int[] arr, int first, int second) {\n        int temp = arr[first];\n        arr[first] = arr[second];\n        arr[second] = temp;\n    }\n\n}\n```\n\n### Explanation of the example arr [] = {5, 4, 3, 2, 1}\n\nStep 1: Count the number of elements less than 5, there are 4 elements less than 5 . move `5` to 5th place in the array ( Index = 4 ).\n\nStep 2: So, 5 will take the position of 1 and then count the number of elements less than 1, there are no elements less than 1 .\nmove `1` to 1st place in the array ( Index = 0 ).\n\nStep 3: The original position of 5 is acquired and one cycle is completed\n\nStep 5: Repeat same for all elements.\n\n## Complexity analysis\n\nThe time complexity of the cyclic sort is **O(n)**. The while loop, in the worst case, can iterate a maximum of `2n-1` times. As you can see, we are not incrementing the index `i` when swapping the numbers, this will result in more than `n` iterations of the loop, but in the worst-case scenario, the while loop will swap a total of `n-1` numbers and once a number is at its correct index, we will move on to the next number by incrementing `i`. So overall, our algorithm will take **O(n) + O(n-1)** or we can say **O(2n-1)** which is asymptotically equivalent to **O(n)**.\n"
  },
  {
    "path": "lessons/dataTypes.md",
    "content": "---\npath: \"/dataTypes\"\ntitle: \"Learn Data Types\"\norder: \"3A\"\nsection: \"Learn Java\"\ndescription: \"Learn java\"\nicon: \"coffee\"\n---\n\nSo before knowing what are data types. First let's know what are variable and Constants.\n\n## Variable\n\nSimply, Variable are placeholder for some data values. when we are creating a variable we are just\nreserving some memory\nlocations or reserving some space in memory to store values. In C++, there are different types of variables,eg:\n\n- **int** stores integers such as 7 or -3.\n- **float** - stores decimal numbers, such as 7.33 or -3.77.\n  etc.\n\n## Constant\n\nAs its name suggest **constant**- which does not change, they remain fixed. Basically these are fixed values which\ndo not change and it must have to be initialized at the time of creation, we can not assign any new values to\nit later. That's why these are called **literals**, cuz it can not be modified.\n\n## Data Types\n\nData types are important because each programming language needs different types of data like integers and\nstrings, and these data are stored as that data type. Data types are used to define a variable before to use in a\nprogram, its a constrains that a expression, such as variable or a function, might take.\nIn Java, whenever a variable is defined, the compiler(which compiles source code written in a high-level language(Java)\ninto a set of machine-language that can be understood by a digital computer's CPU) allocates some memory for that\nvariable based on their data-type. It has some types:\n\n![data-types](./images/dataTypes.png)\n\nThere are two types of data types in Java:\n\n1. **Primitive data types**: The primitive data types include boolean, char, byte, short, int, long, float and double. These are pre defined or they are the most basic structure for building more sophisicated data types.they always have a value.\n\n2. **Non-primitive data types**: The non-primitive data types or reference data types include Classes, Objects, Interfaces, Strings, and Arrays. They have null as default value.\n\nIn Java, all variables must be declared first before they can be used.\n\n# Primitive Data-Type \n\nThese are the building blocks of data manipulation. In Java, these are the most basic data types. \n\nThese are of `8 types`:\n\n|Data Types   |Default Value    |Default Size   |\n|-------------|-----------------|---------------|\n|boolean      |false            |1 bit          |\n|char         |'\\u0000'         |2 byte         |\n|byte         |0                |1 byte         |\n|short        |0                |2 byte         |\n|int          |0                |4 byte         |\n|long         |0L               |8 byte         |\n|float        |0.0f             |4 byte         |\n|double       |0.0d             |8 byte         |\n\n1. **Boolean Data Type** : Variables declared with boolean data type can store only true/false. These are used as flag which checks for a particular conditions. Its size is only 1 bit.\n```java\nboolean a = false;\n```\n2. **Byte Data Type** : It is 8-bit signed 2's complement integer. Its value-range lies between -128 to 127 (inclusive). Its default value is 0. The byte data type is used to save memory in large arrays where the memory savings is most required. It saves space because a byte is 4 times smaller than an integer. It can also be used in place of \"int\" data type.\n```java\nbyte a = 10;\nbyte b = -20;\n``` \n3. **Short Data Type** : It is a 16-bit signed 2's complement integer. Its value-range lies between -32,768 to 32,767 (inclusive). Its default value is 0. A short data type is 2 times smaller than an integer.\n```java\nshort a = 10000;\nshort b = -5000;  \n```\n4. **Int Data Type** : It is a 32-bit signed 2's complement integer. Its value-range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its default value is 0. It is generally used as a default data type for integral values.\n```java\nint a = 100000; \nint b = -200000;\n```\n5. **Long Data Type** : It is a 64-bit 2's complement integer. Its value-range lies between -9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its default value is 0. The long data type is generally used when the integer that we have to store exceeds the range provided by int data type.\n```java\nlong a = 100000L;\nlong b = -200000L; \n```\n6. **Float Data Type** : It is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It is recommended that we should use float (instead of double) if yweou need to save memory in large arrays of floating point numbers. It should never be used for precise values, such as currency. Its default value is 0.0F.\n```java\nfloat f1 = 234.5f ;\n```\n7. **Double Data Type** : It is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. This is also generally used for decimal values just like float. The double data type also should never be used for precise values, such as currency. Its default value is 0.0d.\n```java\ndouble d1 = 12.3;\n```\n8. **Char Data Type** : It is a single 16-bit Unicode character. Its value-range lies between '\\u0000' (or 0) to '\\uffff' (or 65,535 inclusive). It is used to store characters.\n```java\nchar letterA = 'A';\n``` \n\n# Non-Primitive Data-Type\n\nThese are created by programmers, unlike primitive data types which are already built-in. These are used to store a group of values for eg, Arrays, in arrays we store a group of data, another eg is list. Therefore, these are also known as advanced data types in Java. When we define a variable of non-primitive data types, it references a memory location where data is stored in the heap memory. That's why, a non-primitive data type is also known as reference data type in Java or simply object reference variable.\n\nNon-Primitive data types are created by instantiation, i.e, an object is created. This object reference variable lives on the stack memory and the object to which it points always lives on the heap memory. The stack holds a pointer to the object on the heap.\n\nThis object can have more than one reference variable, and if we make changes on the data of the object through one reference variable the actual object gets changed and this changed objects's data is changed in all the variables that are pointing(or referencing) to this object.\n\nLet's see some of its types:\n\n1. **Class** : Every class is considered as user-defined data type as a user creates a class. In Java programming, a class is basically a user-defined data type that act as a template for creating objects of identical type. It represents the common properties and actions (functions) of an object.\n```java\npublic class GitHub\n { \n   // class body.\n }\n ```\n2. **Object** : An object is any real-world thing that has some properties and actions. In other words, an entity that has state and behavior is known as an object. An Object has three characterstics - State, Behaviour and Identity.\n```java\nPerson p = new Person();\n```\n3. **String** : A String is also a class. It represents a sequence of characters like Shuaib, A123, etc. The simplest way to create a string object is by storing sequence of characters into string type variable.\n```java\nString str = \"India\";\n```\n4. **Arrays** : It is an Object which is used to store multiple data of same data type. It can store Primitive as well as Non-Primitive data in it. \n```java\nint [] numbers;\nStudent [] x; // Student is a name of class.\n```\n5. **Interface** : An interface is declared like a class but the only difference is that it contains only final variables and method declarations. It is a fully abstract class. It is blue print of a class. It is mechanism in Java to achieve abstraction and multiple inheritance. There can only be abstract methods and variables and no method body.\n```java\ninterface printnum{\n    void print();\n}\n```\n"
  },
  {
    "path": "lessons/firstjavaprogram.md",
    "content": "---\npath: \"/firstjavaprogram\"\ntitle: \"First Java Program\"\norder: \"2C\"\nsection: \"Basics\"\ndescription: \"run java\"\n---\n\nCreate a fresh new java class file in the `src/` directory with **.java** extension. Don't worry we'll explain this in detail later and start writing the following code in it.\n\n```java\n    // Create a hello world program\n\n    public class HelloWorld {\n        public static void main(String[] args) {\n            System.out.println(\"Hello World!\");\n        }\n    }\n```\n\nOKay so lots of horrible looking code, but it's not that bad, we'll get it line by line.\n\n- The first line is the class declaration. It tells the compiler what the class is called and what it does (in this case it's a HelloWorld class).\n- The 2nd line is the main method. This is where the program starts. `public` is the access modifier, `static` is the modifier, `void` is the return type, `main` is the method name, and `(String[])` is the parameter list. The parameter list is a list of strings, which are the arguments passed to the program. This is basically the terminology.\n- The 3rd line is the `System.out.println` statement. This is a method call. `System` is the class, `out` is the object, `.` is the dot operator, `println` is the method name, and inside the parentheses we pass the string `Hello World!`.\n"
  },
  {
    "path": "lessons/flow-of-recursion.md",
    "content": "---\npath: \"/flow-of-recursion\"\ntitle: \"Flow of Recursion\"\norder: \"8B\"\nsection: \"Recursion\"\ndescription: \"learn Recursion from scratch\"\n---\n"
  },
  {
    "path": "lessons/flowchart.md",
    "content": "---\npath: \"/flowchart\"\ntitle: \"Flowchart & Pseudocode\"\norder: \"2A\"\nsection: \"Basics\"\ndescription: \"this is the description that will show up in social shares\"\nicon: \"code\"\n---\n\nThrough this journey we will be learning problem solving approaches, skills and their associated tools. If we have given any problem what we'll do first?\nwe first understand the problem and its context and then we try to think of the solution and write down the steps of solution and then we try to convert our solution(idea) into the code.\n\nSo for writing down the solution we will use flow chart and pseudocode.\n\n## **Flowchart**\n\n- It is a visual representation of the solution to a given problem.\n- It allows us to see the solution step by step by breaking them into smaller steps.\n\n#### Flowchart Components\n\n- **Start**: The starting point of the flowchart. similarly `End` is the end point where the flowchart ends.\n- **Input/Output**: The input and output of the flowchart.\n- **Process**: The process of the flowchart.\n- **Decision**: The decision of the flowchart.\n- **Arrow**: The arrow that connects the process to the decision.\n\nLets understand the flowchart by looking at the following flowchart.\n[img](#flowchart)\n[img](#flowchart)\n\n## **Decision Making**\n\nDecision making is a process of making a choice based on the available options.\nwe have decision box, it kind of looks like a kite shape.\n\nso lets see an example:\n\n- check whether number is Odd or even\n- Find largest of three numbers\n\n## **Understanding Loops**\n\nSo let suppose we have to print numbers from 1 to n. then how do we do it?\nObivously we will start from 1 and then after priting 1 we have to think the next number of the sequence, so we'll basically add 1 in the previous number and we'll get the next number, this process will keep repeating until we reach n. and when we reach n then we have to check that we don't write the number which comes after the n. Here you will see you are repeating the process and a loop is formed.\n\neg:\n\n- find if a given number is prime or not.\n- find the prime numbers till N.\n\nLet's solve a problem.\n\n```java\n    // find largest of N numbers\n    10, 8, 15, 6, 20\n```\n"
  },
  {
    "path": "lessons/functions.md",
    "content": "---\npath: \"/functions\"\ntitle: \"Function & Scope\"\norder: \"3F\"\nsection: \"Learn Java\"\ndescription: \"Learn how to use functions and scope\"\n---\n\nWhether you a professional programmer or just a beginner it is always better to break your programme into blocks, or functions. It will help you later, first of all in debugging, secondly, it is just better to have an elegant, readable and organized code.\n\nA function is a part of a program that has its own name. This name can be used in the program as a command (this command is called a function call). When a function is called, the commands of which it consists are executed. A function call can return a value (similar to an operation) and therefore can be used in an expression along with operations.\n\nIn java, **Method** is also called as **Behaviour**.\nAnd **Variables** are also called as **States**. \n\n\n### **Syntax**\n\n```java\npublic static int function() \n{\n   //your function Body here//\n}\n```\n\n### **Example**\n\n```java\npublic static void function()\n{\n    System.out.println(\"Hello World\");\n}\n```\nThe main function which calls the above function is as follows:\n\n```java\npublic static void main(String []args)\n{\n    //function() called below to print \"Hello World\"\n    function();\n}\n```\n\nThe **output** is as follows\n```js\nHello World\n```\n\n\n## **Return type  + program examples**\n\nWhenever you define a method in java, you specify a return type i.e. that can be any data type, whether primitive or non-primitive and if you don't want to return a data-type you mark it as void (that means you dont want to return anything from the method).\n\nTo return a something from a method you need to use \"**return**\" keyword followed by the name of the variable or object.\n\nThe below example depicts to return a **Integer(int)** value.\n\n```java\npublic static int function()\n{\n    int count = 0;\n\n    //your code here\n\n    //returning count\n    return count;\n}\n```\n\nMake sure that you return the integer value or else, **Compilation fails**.\n\n\n## **Parameters and Pass-By-Value**\n\n\n## **Scope**\n**Scope** of a variable is the part of the program where the variable is **accessible**. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e.scope of a variable can determined at compile time and independent of function call stack. \nJava programs are organized in the form of classes. Every class is part of some package. Java scope rules can be covered under following categories.\n\n1. **Member Variables** - Scope of member variable is all over the class. You can use it anywhere but inside the class.\n2. **Local Variables** - Scope of Local variable is between the methods not outside the method, if you do so compiler throws an exception.\n3. **Block Variables** - The variables declared inside the block level statements cannot be accessed from outside the block. These blocks includes different types of loops, if else statements, etc. \n\n```java\nclass Scope\n{\n    static int c = 10;\n    //the reason to make c as static is that if we want \n    //to use a variable inside a static method then it \n    //should be static\n\n    public static void main(String []args)\n    {\n        //below both are local variables.\n        int a = 10;\n        int b = 20; \n\n            //Block Statement\n            if(a > b)\n            {\n                //here variable d is block variable\n                //so d cannot be used outside if statement\n                int d = a + b ;\n            }\n\n        //if i try to print value of variable d below \n        //it will throw an error.\n        //System.out.pritnln(d);    \n\n        //but we can print c here because c is a global variable \n        //and its scope is all ove the class.\n        System.out.println(c);\n\n    }// end of main function\n\n}//end of class Scope\n```\n\n\n## **Shadowing**\n\nShadowing in Java is the practice of using variables in overlapping scopes with the **same** **name** where the variable in low-level scope overrides the variable of high-level scope. Here the variable at high-level scope is shadowed by the low-level scope variable.\n\nIn other words we can also say that it will use the global variable untill it finds local variable i.e it will use the local variable when **overlapping** is met.\n\nYou can get it well by refering to the below example\n\n```java\nclass shadow\n{\n\tstatic int x = 20;\n\tpublic static void main(String []args)\n\t{\t\n\t\t//here it preints the global variable\n\t\tSystem.out.println(x);\t\t\n\t\t\n\t\tint x = 40;\n\t\t//here the overlapping is met\n\t\t//so it will print the local variable\n\t\tSystem.out.println(x);\n\t}\n\t\n}\n```\nThe output is as follows:\n```\n20\n40\n```\n\n\n\n## **Overloading**\n\n- In method overloading, we can create methods that have the same name, but the methods differ in type, number and/or sequence of parameters.\n- When an overloaded method is invoked, Java uses the type, number and/or sequence of arguments as its guide to determine which version of the overloaded method to actually call.\n- When java encounters a call to an overloaded method, it simplyexecutes the version of the method whose parameters match the arguments used in the call.\n\n**Rules of Overloading**\n\n- Overloaded methods must change the **arguments** list i.e numbers, datatye or sequence.\n- Overloaded methods can change the **return** type.\n- overloaded methods can change the **access modifier**.\n\nThe below example depicts the concept of method overloading.\n\n```java\nclass Adder\n{\n    static int add(int a,int b)\n    {\n        return a+b;\n    }\n\n    static int add(int a,int b,int c)\n    {\n        return a+b+c;\n    }  \n}  \n\nclass TestOverloading\n{  \n    public static void main(String[] args)\n    {  \n        System.out.println(Adder.add(11,11));  \n        System.out.println(Adder.add(11,11,11));    \n    }\n}  \n```\nThe output is as follows\n```\n22\n33\n```\n\n\n## **Conclusion**\n\nHence after refering the above topics, we can conclude that if you need some code to be executed again again then we must use methods to increase the code reusability and increase the performance of the program.\n\nAnd also seen that how important is, the concept of overloading and the rules for it.\nShadowing is also a great and unique concept where, whenever the variables overlaps then the latest one is considered.\n\n## **Some Examples to practice**\n\n- Write a java program to find the area of different shapes by using the concept of method overloading.\n- Write a suitable java program which depicts the concept of shadowing.\n\n\n\n"
  },
  {
    "path": "lessons/greedy.md",
    "content": "---\npath: \"/greedy\"\ntitle: \"Introduction to Greedy Algorithms\"\norder: \"20A\"\nsection: \"Greedy Algorithms\"\ndescription: \"complete greedy algorithm\"\n---\n"
  },
  {
    "path": "lessons/insertion.md",
    "content": "---\npath: \"/insertion\"\ntitle: \"Insertion Sort\"\norder: \"5E\"\nsection: \"Searching & Sorting\"\ndescription: \"learn Sorting algorithms\"\n---\nInsertion sort is the sorting mechanism where the sorted array is built having one item at a time. The array elements are compared with each other sequentially and then arranged simultaneously in some particular order.\n\n## Explanation\n\nThe first element of the array forms the sorted subarray while the rest create the unsorted subarray from which we choose an element one by one and **insert** the same in the sorted subarray. The same procedure is followed until we reach the end of the array.\n\nIn each iteration, we extend the sorted subarray while shrinking the unsorted subarray. The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list (in the same array).\n\n* If it is the first element, it is already sorted. return 1;\n* Pick next element\n* Compare with all elements in the sorted sub-list\n* Shift all the elements in the sorted sub-list that is greater than the value to be sorted\n* Insert the value\n* Repeat until list is sorted\n\n## Pseudocode\n```pseudocode\nprocedure insertionSort( A : array of items )\n   int holePosition\n   int valueToInsert\n\t\n   for i = 1 to length(A) inclusive do:\n\t\n      /* select value to be inserted */\n      valueToInsert = A[i]\n      holePosition = i\n      \n      /*locate hole position for the element to be inserted */\n\t\t\n      while holePosition > 0 and A[holePosition-1] > valueToInsert do:\n         A[holePosition] = A[holePosition-1]\n         holePosition = holePosition -1\n      end while\n\t\t\n      /* insert the number at hole position */\n      A[holePosition] = valueToInsert\n      \n   end for\n\t\nend procedure\n```\n\n\n\n## Complexity analysis\n\nInsertion sort runs in *O*(*n*) time in its best case and runs in *O*(*n*²) in its worst and average cases.\n\n### Best case\n\nInsertion sort performs two operations: it scans through the list, comparing each pair of elements, and it swaps elements if they are out of order. Each operation contributes to the running time of the algorithm. If the input array is already in sorted order, insertion sort compares *O*(*n*) elements and performs no swaps. Therefore, in the best case, insertion sort runs in O(*n*) time.\n\n### Worst case\n\nThe worst case for insertion sort will occur when the input list is in decreasing order. To insert the last element, we need at most *n*−1 comparisons and at most *n*−1 swaps. To insert the second to last element, we need at most *n*−2 comparisons and at most *n*−2 swaps, and so on. The number of operations needed to perform insertion sort is therefore: 2 × (1+2+⋯+*n* −2+*n* −1) . This is in the order of sum of first n-1 numbers which is quadratic in nature. therefore, in the worst case, insertion sort runs in O(*n*²) time.\n\n\n\n> The average case and the worst case have the same time complexity. Try to think why is this happening.\n\n\n\n## Code Implementation\n\n```java\n\n// Java program for implementation of Insertion Sort\npublic class InsertionSort {\n    public static void insertionSort(int[] input) {\n        for (int i = 1; i < input.length; i++) {\n            int j = i - 1;\n            int temp = input[i];\n            for (; j >= 0 && input[j] > temp; j--) {\n                input[j + 1] = input[j];\n            }\n            input[j + 1] = temp;\n        }\n    }\n\n    public static void main(String[] args) {\n        int[] input = {  1, 5, 4, 2, 3  };\n        insertionSort(input);\n        for (int j : input) {\n            System.out.print(j + \" \");\n        }\n    }\n}\n```\n\n>\n>\n>Explanation of the example  arr [] = {1 , 5 , 4 , 2 , 3 }\n>\n>Step 1 : No element on the left side of 1. so, no change in position.\n>\n>Step 2 : As 1 < 5. so no change in position.\n>\n>Step 3 : As 5 > 4. 4 and 5 will swap. now 1 < 4. so no change in postion.\n>\n>Step 4 : As 5 > 2. 2 and 5 will swap. now 4 > 2 so 2 and 4 will swap. now 1 < 2, so no change in position.\n>\n>Step 5: As  5 > 3. 3 and 5 will swap. now 4 > 3 so 3 and 4 will swap. now 2 < 3, so no change in position. \n\nNow our array is sorted.\n\nyou can visualize this at [hackerearth](https://www.hackerearth.com/practice/algorithms/sorting/insertion-sort/visualize/) \n\n## Advantages\n\n- Simple and easy to understand implementation\n- Efficient for small data\n- If the input list is sorted beforehand (partially) then insertions sort takes `**O(n+d)**` where d is the number of inversions\n- Chosen over bubble sort and selection sort, although all have worst case time complexity as `**O(n^2)**`\n- Maintains relative order of the input data in case of two equal values (stable)\n- It requires only a constant amount `**O(1)**` of additional memory space (in-place Algorithm)\n\n\n\n## Applications\n\n- It could be used in sorting small lists.\n- It could be used in sorting \"almost sorted\" lists.\n- It could be used to sort smaller sub problem in Quick Sort.\n\n\n\n"
  },
  {
    "path": "lessons/intro-binarytree.md",
    "content": "---\npath: \"/intro-binarytree\"\ntitle: \"Intro to Binary Tree\"\norder: \"15A\"\nsection: \"Binary Tree\"\ndescription: \"learn about Binary Tree from scratch\"\nicon: \"tree\"\n---\n"
  },
  {
    "path": "lessons/intro-bst.md",
    "content": "---\npath: \"/intro-bst\"\ntitle: \"Intro to BST\"\norder: \"16A\"\nsection: \"Binary Search Tree\"\ndescription: \"learn about Binary Search Tree from scratch\"\nicon: \"search\"\n---\n### Binary Search Tree\nA Binary Search Tree is a binary tree that additionally satisfies the binary search property.\n\n### Binary Tree Property \nThis property states that the key in each node must be greater than or equal to any key stored in the left sub-tree and less than or equal to any key stored in the right sub-tree.\n\n![BinarySearchTree_diagram](images/BinarySearchTree_diagram.png)\n\n## Operations In BST\n\n### Searching\n1. We begin by examining the root node. If the tree is null , the key we are searching for does not exist in the tree.\n2. If the key equals that of the root If the key is equal that of route the search is successful and we return the node .\n3. If the key is less than that of the root we search the left subtree. Similarly, if the key is greater than that of the root, we search the right subtree.\n4. This process is repeated until the key is found or the remaining subtree is null.\n5. If the search key is not found after a null subtree is reached, then the key is not present in the tree.\n\n### Insertion\nTo insert for a key in the tree , we follow the binary search property and insert accordingly.\n1. Compare the key to be searched with the root key.\n2. If the key is lesser than the roots value, we return the left subtree of the node.\n3. If the key is greater than the roots value, we return the right subtree of node.\n4. This process continued until we hit a leaf node. The new node is inserted to this location as a new node.\n\n### Deletion\nWhen removing a node from a binary search tree it is mandatory to maintain the in-order sequence of the nodes.\nThere are three possible cases to consider:\n1. Deleting a node with no childeren :simply remove the node from the tree \n2. Deleting a node with one child: remove the node and replace it with its child.\n3. Deleting a node with two children: First we find the inorder successor of the node. <br>\nThen the contents of this in-order successor are copied to the node to be deleted.\nFinally, the in-order successor is deleted\n<br>\n\nLet's see the implementation of Binary Search Tree using an example:\n\n```java\n// Java implementation of recursive Binary Search\nclass BinarySearch {\n    // Returns index of x if it is present in arr[l..r],\n    // else return -1\n    int binarySearch(int arr[], int l, int r, int x)\n    {\n        if (r >= l) {\n            int mid = l + (r - l) / 2;\n  \n            // If the element is present at the\n            // middle itself\n            if (arr[mid] == x)\n                return mid;\n  \n            // If element is smaller than mid, then\n            // it can only be present in left subarray\n            if (arr[mid] > x)\n                return binarySearch(arr, l, mid - 1, x);\n  \n            // Else the element can only be present\n            // in right subarray\n            return binarySearch(arr, mid + 1, r, x);\n        }\n  \n        // We reach here when element is not present\n        // in array\n        return -1;\n    }\n  \n    // Driver method to test above\n    public static void main(String args[])\n    {\n        BinarySearch ob = new BinarySearch();\n        int arr[] = { 2, 3, 4, 10, 40 };\n        int n = arr.length;\n        int x = 10;\n        int result = ob.binarySearch(arr, 0, n - 1, x);\n        if (result == -1)\n            System.out.println(\"Element not present\");\n        else\n            System.out.println(\"Element found at index \" + result);\n    }\n}\n```\nOutput : \n```\nElement is present at index 3\n```\n\n## Visualisations \n[BinarySearch Visualisation](https://www.cs.usfca.edu/~galles/visualization/BST.html)\n"
  },
  {
    "path": "lessons/intro-complexity.md",
    "content": "---\npath: \"/intro-complexity\"\ntitle: \"Complexity Analysis\"\norder: \"7A\"\nsection: \"Space & Time Complexity\"\ndescription: \"learn about time and space complexity for various algorithms\"\nicon: \"flask\"\n---\n\nOk so till now we have just learn some algorithm and tried to solve some problems based on them. Now an important question arise while programming is: How efficient is an algorithm or piece of code? How much time and space does it take to run?\n\n## *What is Complexity analysis*\n\nIt's really important to understand the real-world significance of **algorithms and its properties** because using different ideas one can design many algorithms for computing a solution to a given problem. Key important questions in algorithms are :\n\n- How do we design **good** algorithms?\n- How do we know that our algorithm is **efficient**?\n- How to efficiently implement algorithms in a programming language?\n\n> **Interviewer** *often checks your ideas and coding skills by asking you to write a code giving restrictions on its* **time or space complexities.**\n\n## *Why to do Complexity analysis*\n\nWe already know there are tools to measure how fast a program runs. There are programs called *profilers* which measure running time in milliseconds and can help us optimize our code by spotting bottlenecks. While this is a useful tool, it isn't really relevant to algorithm complexity. Algorithm complexity is something designed to compare two algorithms at the idea level — ignoring low-level details such as the implementation programming language, the hardware the algorithm runs on, or the instruction set of the given CPU. We want to compare algorithms in terms of just what they are: Ideas of how something is computed. Counting milliseconds won't help us in that. It's quite possible that a bad algorithm written in a low-level programming language such as [assembly](http://en.wikipedia.org/wiki/Assembly_language) runs much quicker than a good algorithm written in a high-level programming language such as [Python](http://www.python.org/) or [Ruby](http://www.ruby-lang.org/en/).\n\n\n\n### *Memory*\n\nMemory in a computer is just a sequential set of \"buckets\" that can contain numbers, characters, or Boolean values. By using several buckets in a row, we get arrays. By giving names to a set of contiguous buckets, we get a \"structure\". But at its core, a computer memory is a very simple list of numbers. Everything else must be built up upon this.\n\n1. Memory is laid out in sequential order basically from 0 on up (one byte at a time). Each position in memory has a number (called its address!).\n\n2. The compiler (or interpreter) associates your variable names with memory addresses.\n\n3. In some languages like C, you can actually ask the computer for the address of a variable in memory. In C this is done using the ampersand &\n\n   In many languages, the actual address is hidden from you and is of little use to you, as all the access methods \"abstract\" the details of the computer hardware away, allowing the programmer to concentrate on the algorithm, and not the details.\n\n4. Arrays variables simply contain the address of the first element of the array. Arrays are zero based so the address simply becomes the base address plus the index.\n\n5. Structure variables simply contain the address of the first element of the structure, and each \"named\" field of the structure forms an offset from the first bucket. The computer keeps track of this offset so that the programmer can use symbolic names instead of numbers.\n\n6. Memory buckets are 8 bits long (or one byte). A character (char) is one byte. An integer is (usually) four bytes. A float is four bytes. A double is 8 bytes.\n\n\n\n### **Performance**\n\nIt conclude on the basis of time/memory/disk/etc. usage when we run the code. It depends on the machine, compiler, OS, etc as well as the code itself.\n\n### **Complexity**\n\nWe are typically interested in the execution time of large instances of a problem, e.g., when 𝑛 → ∞, (asymptotic complexity). _for this we introduce the big O notation._\n\n**Big O notation** is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity. big O notation is used to classify algorithms according to how their run time or space requirements grow as the input size grows. In analytic number theory, big O notation is often used to express a bound on the difference between an arithmetical function and a better understood approximation. Big O notation characterizes functions according to their growth rates: different functions with the same growth rate may be represented using the same O notation. The letter O is used because the growth rate of a function is also referred to as the **order of the function**. A description of a function in terms of big O notation usually only provides an upper bound on the growth rate of the function.\n\n\n| Function | common name  |\n| :------: | :----------: |\n|    N!    |  factorial   |\n|   2^n    | exponential  |\n|    n³    |    cubic     |\n|    n²    |  quadratic   |\n| n log n  | quasi-linear |\n|    n     |    linear    |\n|  log n   | logarithmic  |\n|    1     |   constant   |\n\n\n\n## Different types of complexity\n\nThere are several different types of complexities , we will only be looking into the more popular and the most commonly used ones.\n\n### Constant Time Complexity: O(1)\n\nComplexity **O(1)** is the best, it’s not always achievable, but if it is, then your code is *independent* of the input size.\n\nOther operations that have complexity **O(1)** are the print function, simple arithmetic — addition, subtraction, and multiplication and division in the case of integers.\n\n### Linear Time Complexity: O(n)\n\nWhen time complexity grows in direct proportion to the size of the input, you are facing Linear Time Complexity, or O(n). Algorithms with this time complexity will process the input (n) in “n” number of operations. This means that as the input grows, the algorithm takes proportionally longer to complete.\n\nLinear running time algorithms are very common, and they relate to the fact that the algorithm visits every element from the input.\n\n### Logarithmic Time Complexity: O(log n)\n\nAlgorithms with this complexity make computation amazingly fast. An algorithm is said to run in logarithmic time if its time execution is proportional to the logarithm of the input size. This means that instead of increasing the time it takes to perform each subsequent step, the time is decreased at a magnitude that is inversely proportional to the input “n”.\n\n### Quadratic Time Complexity: O(n²)\n\nIn this type of algorithms, the time it takes to run grows directly proportional to the square of the size of the input (like linear, but squared).\n\nNested **For Loops** run on quadratic time, because you’re running a linear operation within another linear operation, or *n* which equals *n².*\n\nIf you face these types of algorithms, you’ll either need a lot of resources and time, or you’ll need to come up with a better algorithm.\n\n###  O(n log(n))\n\nIf we have a code or an algorithm with complexity **O(log(n))** that gets repeated multiple times, then it becomes **O(n log(n))**. Famous examples of this are __merge sort and quicksort__.\n\n\n\n# Big O rules\n\nGoing through the above examples, you might have figured out some rules for calculating Big O, but let’s sum them up:\n\n1. Reading, writing an item in a list or a dictionary has **O(1)**.\n2. Going through an iterable is **O(n)**.\n3. Nested loops lead to **O(n²)** complexity.\n4. Any divide and concur approach or loops handling binary numbers have **O(n log(n))** complexity.\n5. We sum up the complexity of sequential loops and multiply the complexity of nested loops.\n"
  },
  {
    "path": "lessons/intro-dp.md",
    "content": "---\npath: \"/intro-dp\"\ntitle: \"Introduction to DP\"\norder: \"19A\"\nsection: \"Dynamic Programming\"\ndescription: \"learn about Dynamic Programming\"\nicon: \"sitemap\"\n---\n"
  },
  {
    "path": "lessons/intro-ds.md",
    "content": "---\npath: \"/intro-ds\"\ntitle: \"Introduction to Data Structures\"\norder: \"12A\"\nsection: \"Linked Lists\"\ndescription: \"complete intro to data structures\"\nicon: \"link\"\n---\n"
  },
  {
    "path": "lessons/intro-graph.md",
    "content": "---\npath: \"/intro-graphs\"\ntitle: \"Introduction to Graphs\"\norder: \"22A\"\nsection: \"Graphs\"\ndescription: \"learn about graph data-structure from scratch\"\nicon: \"map-signs\"\n---\n"
  },
  {
    "path": "lessons/intro-hashmap.md",
    "content": "---\npath: \"/intro-hashmap\"\ntitle: \"Introduction to Hashmap\"\norder: \"18A\"\nsection: \"Hashmap\"\ndescription: \"learn about hashmap from scratch\"\nicon: \"book\"\n---\n"
  },
  {
    "path": "lessons/intro-heap.md",
    "content": "---\npath: \"/intro-heap\"\ntitle: \"Introduction to Heaps\"\norder: \"17A\"\nsection: \"Heaps\"\ndescription: \"complete introduction to heaps\"\nicon: \"object-ungroup\"\n---\n"
  },
  {
    "path": "lessons/intro-linkedlist.md",
    "content": "---\npath: \"/intro-linkedlist\"\ntitle: \"Introduction to Linked List\"\norder: \"12B\"\nsection: \"Linked Lists\"\ndescription: \"learn Linked list from scratch\"\n---\n"
  },
  {
    "path": "lessons/intro-maths.md",
    "content": "---\npath: \"/intro-maths\"\ntitle: \"Introduction to Maths in DSA\"\norder: \"10A\"\nsection: \"Maths for DSA\"\ndescription: \"learn maths required in DSA\"\nicon: \"plus\"\n---\n"
  },
  {
    "path": "lessons/intro-oop.md",
    "content": "---\npath: \"/intro-oop\"\ntitle: \"Introduction\"\norder: \"11A\"\nsection: \"Object Oriented Programming\"\ndescription: \"complete introduction to object oriented programming\"\nicon: \"object-ungroup\"\n---\n\nHaving learned the material in the preceding chapters, you are able to solve many programming problems using selections, loops, methods, and arrays. However, these Java features\nare not sufficient for developing graphical user interfaces and large-scale software systems.\nSuppose you want to develop a graphical user interface (GUI, pronounced goo-ee) for Calculator. How would you program it?\n\nOkay so, In this lesson we'll be talking about OOP(Object Oriented Porgramming) concepts.Object-Oriented Programming paradigm is a popular programming paradigm which is used to write to good quality code and this is the paradigm which is the default choice everywhere whether you want to do web or android development or any sort of development from now onwards, OOP concepts are the concepts that will be most useful to you. So before we go in detail of the OOPs, let's try to understand why OOP is the most popular choice.\n\nBasically Object-Oriented Programming is actually inspired by the real life problems that you're trying to solve. The intent behind OOP is whatever your problem is, your code should be looks similar to the problem that you are trying to solve. When you are solving a problem then you would find that your code also revolves around **Objects**. An **object** represents an entity in the real world that can be distinctly identified. For example, a student, a\ndesk, a circle, and button can all be viewed as objects. An object has a unique\nidentity, state, and behavior. So In OOP, what we do is, we identify which are objects to which our problem will revolves around and then we try writing code assimilating the problem that we're trying to solve.\n\nLet's understand this by an example.\n<b>Suppose you have given a project from college which is college management system, now In this project, what all do you think will be key entities around which this system will revolve.\nI think the key entities will be teachers, students, departments, batches, courses, etc will be objects for us to work with. Now we have Objects, then obiviously they'll have proeperties associated with themselves.</b>\n\nNow as you move forward you'll realise that OOP is revolving around two major terms which is basically <b>Objects</b> and <b>Classes</b>. So what exactly is an object, let's we have some students S1, S2, S3, S4, so each student is our object, now each student will have certain set properties associated and functionality with them such as name, uid, phone number, address, email etc. and functionality let's say isEligibleForScholarhip, getBatch, getDepartment, etc.\nNow S1, S2, S3, S4 all are have these properties, so when you're creating an object you would not want to write that list of properties everytime, instead you would want that I just create an object and I can expect that object will have all the set of properties and functionality, So this is where <b>Classes</b> come in.\n\n**Class** is basically a template of properties of an object. So, if you have a student S1, S2, S3, S4, then you can create a class called Student and then create an object of that class called S1, S2, S3, S4. Now, S1, S2, S3, S4 will have all the properties and functionality of the Student class.\n\n<b>\nNow a class will only indicate the list of properties that a student should have not values. Actual values of these properties will be the once that you will specify once you create an object of that class. For example, S1 and S2 will both have a property name, but their values(names may be different) will be different. So this is the difference b/w classes and objects.\nObjects are actually is an instance of a class\n</b>\nNow I hope you've got the idea of how OOP works, so let's move further.\n"
  },
  {
    "path": "lessons/intro-priorityqueues.md",
    "content": "---\npath: \"/intro-priorityqueues\"\ntitle: \"Introduction to Priority Queues\"\norder: \"21A\"\nsection: \"Priority Queues\"\ndescription: \"learn about Priority Queues from scratch\"\nicon: \"braille\"\n---\n"
  },
  {
    "path": "lessons/intro-programming.md",
    "content": "---\npath: \"/intro-programming\"\ntitle: \"Intro to Programming\"\norder: \"1B\"\nsection: \"Introduction\"\ndescription: \"learn Java\"\n---\n\nThere is a question comes in everyone's mind before getting started with coding or ds algo or Competitive Programming(**cp**) - Which is the best programming language to get started with? And truly it's quite important to figure out the language which is most suitable for you.\nSo we're just going to recommend you two languages-\n\n1. C++\n2. Java\n\nNow, If you are interested in doing some development and also wanted to learn ds algo and _cp_, definitely choose `Java`.\n\nBut if your main focus is _cp_ and wanted to do game development or likes to work on Operating System then choose `C++`.\n\n## **C++**\n\nC++ is a programming language which can be used to develop games,\noperating systems, Graphical User Interfaces(GUI) etc. It supports procedural programming object-oriented programming (**OOPs**), functional programming(**FP**), etc. C++, developed by `Bjarne Stroustrup`, is a relatively faster programming language in comparison with other and That's why it is most recommended and widely used in Competitive coding rounds. It consists some rich libraries like Standard Template Library(**STL**) which includes template classes that has various data structures such as stacks,lists,trees,graphs, arrays, etc\n\n## **Java**\n\n**JAVA** another most recommended programming language for Competitive Programming. It is developed by Sun Microsystems and is used to build large class applications. Java works great within corporate environments, although it can be used for small tasks, it's less suited for that. Many popular IDE's and tools are are written and developed in Java such Eclipse, IntelliJ IDEA and NetBeans IDE.\nIn this course I will pick Java as a programming language for learning data structures and algorithms. It has various features like OOPs, Functional Programming, Generics, etc. It is relatively more stable than other and it also has multi-threading support. Java is very efficient at memory management and it is very fast.\n\n#### **Java Plateform Independent**\n\nAs you may have hear from others that Java is a platform independent language, so what does it mean basically lets understand.\n\nlets we have,\n\n```java\n      code           machine\n    c = a + b  -->   Binary\n (human-readable)   (base-2)\n                       /\\\n                      0  1\n```\n\nBinary is base-2 number system. which is basically 0 and 1.\nWe write the code which is by the way human readable, computer can not understand it that's why we need to convert it into binary. so somehow we need to bridge this gap. Now it's like there are two people talking in different languages and they wanted to communicate with each other. Similarly here at the one end we have a high-level language like **Java** & **C++** and on the other hand a hardware which understand only binary therefore we need a sort of imediator to bridge this gap. This imediator comes into the picture is called **Compiler**. so this conversion(Human-readable to binary) done by this compiler okay. Now Let's talk about both the languages C++ and Java and how the compiler works.\n\n```cpp\n        code  (.cpp)\n          ↓\n       compile\n          ↓   (.exe or a.out)\n       machine\n```\n\nIn case of C++, first our code which is in **.cpp** file is compiled and then a new **.exe or a.out** file generated by compiler. And that .exe or a.out file is run on the machine or Plateform. Now the binary outcome(compiled outcome) is different on different plateforms means if we are using Windows, then the compiled outcome is an .exe file. If we are using Linux or Mac, then the compiled outcome is an a.out file.\n\nNow this brings us to a problem which is if we want to share the compiled ooutcome with someone, we cannot directly do that because that compiled code might not work on the other machinne or plateform. now the question arises how do we share our code with someone? well we can share the source-code (.cpp) file but generally we don't do that cuz we don't want to share our private code. This is a problem with **C++**.\nNow **Java** is different from **C++** in that this problem is something delt in java and you don't have to worry about it.\n\n```java\n        code  (.java)\n          ↓\n   ←-------compile-----------→\n   |         |   (.class)    |\n   |         |               |\n   |         |               |\n   ↓         ↓               ↓\nPlateform1 Plateform2  Plateform3\n```\n\nIn case of Java the compiler compiles the .java file and generates a .class file. So the compiled outcome is the same on all plateforms. we can share that .class file with anyone without sharing our actual source-code.\n\nNow how is that happen in java? Does that mean that all plateforms understand the same binary outcome? No all plateforms have their own binary outcome and it's different. so how is that happen? okay so **JVM(Java Virtual Machine)** comes into the action. JVM is another layer which is there in between compiler and plateform. JVM is a virtual machine which is a program which runs on the plateform and it's responsible for converting the human-readable outcome into the binary outcome. So different plateforms have different JVM's and it converts .class file into the relevant binary outcome that need to run on particular hardware.\n\nNow I think you got the point. This is why Java is called **Plateform Independent**. Now lets move further.\n"
  },
  {
    "path": "lessons/intro-recursion.md",
    "content": "---\npath: \"/intro-recursion\"\ntitle: \"Intro to Recursion\"\norder: \"8A\"\nsection: \"Recursion\"\ndescription: \"learn Recursion from scratch\"\nicon: \"redo\"\n---\n\nRecursion is a technique that leads to elegant solutions to problems that are difficult to solve using simple iteration(loops). In some cases, it enables\nyou to develop a natural, straightforward, simple solution to an otherwise difficult problem.\n\n> Recursion in Computer Science is a method where the solution to a problem depends on the solution to smaller instances of the same problem.\n\nThis lesson introduces the concepts and techniques of recursive programming and illustrates with examples of how to **“think recursively”**. Let's understand this by a simple example:\n\n```java\n    Calculate factorial of a number by using recursion\n```\n\nNow, How do you find `n!` of a given number?\n\n- To find `1!` is easy, because you know that `0!` is 1, and 1! is 1 × 0!.\n- Assuming that you know `(n - 1)!`, you can obtain n! immediately by using `n × (n - 1)!`. Thus, the problem of computing n! is reduced to computing (n - 1)!. When computing `(n - 1)!`, you can apply the same idea recursively until n is reduced to 0.\n- Let factorial(n) be the method for computing n!. If you call the method with n = 0, it immediately returns the result. The method knows how to solve the simplest case, which is referred to as the **base case** or the stopping condition.\n- If you call the method with n > 0, it reduces the problem into a subproblem for computing the factorial of n - 1.\n- The subproblem is essentially the same as the original problem, but it is simpler or smaller. Because the sub-problem has the same property as the original problem, you can call the method with a different argument, which is referred to as a recursive call.\n- The recursive algorithm for computing factorial(n) can be simply described as follows:\n\n```java\n    if(n == 0){\n        return 1;\n    }else{\n        return n * factorial(n - 1);\n    }\n```\n\nA recursive call can result in many more recursive calls, because the method keeps on dividing a subproblem into new subproblems. For a recursive method to terminate, the problem must eventually be reduced to a stopping case, at which point the method returns a result to its caller. The caller then performs a computation and returns the result to its own caller. This process continues until the result is passed back to the original caller. The original problem\ncan now be solved by multiplying `n` by the result of **factorial(n - 1)**.\n\n```java\n    import java.util.Scanner;\n\n    public class CalculateFactorial {\n    /** Main method */\n        public static void main(String[] args) {\n        // Create a Scanner\n            Scanner input = new Scanner(System.in);\n            System.out.print(\"Enter a nonnegative integer: \");\n            int n = input.nextInt();\n            \n            // Display factorial\n            System.out.println(\"Factorial of \" + n + \" is \" + factorial(n));\n        }\n\n        /** Return the factorial for the specified number */\n        public static long factorial(int n) {\n            if (n == 0) // Base case\n                return 1;\n            else\n                return n * factorial(n - 1); // Recursive call\n        }\n    }\n```\n##### Output:\n```yml\neg-1:\nEnter a nonnegative integer: 4\nFactorial of 4 is 24 \n\neg-2:\nEnter a nonnegative integer: 10\nFactorial of 10 is 3628800\n```\nThe `factorial` method is essentially a direct translation of the recursive mathematical definition for the factorial into Java code. The call to factorial is recursive\nbecause it calls itself. The parameter passed to factorial is decremented until it reaches the base case of 0. You see how to write a recursive method. How does recursion work behind the scenes? Below diagram illustrates the execution of the recursive calls, starting with n = 4.\n\n![fact](./images/fact.png)\n\n```java\npublic static long factorial(int n) {\n    return n * factorial(n - 1);\n }\n```\nThe example discussed in this section shows a recursive method that invokes itself. This is known as direct recursion. It is also possible to create indirect recursion. This occurs when method A invokes method B, which in turn invokes method A. There can even be seeral more methods involved in the recursion. For example, method A invokes method B, which invoke method C, which invokes method A. Let'seee one more another example to grasp it better.\n\n## Computing Fibonacci Numbers\n\nAs I mentioned that Recursion enables we to create an intuitative straightforward, simple solution to a problem. In this section, we'll be looking an example for creating an intuitive solution to a problem using recursion. Consider the well-known Fibonacci-series problem:\n\n```java\nThe series: 0 1 1 2 3 5 8 13 21 34 55 89 …\n (indexes): 0 1 2 3 4 5 6 7 8 9 10 11\n```\n\nThe Fibonacci series begins with 0 and 1, and each subsequent number is the sum of the preceding two. The series can be recursively defined as:\n\n```java\nfib(0) = 0;\nfib(1) = 1;\nfib(index) = fib(index - 2) + fib(index - 1); \nfor index >= 2\n```\n\nSo now the problem is: How do we find `fib(index)` for a given index?\n\nIt is easy to find `fib(2)`, because we know `fib(0)` and `fib(1)`. Assuming that we know `fib(index - 2)` and `fib(index - 1)`, we can obtain `fib(index)` immediately. Thus, the problem of computing `fib(index)` is reduced to computing `fib(index - 2)` and `fib(index - 1)`. When doing so, we apply the idea recursively until index is reduced to `0` or `1`.\n\nThe base case is index = `0` or index = `1`. One thing here to keep in mind that we can have more than one **Base case** also. If we call the method with index = `0` or index = `1`, it immediately returns the result. If we call the method with index >= `2`, it divides the problem into two subproblems for computing `fib(index - 1)` and `fib(index - 2)` using recursive calls. The recursive algorithm for computing `fib(index)` can be simply described as follows:\n\n```java\nif (index == 0) {\n    return 0;\n}\nelse if (index == 1) {\n    return 1;\n}\nelse {\n    return fib(index - 1) + fib(index - 2);\n}\n```\nlet's see how we can implement this recursive technique into the code:\n\n```java\nimport java.util.Scanner;\n\npublic class ComputeFibonacci {\n    // Main method\n    public static void main(String[] args) {\n        // Create a Scanner\n        Scanner input = new Scanner(System.in);\n        System.out.print(\"Enter an index for a Fibonacci number: \");\n        int index = input.nextInt();\n\n        // Find and display the Fibonacci number\n        System.out.println(\"The Fibonacci number at index \"\n        + index + \" is \" + fib(index));\n    }\n\n    // The method for finding the Fibonacci number\n    public static long fib(long index) {\n        if (index == 0) {// Base case\n            return 0;\n        }\n        else if (index == 1) {// Base case\n            return 1;\n        }\n        else {// Reduction and recursive calls\n            return fib(index - 1) + fib(index - 2);\n        }\n    }\n }\n```\n##### Output:\n\n```java\nEnter an index for a Fibonacci number: 1 (entered by user)\nThe Fibonacci number at index 1 is 1 \n\nEnter an index for a Fibonacci number: 6 (entered by user)\nThe Fibonacci number at index 6 is 8\n\nEnter an index for a Fibonacci number: 7 (entered by user)\nThe Fibonacci number at index 7 is 13\n```\n\nA little mind-melting, right? Let's break it down really quick.\n\n![fibonacci](./images/fibonacci.png)\n\nThe successive recursive calls for evaluating `fib(4)`. The original method, `fib(4)`, makes two recursive calls, `fib(3)` and `fib(2)`, and then returns `fib(3) + fib(2)`. But in what order are these methods called? In Java, operands are evaluated from left to right, so `fib(2)` is called after `fib(3)` is completely evaluated. There are many duplicated recursive calls. For instance, `fib(2)` is called twice, `fib(1)` three times, and `fib(0)` twice. In general, computing `fib(index)` requires roughly twice as many recursive calls as does computing `fib(index - 1)`. As you try larger index values, the number of calls substantially increases, see below:\n\n```java\nTable: Number of Recursive Calls in fib(index)\nindex: 2 3 4 10 20 30 40 50\nnumber of calls: 3 5 9 177 21891 2,692,537 331,160,281 2,075,316,483\n```\n\nOkay so I hope you will able to understand the idea of Recursion and why it is used, so let's move forward to the next lesson to know more about the Recursion.\n"
  },
  {
    "path": "lessons/intro-stacks.md",
    "content": "---\npath: \"/intro-stacks\"\ntitle: \"Intro to Stack\"\norder: \"13A\"\nsection: \"Stacks & Queues\"\ndescription: \"learn stack data-structure from scratch\"\nicon: \"align-justify\"\n---\n"
  },
  {
    "path": "lessons/intro-string.md",
    "content": "---\npath: \"/intro-string\"\ntitle: \"Intro to Strings\"\norder: \"6A\"\nsection: \"Strings In Depth\"\ndescription: \"learn strings in depth\"\nicon: \"road\"\n---\n"
  },
  {
    "path": "lessons/intro-trees.md",
    "content": "---\npath: \"/intro-trees\"\ntitle: \"Intro to Trees\"\norder: \"14A\"\nsection: \"Trees\"\ndescription: \"learn Tree data-struture from scratch\"\nicon: \"seedling\"\n---\n\nTree is a non-linear data structure which organises data in hierarchical form  and is recursive in nature. It is a popular data structure used in wide range of applications. Every element is considered as a node which has a predecessor and a successor. Trees are further classified into many types I.e, Binary Tree, Complete Binary Tree, Perfect Binary Tree etc. \n\n## Structure of Tree\n\nStructure of this Data Structure is clearly mentioned by its name which is in the form of a Tree. Every circle here represents a node.  Let’s understand them better with the help of the diagram below \n\n![binary_tree](./images/binary_tree.jpeg)\n\n**Root** - Initial node of a tree , which divides the tree into n numbers.\n\n**Parent Node** - The Predecessor of every node is its parent node. As D here is the parent of H & I.\n\n**Child Node** - The successor of every node is its child node. Here, H & I are the successors of D. \n\n**Siblings** - Nodes at the same levels are considered as siblings. \n\n**Leaf nodes** - The nodes having no successors are the one’s which are considered as leaves.\n\n**Right Sub-tree** - Nodes at the right side of the root node are the one’s of right sub-tree.\n\n**Left Sub-tree** - Nodes at the left side of the root node are the one’s of left sub tree.\n\n## Types of Trees\n\nTheir are in basic 4 types of Trees \n\n* Binary tree\n* Binary Search tree\n* AVL tree\n* B-tree\n\n### Binary Tree \n\nBinary tree is the one whose every parent node has atmost 2 children. Number of child nodes can be either 0,1 or 2. \nBinary Trees can further be classified into more types given below in the diagram.\n\n![binary_type](./images/binary_type.png)\n\n### Binary Search Tree \n\nBST is a lot similar to a binary tree  in which every parent node has at most 2 children. Other than that, BST follows few properties which makes it different from a binary tree. \n\nThe properties are - \n* Value in all the nodes of a left subtree should be lesser than the value in the root node.\n* Value in all the nodes of a right subtree should be larger than the value in the root node.\n\nThe pictorial representation of BST is \n\n![binary_search_tree](./images/binary_search_tree.png)\n\n### AVL Tree \n\nAVL trees are considered as the variants of binary tree which have the characteristics of both Binary tree and Binary search tree. These trees are self-balanced which means the height of left sub tree and right are sub tree are equal. This balanced is measured in terms of balancing factor. \n\n![AVL](./images/AVL.png)\n\nNow, let’s understand what is a balancing factor - \n* It is the difference between the left sub tree and right sub tree.\n* The value of balancing factor must be 0 , -1 and 1 , which means each node will be having a balancing factor of 0,1 and -1.\n* Values of nodes other than -1, to 1 in an AVL tree will represent an unbalanced tree that needs to be balanced.\n* If a node has a balance factor of 1, it means that the left subtree is one level higher than the right subtree.\n* If a node has a balance factor of 0, it means that the height of the left subtree and the right subtree is equal.\n* If a node has a balance factor of -1, it means that the right subtree is one level higher than the left subtree or the left subtree is one level lower than the right subtree.\n\n### B-Tree \n\nIt is also known as height-balanced m way tree, where m is the order of the tree. B-tree is more generalised form of a binary search tree.  In the case of a binary tree, the leaf nodes might not be at the same level. However, in the case of a B Tree, all the leaf nodes should be at the same level. \n\nProperties of B-Tree are -\n* The root may have between 2 and m children.\n* All other nodes must have between [M/2] and m children.\n* A node that has k children will have k-1 key values.\n* Thus, the root may have only 2 children; all other nodes must be at least half full .\n\n## Traversals in Trees\n\nTree traversals means traversing or visiting each node of the tree. Other than tree data structure, Stack , Queue and Linked List only have one way for traversing which makes Trees different from them also. \n\nTraversals are of 3 types \n\n1. **In-order Traversal** - This traversal calls for the sequence of LEFT, ROOT, RIGHT. \n2. **Pre-order Traversal** - This traversal calls for the sequence of ROOT ,LEFT, RIGHT.\n3. **Post-order Traversal** - This traversal calls for the sequence of LEFT, RIGHT, ROOT.\n\nNow let’s understand these a help of an example\n\n![traversal](./images/traversal.png)\n\nTaking the above tree into consideration let's understand how  traversing is done\n\n**In-order Traversal (LEFT , ROOT, RIGHT)** - Traverse the left sub-tree , visit the root , traverse the right sub-tree which makes the sequence (1,5,6,10,17,19,21)\n\n**Pre-order traversal (ROOT, LEFT , RIGHT)** - Visit the root , Traverse the left sub tree , Traverse the right sub tree which makes the sequence (10,5,1,6,19,17,21)\n\n**Post-order traversal (LEFT,RIGHT,ROOT)** - Traverse the left sub tree , Traverse the right sub-tree , visit the root which makes the sequence (1,6,5,17,21,19,10)\n"
  },
  {
    "path": "lessons/intro-tries.md",
    "content": "---\npath: \"/intro-tries\"\ntitle: \"Introduction to Tries\"\norder: \"23A\"\nsection: \"Tries\"\ndescription: \"learn about tries from scratch\"\nicon: \"share-alt\"\n---\n"
  },
  {
    "path": "lessons/introduction.md",
    "content": "---\npath: \"/introduction\"\ntitle: \"Welcome\"\norder: \"1A\"\nsection: \"Introduction\"\ndescription: \"this is the introduction to the website\"\nicon: \"search\"\n---\n\nHi there! We have made this website for the learning purpose for all those students out there who wanted to enhance there knowledge learning Data-Structure and Algorithms. This website contains all the data structures and algorithms in very simple way such that anyone can learn. The DS Algo will be oriented towards the language Java. Okay!\n\n## Motivations\n\nSo why should you care to learn DS Algo?\nSo the simple answer is that the skills here you will gain, will help you to enhance your problem-solving skills and in your interview for tech jobs since a lot of the questions asked by big tech companies are either directly related or derived from these classic algorithms and data structures.\n\n## Tips to Get Started\n\n> This course is hard. Like, really hard. Even if you've done all these things before, there is so much brain power to get through questions of these platform mentioned below. Don't expect to get everything on the first try. Don't get frustrated with yourself.\n\n- Solve Daily 5-10 Question.\n- If you are solving question on plateforms like Leetcode, CodeChef, Top-Coder etc.Keep the following points in mind:\n  - Don't give more than 45 mins to a Problem.(Leetcode)\n  - First Try to Solve Problem for 15 mins by Own.\n  - If you get stuck, Look for hints after trying 15 min by your own.\n  - If you unable to solve the problem check the solution, and then after few days try to solve again.\n\n## Where to File Issues\n\nWe have written this kind of like blog-site for Java and ds-algo and tried our best to not make mistakes. However when writing hours of material, mistakes are\ninevitable, both here in the grammar and in the course with the material. However We are constantly correcting the\nmistakes so that those of you that come later get the best material possible. If you find a mistake we'd love to fix\nit. The best way to do this is to open a pull request or [file an issue](https://www.github.com/utkarsh1504/DSA-Java) on the GitHub\nrepo.\n\n## Prerequisites\n\nThis course requires some of the prerequisite knowledge of the following:\n\n- Basic knowledge of any programming language (Like C, C++, Java, etc.). but if you don't that's completely fine. we'll be firstly going to learn Java then we'll move to data structures and algorithms.\n- One thing I'll recommend is to follow the [DSA-Bootcamp-Java](https://www.youtube.com/playlist?list=PL9gnSGHSqcnr_DxHsP7AW9ftq0AtAyYqJ) course because most of the notes and the material are based on that. So definitely you should watch that course.\n\n## Special Thanks\n\nA big shout out to [Kunal](https://twitter.com/kunalstwt) for his [DSA-Bootcamp-Java](https://www.youtube.com/playlist?list=PL9gnSGHSqcnr_DxHsP7AW9ftq0AtAyYqJ) course. On his Youtube channel, he is teaching this quality-loaded course completely for free.\n\nI also want to thank [Brian Holt](https://twitter.com/holtbt) for the idea of this course-site and for allowing me to use his starter. He's a great instructor at [Frontend Masters](https://frontendmasters.com/teachers/brian-holt/), if you want to learn some react and javascript related stuffs go checkout his courses. I'm really grateful for his support.\n"
  },
  {
    "path": "lessons/io-conditionals.md",
    "content": "---\npath: \"/io-conditionals\"\ntitle: \"Input/Output & Conditionals\"\norder: \"3C\"\nsection: \"Learn Java\"\ndescription: \"Learn java\"\n---\n\nOkay so let's learn about the control flow of a Java program.\n\n```java\n    // Java program to demonstrate the control flow\n\n    public class <ClassName> {\n        public static void main(String[] args){\n            System.out.println(\"Hello World\");\n        }\n    }\n```\n\nLet's go through the code line by line.\n\n- **``public static void main(String[] args)``** Java main method is the entry point of any Java program. You can only change the name of String array argument, for example you can change ``args`` to ``myStringArgs``.\n- **``public``** This is the access modifier of the main method. It has to be ``public`` so that Java Runtime Environment(JRE) can execute this method. Remember that if you make any method non-public then it’s not allowed to be executed by any program, there are some access restrictions applied. So it means that the main method has to be public.\n- **``Static``** When JRE starts, there is no object of the class present. That’s why the main method has to be static so that JVM can load the class into memory and call the main method. If the main method won’t be static, JVM would not be able to call it because there is no object of the class is present.\n- **``Void``** Java programming mandates that every method provide the return type. Java main method doesn’t return anything, that’s why it’s return type is void. This has been done to keep things simple because once the main method is finished executing, java program terminates. So there is no point in returning anything, there is nothing that can be done for the returned object by JVM. If we try to return something from the main method, it will give compilation error as an unexpected return value.\n- **``Main``** method is similar to the main function in C and C++.\nThe ``main`` method accepts a single argument: an array of elements of type String.\n- **``String[] args``** Java main method accepts a single argument of type String array. This is also called as java command line arguments.\n- **``System.out.println(\"Hello, World\");``** Outputs the string “Hello, World” followed by a new line on the screen.Output is actually accomplished by the built-in println( ) method. ``System`` is a predefined class that provides access to the system, and ``out`` is the variable of type output stream that is connected to the console.\n\n> System, out, println these are default classes and methods built into Java. If you want to read docs do a `ctrl+click` (IntelliJ Idea) on them.\n> \nOkay that's a lot of information to digest and it is the basic for a Java program. Now let's move on to the next section.\n\n## **If-Else Statements**\n\nIf-else statements are used to execute different code depending on the value of a variable. We use If-else statements for the condition based problem solving. If we have given a choice, then we can use if-else statements to decide which code to execute and it is called conditional execution.\n\nIt will be really easy to understand as we will see in the following example.\n\n#### Syntax\n\nif-else statements are written as follows.\n\n```java\n    // syntax\n    if (condition) {\n        // Code to execute if condition is true\n    }\n    else {\n        // Code to execute if condition is false\n    }\n```\n\nso above is the basic syntax of if-else statements. let's see some of the examples to understand it better.\nwe will see some simple examples and in last of this section i will link some more question so you can practise them on your own.\n\n```java\n    // program to check the greater number of the two.\n\n    public class <ClassName> {\n        public static void main(String[] args){\n            int a = 10;\n            int b = 20;\n            if(a > b){\n                System.out.println(\"a is greater than b\");\n            }\n            else{\n                System.out.println(\"b is greater than a\");\n            }\n        }\n    }\n```\n\nLets go through the if-else code line by line.\n\n- `if` is the keyword that indicates that the code block is an if statement. `(a > b)` is the condition. we can have multiple conditions in a single if statement. we're checking if `a` is greater than `b` if this turn out to be true then the code block under the if statement will be executed, if not then we'll move on the next statement.\n- `else if` is the keyword that indicates that the code block is an else if statement. `(a < b)` is the condition. else if is used to check if the condition is true then the code block under the if statement will be executed, if not then we'll move on the next statement. it is used when we have multiple conditions in a single if statement.\n- `else` is the keyword that indicates that the code block is an else statement. if the condition from the above statements are turn out to be false then the code block under the else statement will be executed.\n\nok so that's all. now let's see some more examples.\n\n```java\n    //A Java Program to demonstrate the use of if-else statement.  \n    //It is a program of odd and even number.  \n    public class IfElseClass {  \n        public static void main(String[] args) {  \n        //defining a variable  \n        int number = 13;  \n        //Check if the number is divisible by 2 or not  \n        if(number % 2 == 0){  \n            System.out.println(\"even number\");  \n        }\n        else{  \n            System.out.println(\"odd number\");  \n        }  \n    }  \n}  \n```\n\nLet's go through the code line by line.\n\n- `if` is the keyword that indicates that the code block is an if statement. `(number%2==0)` is the condition. we can have multiple conditions in a single if statement. we're checking if  ``number`` is divisible by ``2``  if this turn out to be true then the code block under the if statement will be executed, if not then we'll move on the next statement.\n- `else` is the keyword that indicates that the code block is an else statement. if the condition from the above statements are turn out to be false then the code block under the else statement will be executed.\n\n\n## **Switch Statements**\n\nSwitch statements are used to execute different code depending on the value of a variable. We use Switch statements for the condition based problem solving. Switch statements are used when we have multiple conditions in a single if statement. It is just a substitute for multiple if-else statements. In this a variable is compared to multiple cases one by one and when the case is matched then the code block under that case will be executed.\n\n#### Syntax\n\n```java\n    // syntax\n\n    switch (expression) {\n        case value1:\n            // code to execute if expression is value1\n            break;\n        case value2:\n            // code to execute if expression is value2\n            break;\n        default:\n            // code to execute if expression is not value1 or value2\n            break;\n    }\n```\nAbove is the basic syntax of switch statements. This is how it works:\n- The switch expression is only evaluated `once`.\n- The value of the expression is `compared` with the values of each case value.\n- If there is a `match`, ie. the case value and the switch expression are same, the associated block of code with the case value is executed.\n- The `break` and `default` keywords are optional and will be explained ahead.\n\nNow, let us see a diagramtic workflow of the Java Switch statement for a better understanding.\n\n![java-switch-statement](./images/java-switch-statement.png)\n\nLet us see an example to understand it better.\n\n```java\n    // Program to check Vowel or Consonant: \n    // It is not case-sensitive.\n\n    public class <ClassName> {\n        public static void main(String[] args){\n            char ch='O';  \n            switch(ch)  \n            {  \n                case 'a':   \n                    System.out.println(\"Vowel\");  \n                    break;  \n                case 'e':   \n                    System.out.println(\"Vowel\");  \n                    break;  \n                case 'i':   \n                    System.out.println(\"Vowel\");  \n                    break;  \n                case 'o':   \n                    System.out.println(\"Vowel\");  \n                    break;  \n                case 'u':   \n                    System.out.println(\"Vowel\");  \n                    break;  \n                case 'A':   \n                    System.out.println(\"Vowel\");  \n                    break;  \n                case 'E':   \n                    System.out.println(\"Vowel\");  \n                    break;  \n                case 'I':   \n                    System.out.println(\"Vowel\");  \n                    break;  \n                case 'O':   \n                    System.out.println(\"Vowel\");  \n                    break;  \n                case 'U':   \n                    System.out.println(\"Vowel\");  \n                    break;  \n                default:   \n                    System.out.println(\"Consonant\"); \n                    break;\n            }\n        }\n    }\n    \n    Output : Vowel\n```\n#### The 'break' Keyword\n- When the Java compiler reaches a `break` keyword, it breaks out of the switch block.\n- This will stop the execution of more code and case testing inside the block.\n- Basically it means that When a match is found, and the job is done, there is no need for more testing. Hence we break out of the switch statement.\n\n#### The 'default' Keyword\n- The `default` keyword specifies some code to run if there is no case match:\n\nNow let us see another example where there are no break statements present:\n\n```java\n    //switch cases without break statements\n\n    public class SwitchExample2 {  \n        public static void main(String[] args) {  \n            int num = 20;  \n            switch(num){  \n                case 10: \n                    System.out.println(\"10\");  \n                case 20: \n                    System.out.println(\"20\");  \n                case 30: \n                    System.out.println(\"30\");  \n                default:\n                    System.out.println(\"The number is not 10, 20 or 30\");  \n            }  \n        }  \n    } \n    \n    Output : 20\n             30\n             The number is not 10, 20 or 30\n```\nRemember that the switch statement is `fall-through`. That's why all the statements got executed after the first match because the break statement is NOT present.\n\n#### Points to Remember\n- There can be 1 or N number of `case values` for a switch expression.\n- The `case values` must be `literal` or `constant`. It doesn't allow variables.\n- The `case values` must be `unique`. In case of duplicate value, it renders compile-time error.\n- The Java `switch expression` must be of `byte, short, int, long` (with its Wrapper type), `enums and string`.\n- Each case statement can have a `break` statement which is `optional`. When control reaches to the break statement, it jumps the control after the switch expression. If a break statement is `not found`, it executes the next case.\n- The case value can have a `default` label which is `optional`.\n- The Java switch statement is `fall-through`. It means it executes all statements after the first match if a break statement is NOT present.\n\n#### Java Nested Switch Statements\nWe can use switch statement inside other switch statement in Java. It is known as nested switch statement.\n\n```java\n    //Java Program to demonstrate the use of Java Nested Switch  \n\n    public class NestedSwitchExample {    \n        public static void main(String args[])  \n          {  \n            //C - CSE, E - ECE, M - Mechanical  \n            char branch = 'C';                 \n            int collegeYear = 4;  \n            switch(collegeYear)  \n            {  \n                case 1:  \n                    System.out.println(\"English, Maths, Science\");  \n                    break;  \n                case 2:  \n                    switch( branch )   \n                    {  \n                        case 'C':  \n                            System.out.println(\"Operating System, Java, Data Structure\");  \n                            break;  \n                        case 'E':  \n                            System.out.println(\"Micro processors, Logic switching theory\");  \n                            break;  \n                        case 'M':  \n                            System.out.println(\"Drawing, Manufacturing Machines\");  \n                            break;  \n                    }  \n                    break;  \n                case 3:  \n                    switch(branch)   \n                    {  \n                        case 'C':  \n                            System.out.println(\"Computer Organization, MultiMedia\");  \n                            break;  \n                        case 'E':  \n                            System.out.println(\"Fundamentals of Logic Design, Microelectronics\");  \n                            break;  \n                        case 'M':  \n                            System.out.println(\"Internal Combustion Engines, Mechanical Vibration\");  \n                            break;  \n                    }  \n                    break;  \n                case 4:  \n                    switch(branch)   \n                    {  \n                        case 'C':  \n                            System.out.println(\"Data Communication and Networks, MultiMedia\");  \n                            break;  \n                        case 'E':  \n                                System.out.println(\"Embedded System, Image Processing\");  \n                            break;  \n                        case 'M':  \n                            System.out.println(\"Production Technology, Thermal Engineering\");  \n                            break;  \n                    }  \n                    break;  \n            }  \n        }  \n    } \n    \n    Output : Data Communication and Networks, MultiMedia\n```\n\n"
  },
  {
    "path": "lessons/jagged-array.md",
    "content": "---\npath: \"/jagged-array\"\ntitle: \"Jagged Arrays\"\norder: \"4F\"\nsection: \"Arrays\"\ndescription: \"arrays\"\n---\n\n> A jagged array is an array of arrays such that the member arrays can be of different sizes.\nWe can create a 2-D(multi-dimensional) array but with a variable number of columns in each row. \nThese types of arrays are known as Jagged arrays.\n\n![java-jaggedarray](./images/java-jagged-array.png)\n\n#### Declaration and Initialization of Jagged array :\n##### Syntax : \n\n```java\n    data_type array_name[][] = new data_type[n][];  //n: no. of rows\n        array_name[] = new data_type[n1]; //n1= no. of colmuns in row-1\n        array_name[] = new data_type[n2]; //n2= no. of colmuns in row-2\n        array_name[] = new data_type[n3]; //n3= no. of colmuns in row-3\n                                .                \n                                .                \n                                .              \n        array_name[] = new data_type[nk];  //nk=no. of colmuns in row-n\n```      \n#### Alternative, ways to Initialize a Jagged array :\n```java\n    int arr_name[][] = new int[][]  {\n        new int[] {15, 7, 22},\n        new int[] {67, 81},\n        new int[] {12, 91, 1, 17}\n    };\n```                                  \nOR   \n```java\n    int[][] arr_name = {\n        new int[] {15, 7, 22},\n        new int[] {67, 81},\n        new int[] {12, 91, 1, 17}\n    };\n```\n OR  \n```java\n    int[][] arr_name = {\n        {15, 7, 22},\n        {67, 81},\n        {12, 91, 1, 17}\n    };\n```\n\n```java\n    class Main {\n        public static void main(String[] args)\n        {\n            // Declaring 2-D array with 2 rows\n            int arr[][] = new int[2][];\n    \n            // Making the above array Jagged\n    \n            // First row has 3 columns\n            arr[0] = new int[3];\n    \n            // Second row has 2 columns\n            arr[1] = new int[2];\n    \n            // Initializing array\n            int count = 0;\n            for (int i = 0; i < arr.length; i++)\n                for (int j = 0; j < arr[i].length; j++)\n                    arr[i][j] = count++;\n    \n            // Displaying the values of 2D Jagged array\n            System.out.println(\"Contents of 2D Jagged Array\");\n            for (int i = 0; i < arr.length; i++) {\n                for (int j = 0; j < arr[i].length; j++)\n                    System.out.print(arr[i][j] + \" \");\n                System.out.println();\n            }\n        }\n    }\n```\n\n##### Output\nContents of 2D Jagged Array\n0 1 2 \n3 4 \n\nFollowing is another example where i’th row has i columns, i.e., the first row has 1 element, the second row has two elements and so on.\n\n```java\n// Another Java program to demonstrate 2-D jagged\n// array such that first row has 1 element, second\n// row has two elements and so on.\nclass Main {\n    public static void main(String[] args)\n    {\n        int r = 5;\n \n        // Declaring 2-D array with 5 rows\n        int arr[][] = new int[r][];\n \n        // Creating a 2D array such that first row\n        // has 1 element, second row has two\n        // elements and so on.\n        for (int i = 0; i < arr.length; i++)\n            arr[i] = new int[i + 1];\n \n        // Initializing array\n        int count = 0;\n        for (int i = 0; i < arr.length; i++)\n            for (int j = 0; j < arr[i].length; j++)\n                arr[i][j] = count++;\n \n        // Displaying the values of 2D Jagged array\n        System.out.println(\"Contents of 2D Jagged Array\");\n        for (int i = 0; i < arr.length; i++) {\n            for (int j = 0; j < arr[i].length; j++)\n                System.out.print(arr[i][j] + \" \");\n            System.out.println();\n        }\n    }\n}\n```\n##### Output\nContents of 2D Jagged Array\n0 \n1 2 \n3 4 5 \n6 7 8 9 \n10 11 12 13 14 \n\n\n### Applications\n\nAfter having learnt about Jagged Arrays, you must be wondering, where you should use them? Well, continue reading....\n\nA matrix is typically stored as a 2D arrays. It may be called as a \"dense\" representation. It's called dense because it stores each and every element of the array. But in some cases many elements of the array are 0 (or perhaps some other value) and it doesn't make sense to store them explicitly. These are called \"sparse\" matrix.\n\nNow coming to the applications and uses-\n- A lot of sparse matrix representations use a small number of 1D arrays.\nReally jagged arrays are definitely useful in situations where you don't want each 1D array to have the same length. Jagged arrays also make it somewhat easier to swap out entire \"rows\".\n- It should be noted that, jagged arrays usually have better performance than multidimensional arrays.\n- When using jagged arrays you can easily perform operations like row swap and row resize. Maybe in some cases usage of multidimensional arrays will be more safe, but jagged arrays should be used instead of multidimensional when you use it for analysis purposes."
  },
  {
    "path": "lessons/java-setup.md",
    "content": "---\npath: \"/java-setup\"\ntitle: \"Java Development Setup\"\norder: \"2B\"\nsection: \"Basics\"\ndescription: \"Intro to java\"\n---\n\n## Tools You Will Need\n\nFor setting up environment for performing java codes you need with a minimum of 64 MB of RAM.\nYou will also need the following softwares:\n- Linux 5.14 or Windows XP/7/8/10 operating system\n- [Java JDK 16](https://www.oracle.com/java/technologies/javase-jdk16-downloads.html)\n- IDEs\n\n\n## Java Architecture\nJava Architecture combines the process of compilation and interpretation. It explains the various processes involved whilst formulating a Java program\nThe explaination of  the java architecture in simple steps are as follows:\n\n- In Java, there is a process of compilation and interpretation.\n- The code written in Java, is converted into byte codes which is done by the Java Compiler.\n- The byte codes, then are converted into machine code by the JVM.\n- The Machine code is executed directly by the machine.\n\n### Components of Java Architecture\nThere are three main components of Java language:\n\n- **JVM:** Java Virtual Machine \n- **JRE:** Java Runtime Environment \n- **JDK:** Java Development Kit\n\n### Java Virtual Machine:\nJava applications are called WORA(Write Once, Run Anywhere) because of their ability to run a code on any platform. This is done only because of JVM. The JVM is a Java platform component that provides an environment for executing Java programs. JVM interprets the bytecode into machine code which is executed in the machine in which the Java program runs.\n\nSo, in a nutshell, JVM performs the following functions:\n- Loads the code\n- Verifies the code\n- Executes the code\n- Provides runtime environment\n\n### Java Runtime Environment:\nThe JRE software builds a runtime environment in which Java programs can be executed. The JRE is the on-disk system that takes your Java code, combines it with the needed libraries, and starts the JVM to execute it. The JRE contains libraries and software needed by your Java programs to run. JRE is a part of JDK but can be downloaded separately.\n\n### Java Development Kit:\nThe Java Development Kit is a software development environment used to develop Java applications and applets. It contains JRE and several development tools, an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (javadoc) accompanied with another tool.\n\n\n## Setting up Java development environment\n\nJava SE is freely available from the link [Download Java](https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads.html). You can download a version based on your \noperating system. Follow the instructions to download Java and run the `.exe` to install Java on your machine. Once Java is installed on your machine, you will need to set \nenvironment variables to point to correct installation directories:\n\n### Setting Up the Path for Windows:\n\nAssuming you have installed Java in *`C:\\Program Files\\Java\\JDK* directory`:*\n- Right-click on `This PC` and select `Properties`.\n- Click the `Environment variables` button under the `Advanced` tab.\n- Now, alter the `PATH` variable so that it also contains the path to the Java executable. Example, if the path is currently set to *`C:\\WINDOWS\\SYSTEM32`*, then change your \npath to read *`C:\\WINDOWS\\SYSTEM32;C:\\Program Files\\Java\\JDK\\bin`*\n\n### Setting Up the Path for Linux, UNIX:\n\nEnvironment variable `PATH` should be set to point to where the Java binaries have been installed. Refer to your shell documentation, if you have trouble doing this. Example, if\nyou use bash as your shell, then you would add the following line to the end of your *`.bashrc: export PATH = /path/to/java:$PATH`*.\n\n\n## IDEs\n\nIt is a software development environment for writing, debugging, and testing Java programs. we can write code very smoothly using IDE. There are many IDE's available for java. for example, **[IntelliJ IDEA](https://www.jetbrains.com/idea/)**, [Eclipse](https://www.eclipse.org/downloads/), [Netbeans](https://netbeans.apache.org/download/nb120/nb120.html), etc.\n\n\nAfter setting up JDK, install anyone of the of your favorite IDE just by clicking on the link and install it.\n\n\n*It's really Simple!*\n"
  },
  {
    "path": "lessons/jumps.md",
    "content": "---\npath: \"/jumps\"\ntitle: \"Jumps Statements\"\norder: \"3E\"\nsection: \"Learn Java\"\ndescription: \"Learn Java\"\n---\n\nJumps statements are used to jump to a specific line in a program. \n\nJava supports three jump statements.\n - `break`\n - `continue` \n - `return`\n \n These three statements transfer control to other part of the program.\n \nLet's see one by one how it works.\n\n## **Break statements**\nBreak Statement is a loop control statement that is used to terminate the loop. As soon as the  `break` statement is encountered from within a loop, the loop iterations stop there, and control returns from the loop immediately to the first statement after the loop.\n\nExample.\n```java\npublic  class  HelloWorld {\n     public  static  void  main(String[] args) {\n        // Initially loop is set to run from 1-5\n        for(int i=1; i<=5; i++){\n             // terminate loop when i is 4.\n             if(i=4){\n             break;\n             System.out.print(i);\n             }\n         }\n     }\n}\n\n```\nOutput:    `1 2 3`\n\nIn Java, `break` is majorly used for:\n- To exit a loop.\n- Terminate a sequence in a `switch` statement.\n\n## **Continue Statements**\nSometimes you doesn't want to execute a particular iteration in a loop. That is, you might want to continue running the loop but stop processing the  particular iteration. Then `continue` statement performs such an action.\n\nExample.\n```java\npublic  class  HelloWorld {\n     public  static  void  main(String[] args) {\n        // Initially loop is set to run from 1-5\n        for(int i=1; i<=6; i++){\n            // terminate loop when i is 4.\n            if(i=4){\n            continue;\n            System.out.print(i);\n            }\n        }\n    }\n}\n\n```\nOutput:   `1 2 3 5 6`\n\n## **Break vs Continue**\nLet's us see how these two jump statements are different from each other.\n\n\n| break             | continue                                                                |\n| ----------------- | --------------- |\n|The break statement is used to terminate the loop immediately. | The continue statement is used to skip the current iteration of the loop.|\n| break keyword is used to indicate break statements in java programming. | continue keyword is used to indicate continue statement in java programming.|\n| We can use a break with the switch statement. | The continue statement brings the next iteration early. |\n| It stops the execution of the loop. | It does not stop the execution of the loop.|\n\n\n\n## **Return Statement**\nThe `return` statement is used to explicitly return from a method. That is, it causes a program control to transfer back to the caller of the method.\nIt is used to **exit** from a method, with or without a value. Usage of **return keyword** as there exist two ways as listed below as follows:\n\n-   **Case 1:**  Methods returning a value\n-   **Case 2:**  Methods not returning a value\n\n\n##  **Methods returning a value**\n```java\n// Main method\nclass  CodeExample {\n    // Method 1\n\tpublic static int sumFunction(int a, int b) {\n\t\tint sum = a + b;\n\t    // Since return type of sunFunction method is integer so this method should return integer value\t\n\t\treturn sum;\n\t}\n\t\n\t// Main driver method\n\tpublic static void main(String[] args){\n\t    int a = 5;\n\t    int b = 8;\n\t    // here ans variable will receive sum from sumFunction\n\t\tint ans = sumFunction(a, b);\n\t\t// print statement\n\t\tSystem.out.println(ans);\n\t}\n}\n\n```\nOutput:  `13`\n\n**Output explanation:**  When  we are calling a class CodeExample method that has **return sum** which returns the value of sum and that’s value gets displayed on the console.\n\n##  **Methods not returning a value**\nFor methods that do not return a value, `return` statement in Java can be skipped. Here there arise two cases when there is no value been returned by the user as listed below as follows:\n-  Method not using return statement in void function\n- Methods with return type void\n\n#### Method not using return statement in void function\n```java\n// Main method\nclass  CodeExample {\n    // Method 1\n\tpublic static void sumFunction(int a, int b) {\n\t\tint sum = a + b;\n\t    // Since return type of sunFunction method is void so this method should not return any value.\t\n\t\tSystem.out.println(sum);\n\t}\n\t\n\t// Main driver method\n\tpublic static void main(String[] args){\n\t    int a = 5;\n\t    int b = 8;\n\t    // Here, we will just call the function and the program will execute successfully.\n\t    sumFunction(a, b);\n\t}\n}\n```\nOutput:  `13`\n\n#### Method with return type void\n```java\n// Main method\nclass CodeExample {\n    // Method 1\n\tpublic static void demoFunction(int n) {\n\t\tif(n<10) {\n\t\t    // return statement below(only using return statement and not returning anything)\n            \t    // control exits the method if this condition(i.e, n<9) is true.\n\t\t    return;\n\t        } else {\n\t\t   n++;\n\t\t}\n\t}\n\t// Main driver method\n\tpublic static void main(String[] args){\n\t     int n = 8;\n\t     // calling the function\n\t     sumFunction(n);\n\t}\n}\n```\nProgram executed successfully. \n"
  },
  {
    "path": "lessons/linearsearch.md",
    "content": "---\npath: \"/linearsearch\"\ntitle: \"Linear Search\"\norder: \"5A\"\nsection: \"Searching & Sorting\"\ndescription: \"learn Searching algorithms\"\nicon: \"sort\"\n---\n\n## **What is Searching ?**\n\nSearching is the process of finding some particular element in the list. If the element is present in the list, then the process is called successful and the process returns the location of that element, otherwise the search is called unsuccessful.\n\n## **What is Linear Search ?**\n\nLinear search is the simplest search algorithm and often called sequential search. In this type of searching, we simply traverse the list completely and match each element of the list with the item whose location is to be found. If the match found then location of the item is returned otherwise the algorithm return NULL.\n\n## **Linear Search Algorithm :**\n\n***LINEAR_SEARCH(ARR, N, VAL)***\n\n- **Step 1:** [INITIALIZE] SET POS = -1\n- **Step 2:** [INITIALIZE] SET I = 1\n- **Step 3:** Repeat Step 4 while I<=N\n- **Step 4:** IF ARR[I] = VAL\n<br> SET POS = I\n<br> PRINT POS\n<br> Go to Step 6\n<br> [END OF IF]\n<br> SET I = I + 1\n<br> [END OF LOOP]\n- **Step 5:** IF POS = -1\n<br> PRINT \" VALUE IS NOT PRESENTIN THE ARRAY \"\n<br> [END OF IF]\n- **Step 6:** EXIT\n\n![linear-search](./images/linear-search.png)\n\n## **Complexity of Algorithm :**\n\n- **Time Complexity :** O(n)\n- **Space Complexity :** O(1)\n\n## **Code :**\n\n```java\nclass LinearSearch\n{\n    // linear search algorithm \n    public static int linearSearch(int arr[], int n, int val)\n    {\n        for (int i = 0; i < n; i++)\n        {\n            if (arr[i] == val)\n                return i;\n        }\n        return -1;\n    }\n \n    // driver code main method\n    public static void main(String args[])\n    {\n        int arr[] = { 12, 25, 8, 10, 32 };\n        int x = 8;\n \n        // function call\n        int result = linearSearch(arr, arr.length, x);\n        if (result == -1)\n            System.out.print(\"Element is not present in array\");\n        else\n            System.out.print(\"Element is present at index : \"+ result);\n    }\n}\n```\n\n## **Output :**\n\n```\nElement is present at index : 2\n```"
  },
  {
    "path": "lessons/loops.md",
    "content": "---\npath: \"/loops\"\ntitle: \"Loops In Java\"\norder: \"3D\"\nsection: \"Learn Java\"\ndescription: \"Learn java\"\n---\n\nLoops are a way to repeat a block of code. It is used to remove repetitive code and to make code more readable. It is a way to write iterative code.\n\nThere are three types of loops in Java.\n\n- For\n- While\n- Do-While\n\n## **For Loops**\n\nFor loops are used to iterate over a range of numbers. In this loop, the range is defined by the `for` keyword. It needs a variable to store the current value and a condition to check if the loop should continue or not and a block of code to be executed for each value in the range of numbers (from the first to the last).\n\n#### Semantics\n\n```java\n    // syntax\n\n    for (initialization; condition; update){\n        // block of code\n    }\n```\n\n##### FlowChart\n\n![ForLoop](../images/forLoop.png)\n\nOk so let's see how to use for loops in writing a program.\n\n```java\n    //program to find sum upto n numbers\n    public class <ClassName> {\n        public static void main(String[] args) {\n            int sum = 0;\n            for (int i = 0; i < 10; i++) {\n                sum += i;\n            }\n            System.out.println(\"Sum of numbers upto 10 is \" + sum);\n        }\n    }\n```\n\nso let's analyze the code.\n\n- we have initialized the variable `sum` to 0.\n- then we used `for` loop:\n\n  - In the initialization, we have initialized the variable `i` to 0(`int i=0;`). This step is completely optional. You can also do the initialization before the loop. In that that would be look like:\n\n  ```java\n      int sum = 0;\n      int i = 0;\n      for (; i < 10; i++) {\n          ....\n  ```\n\n  or something like that.\n\n  ```java\n      int i;\n      for (i = 0; i < 10; i++) {\n  ```\n\n  - In the condition, it checks if `i` is less than 10. The condition checks if the loop should continue or not and this is not optional, you have to provide condition. In this case we have given a sigle condition `i < 10`. we can also have multiple conditions like `i < 10 && i > 0`. for multiple conditions, we need to use logical operator to combine them.\n\n  ```java\n        int sum = 0;\n        for(int i=0; i<10 && i%2==0; i++) {\n  ```\n\n  - In the update, it updates the value of `i` by 1. This is optional too. you can have the update like: i++, i--, i+=2, i-=2 etc.\n\n  ```java\n        int sum = 0;\n        for(int i=0; i<10;) {\n            sum += i;\n            i++;\n        }\n\n  ```\n\n- Okay so these are the variation of for loops. let's understand how this for loop works. So `i=0;`, i is assigned to 0. now it checks is `i`(0) is less than `10`, the answer is yes(true). if condition comes true, it executes the block of code. so inside the body, `sum += i;`, expression is evaluated. `sum` is assigned to 0 as sum = sum + i(0). so `sum` is assigned to 0. This is the first iteration.\n- Now `i` get updated to 1. now it checks if `i` is less than 10, the answer is yes(true). if condition comes true, it executes the block of code. so inside the body, `sum += i;`, expression is evaluated. `sum` is assigned to 0 as sum = sum + i(1). so `sum` is assigned to 1. This is the second iteration.\n- This iteration continues until `i` is less than 10. As `i` reaches 10, the condition becomes false and the loop stops.\n- So the final value of `sum` is 10, which will be printed on the console.\n\nAnd that's all. You can see that the for loop is very simple and easy to understand. You can practise some questions based on for loops in the [Assignment Section](./assignment.md).\n\n## **While Loops**\n\nWhile Loops are used to iterate over a range of numbers. In this loop, the range is defined by the `while` keyword. It needs a condition to check if the loop should continue or not and a block of code to be executed for each value in the range of numbers (from the first to the last).\n\n#### Semantics\n\n```java\n    // syntax\n    while(condition) {\n        // block of code\n    }\n```\n\n##### FlowChart\n\n![WhileLoop](./images/whileLoop.png)\n\nLet's see how to use while loops in writing a program.\n\n```java\n    // Program to demonstrate while loop\n    public class <ClassName> {\n        public static void main(String[] args) {\n            int i = 0;\n            while (i < 10) {\n                System.out.println(\"i is \" + i);\n                i++;\n            }\n        }\n    }\n```\n\nlet's analyze the code.\n\n- In line six, we have used `while` to iterate over the range of numbers and we have put condition `n > 0` because we want to iterate over the numbers from the first to the last.\n- Inside the loop we have used `n--` which is another way of writing `n = n - 1`, we're decrementing the value of `n` by 1 each time till it reaches zero and it reaches zero, condition will be false and the loop will break.\n- Lastly we print the value of `sum` to the screen.\n\nI think that's easy to understand. So let's move to our next loop.\n\n## **Do-While Loops**\n\nDo-While loops are used to iterate over a range of numbers. In this loop, the range is defined by the `do-while` keyword. It needs a condition to check if the loop should continue or not and a block of code to be executed for each value in the range of numbers (from the first to the last). The main difference between do-while and while loop is that the do-while loop is iterates _atleast once_ whether the condition is true or not it will execute the block of code atleast once which is not true in case of while loop.\n\n`While` loop firstly checks the condition and then it works according to the condition but `Do-while` loop first execute the code inside the body of the loop then checks the condition.\n\n#### Semantics\n\n```java\n    // syntax\n    do {\n        // block of code\n    } while(condition);\n```\n\n##### FlowChart\n\n![DoWhileLoop](./images/doWhileLoop.png)\n\nLet's see how to apply do-while loop in writing a program.\n\n```java\n    // Program to demonstrate do-while loop\n    public class <ClassName> {\n        public static void main(String[] args) {\n            int i = 0;\n            do {\n                System.out.println(\"i is \" + i);\n                i++;\n            } while (i < 10);\n        }\n    }\n```\n\nLets analyze the code.\n\n- we have used `do` keyword to execute the block of code firstly. firstly this loop will start executing the block of code and print the value of `i` to the console.\n- after that we're incrementing the value of `i` by 1 and then we check the condition `i < 10` and if the condition is true then we execute the loop again and print the value of `i` to the console.\n- and if the condition is false then we break the loop.\n- so the conclusion is that we first, atleast once execute the block of code and then we'll check the condition and according to the condition we'll work further.\n\n> There may be a question when to use which loop?\n\nOkay so it depends on the situation. It completey depends on the problem you are solving.\n\n- **`for` and `while`** - you can use both loop as per your requirement, but there is one thing which recommended by all is you should use `while` loop when you don't know how many times you have to iterate and use a `for` loop when you know how many times you have to iterate. suppose you have to print numbers from 1 to 10 then you know how many times you have to run the loop so use `for` loop. And if you have given that keep taking input from a user till user doesn't press x, here you don't know how many times you have to iterate so use `while` loop.\n\n- **`while` and `do-while`** - so in situations like, when you atleast once want to run the loop, irrespective of the condition, then you should use `do-while` loop and rest in all other cases either use `while` loop or `for` loop.\n"
  },
  {
    "path": "lessons/mergesort.md",
    "content": "---\npath: \"/mergesort\"\ntitle: \"Merge Sort\"\norder: \"8E\"\nsection: \"Recursion\"\ndescription: \"learn Recursion from scratch\"\n---\n"
  },
  {
    "path": "lessons/num-one.md",
    "content": "---\npath: \"/num-one\"\ntitle: \"Number Theory Part-A\"\norder: \"10C\"\nsection: \"Maths for DSA\"\ndescription: \"learn maths required in DSA\"\n---\n"
  },
  {
    "path": "lessons/num-three.md",
    "content": "---\npath: \"/num-three\"\ntitle: \"Number Theory Part-C\"\norder: \"10E\"\nsection: \"Maths for DSA\"\ndescription: \"learn maths required in DSA\"\n---\n\nIn this article we will cover the remaining and some advanced concepts of number theory.\n\n\n## **Mathmatical Exceptation**\n\nMathematical Expectation is an important concept in Probability Theory.This article attempts to throw some light on this topic by discussing few related mathematical and programming problems.\n\nMathematical expectation, also known as the expected value, which is the summation of all possible values from a random variable.It is also known as the product of the probability of an event occurring, denoted by P(x), and the value corresponding with the actually observed occurrence of the event.\nThe mathematical expectation is denoted by the formula:\n> E(X)= Σ (x1p1, x2p2, …, xnpn)\n\nIt is important to understand that **\"expected value\"** is not same as **\"most probable value\"** - rather, it need not even be one of the probable values. For example, in a dice-throw experiment, the expected value,  is not one of the possible outcomes at all.\n> The rule of **\"linearity of of the expectation\"** says that E[x1+x2] = E[x1] + E[x2].\n\n## **Fermat's Theorem**\n\nIt is also known as Fermat's little theorem.\nFermat’s little theorem states that if p is a prime number, then for any integer a, the number a^(p) – a is an integer multiple of p.\n> Here p is a prime number ap ≡ a (mod p) \n\n>Let's see an Example How Fermat’s little theorem works \n\n\n**Examples:** \n \n P = an integer Prime number   \n a = an integer which is not multiple of P  \n Let a = 2 and P = 17 \n \n According to Fermat's little theorem \n  2^(17 - 1)     ≡ 1 mod(17)\n we got  65536 % 17 ≡ 1   \n that mean (65536-1) is an multiple of 17 \n \n ```java\n// Java program to find modular \n// inverse of a under modulo m \n// using Fermat's little theorem. \n// This program works only if m is prime.\n\nclass Main {\n    static int __gcd(int a, int b) {\n        if (b == 0) {\n            return a;\n        } else {\n            return __gcd(b, a % b);\n        }\n    }\n\n    // To compute x^y under modulo m\n    static int power(int x, int y, int m) {\n        if (y == 0) {\n            return 1;\n        }\n        int p = power(x, y / 2, m) % m;\n        p = (p * p) % m;\n\n        return (y % 2 == 0) ? p : (x * p) % m;\n    }\n\n    // Function to find modular\n    // inverse of a under modulo m\n    // Assumption: m is prime\n    static void modInverse(int a, int m) {\n        if (__gcd(a, m) != 1) {\n            System.out.print(\"Inverse doesn't exist\");\n        } else {\n            // If a and m are relatively prime, then\n            // modulo inverse is a^(m-2) mode m\n            System.out.print(\"Modular multiplicative inverse is \" + power(a, m - 2, m));\n        }\n    }\n\n    // Driver code\n    public static void main(String[] args) {\n        int a = 3, m = 11;\n        modInverse(a, m);\n    }\n}\n```\n\n## **Wilson's Theorem**\n\nWilson’s theorem states that a natural number p > 1 is a prime number if and only if\n**(p-1) ! ≡ -1 mod p**<br> \nOR **(p-1) ! ≡ (p-1) mod p**\n\n**Examples:**\n\np = 5\n(p-1)! = 24\n24 % 5  = 4\n\np = 7\n(p-1)! = 6! = 720\n720 % 7  = 6\n\n**Proof:**\nIt is easy to check the result when n is 2 or 3, so let us assume n > 3. If n is composite, then its positive divisors are among the integers 1, 2, 3, 4, ... , n-1 and it is clear that gcd( (n-1)! , n) > 1, so we can not have (n-1)! = -1 (mod n).\n\nHowever if n is prime, then each of the above integers are relatively prime to n. So for each of these integers a there is another b such that ab = 1 (mod n). It is important to note that this b is unique modulo n, and that since n is prime, a = b if and only if a is 1 or n-1. Now if we omit 1 and n-1, then the others can be grouped into pairs whose product is one showing\n\n2.3.4.....(n-2) = 1 (mod n)\n\n(or more simply (n-2)! = 1 (mod n)). Finally, multiply this equality by n-1 to complete the proof.\n\n## **Lucas Theorem**\n\nLucas theorem basically suggests that the value of nCr can be computed by multiplying results of niCri where ni and ri are individual same-positioned digits in base p representations of n and r respectively..\nThe idea is to one by one compute niCri for individual digits ni and ri in base p.Since these digits are in base p, we would never need more than O(p) space and time complexity of these individual computations would be bounded by O(p2).\n\n```java\n// A Lucas Theorem based solution to compute nCr % p\nclass Lucas {\n    // Returns nCr % p. In this Lucas Theorem based program,\n    // this function is only called for n < p and r < p.\n    static int nCrModpDP(int n, int r, int p) {\n        // The array C is going to store last row of\n        // pascal triangle at the end. And last entry\n        // of last row is nCr\n        int[] C = new int[r + 1];\n        C[0] = 1; // Top row of Pascal Triangle\n\n        // One by constructs remaining rows of Pascal\n        // Triangle from top to bottom\n        for (int i = 1; i <= n; i++) {\n            // Fill entries of current row using previous\n            // row values\n            for (int j = Math.min(i, r); j > 0; j--)\n                // nCj = (n-1)Cj + (n-1)C(j-1);\n                C[j] = (C[j] + C[j - 1]) % p;\n        }\n        return C[r];\n    }\n\n    // Lucas Theorem based function that returns nCr % p\n    // This function works like decimal to binary conversion\n    // recursive function. First we compute last digits of\n    // n and r in base p, then recur for remaining digits\n    static int nCrModpLucas(int n, int r, int p) {\n        // Base case\n        if (r == 0) {\n            return 1;\n        }\n        // Compute last digits of n and r in base p\n        int ni = n % p;\n        int ri = r % p;\n        // Compute result for last digits computed above, and\n        // for remaining digits. Multiply the two results and\n        // compute the result of multiplication in modulo p.\n        return (nCrModpLucas(n / p, r / p, p) * // Last digits of n and r\n                nCrModpDP(ni, ri, p)) % p; // Remaining digits\n    }\n\n    // Driver program\n\n    public static void main(String[] args) {\n        int n = 1000, r = 900, p = 13;\n        System.out.println(\"Value of nCr % p is \" + nCrModpLucas(n, r, p));\n    }\n}\n```\n\n## **Chinese Remainder Theorem**\n\n**Chinese Remainder Theorem states that there always exists an x that satisfies given congruences.**\n\nLet num[0], num[1], …num[k-1] be positive integers that are pairwise coprime. Then, for any given sequence of integers rem[0], rem[1], … rem[k-1], there exists an integer x solving the following system of simultaneous congruences.\nA Naive Approach to find x is to start with 1 and one by one increment it and check if dividing it with given elements in num[] produces corresponding remainders in rem[]. Once we find such an x, we return it. \n\n```java\n\n// A Java program to demonstrate the working of Chinese remainder theorem\nclass ChineseRemainderTheorem {\n    // k is size of num[] and rem[]. Returns the smallest\n    // number x such that:\n    // x % num[0] = rem[0],\n    // x % num[1] = rem[1],\n    // ..................\n    // x % num[k-2] = rem[k-1]\n    // Assumption: Numbers in num[] are pairwise coprime\n    // (gcd for every pair is 1)\n    static int findMinX(int num[], int rem[], int k) {\n        int x = 1; // Initialize result\n        // As per the Chinese remainder theorem,\n        // this loop will always break.\n        while (true) {\n            // Check if remainder of x % num[j] is\n            // rem[j] or not (for all j from 0 to k-1)\n            int j;\n            for (j = 0; j < k; j++)\n                if (x % num[j] != rem[j]) {\n                    break;\n                }\n            // If all remainders matched, we found x\n            if (j == k) {\n                return x;\n            }\n\n            // Else try next number\n            x++;\n        }\n\n    }\n\n    // Driver method\n    public static void main(String args[]) {\n        int num[] = { 3, 4, 5 };\n        int rem[] = { 2, 3, 1 };\n        int k = num.length;\n        System.out.println(\"x is \" + findMinX(num, rem, k));\n    }\n}\n```\n\n## **NP-Completeness**\nA problem is in the class NPC if it is in NP and is as hard as any problem in NP. A problem is NP-hard if all problems in NP are polynomial time reducible to it, even though it may not be in NP itself.\n\n**NP-Hard**\nIf a polynomial time algorithm exists for any of these problems, all problems in NP would be polynomial time solvable. These problems are called NP-complete. The phenomenon of NP-completeness is important for both theoretical and practical reasons.\n\n##### Definition of NP-Completeness\n\nA language B is NP-complete if it satisfies two conditions:\n- B is in NP.\n- Every A in NP is polynomial time reducible to B.\n\nIf a language satisfies the second property, but not necessarily the first one, the language B is known as NP-Hard. Informally, a search problem B is NP-Hard if there exists some NP-Complete problem A that Turing reduces to B.\n\nThe problem in NP-Hard cannot be solved in polynomial time, until P = NP. If a problem is proved to be NPC, there is no need to waste time on trying to find an efficient algorithm for it. Instead, we can focus on design approximation algorithm.\n\n**NP-Completeness Problems**:\n> Following are some NP-Complete problems, for which no polynomial time algorithm is known.\n\n - Determining whether a graph has a Hamiltonian cycle\n - Determining whether a Boolean formula is satisfiable, etc.\n \n**NP-Hard Problems\n> The following problems are NP-Hard\n\n- The circuit-satisfiability problem\n- Set Cover\n- Vertex Cover\n- Travelling Salesman Problem\n\nIn this context, now we will discuss TSP is NP-Complete:\n\n**TSP is NP-Complete**\n\nThe traveling salesman problem consists of a salesman and a set of cities. The salesman has to visit each one of the cities starting from a certain one and returning to the same city. The challenge of the problem is that the traveling salesman wants to minimize the total length of the trip\n\nOkay so let's move to some more advanced concepts: \n\n## 1. Bit Masking + Dynamic Programming \n\nFirst thing to make sure before using bitmasks for solving a problem is that it must be having small constraints, as solutions which use bitmasking generally take up exponential time and memory.\n\nLet's first try to understand what Bitmask means. Mask in Bitmask means hiding something. Bitmask is nothing but a binary number that represents something. Let's take an example. Consider the set *A={1,2,3,4,5}*. We can represent any subset of *A* using a bitmask of length *5*, with an assumption that if *ith(0<=i<=4)* bit is set then it means ith element is present in subset. So the bitmask *01010* represents the subset *{2,4}*\n\n*Now the benefit of using bitmask. We can set the ith bit, unset the ith bit, check if ith bit is set in just one step each. Let's say the bitmask b = 01010.*\n\n***Set the ith bit*** : b|(1<<i). Let i = 0, so, \n\n\n(1<<i) = 00001\n01010 | 00001 = 01011\n\nSo now the subset includes the 0th element also, the subset is {1,2,4}.\n\n***Unset the ith bit*** : b&!(1<<i). Let i = 1, so\n\n(1<<i) = 00010\n\n!(1<<i) = 11101\n\n00010 & 11101 = 01000\n\nNow the subset does not include the 1st element so the subset now is {4}.\n\n***Checking if the ith bit is set***: b&(1<<i) doing this operation if ith bit is set we will get a non-zero integer other wise a zero.\n\nLet i =3, \n\n(1<<i) = 01000\n\n01010 & 01000 =  01000\n\nClearly the result is non-zero so that means 3rd element is present in the subset. \n\n***Lets take a problem where given a set we have to count how many subsets have sum of elements greater than or equal to a give value.***\n\nAlgorithm is simple:\n```algorithm \nsolve(set, set_size, val)\n    count = 0\n    for x = 0 to power(2, set_size)\n        sum = 0\n        for k = 0 to set_size        \n            if kth bit is set in x\n                sum = sum + set[k]\n        if sum >= val\n             count = count + 1\n    return count\n```\nTo iterate over all the subsets we are going to each number from *0 to 2^(set_size)-1*.\nThe above problem simply uses bitmask and complexity is *O(N2^(N))*.\n\n##### Assignment Problem:\n*There are N persons and N tasks, each task is to be alloted to a single person. We are also given a matrix cost of size NxN , where cost[i][j] denotes, how much person i is going to charge for task j. Now we need to assign each task to a person in such a way that the total cost is minimum. Note that each task is to be alloted to a single person, and each person will be alloted only one task.*\n\nThe brute force approach here is to try every possible assignment. Algorithm is given below:\n\n```\nassign(N,  cost)\n    for i = 0 to N\n        assignment[i] = i            //assigning task i to person i\n    res = INFINITY\n    for j = 0 to factorial(N)\n        total_cost = 0\n        for i = 0 to N\n            total_cost = total_cost + cost[i][assignment[i]]\n        res = min(res, total_cost)\n        generate_next_greater_permutation(assignment)\n    return res\n```\n\nThe complexity of above algorithm is *O(N!)*, well that's clearly not good.\n\nLet's try to improve it using dynamic programming. Suppose the state of dp is *(k,mask)* , where k represents that person 0 to k-1 have been assigned a task, and mask is a binary number, whose ith bit represents if the ith task has been assigned or not.\nNow, suppose, we have answer(k,mask), we can assign a task i  to person k, iff ith task is not yet assigned to any peron i.e. *mask&(i<<i)* = 0  then *answer(k+1,mask|(1<<i))*,  will be given as:\n\n*answer(k+1,mask|(1<<i)) = min(answer(k+1,mask|(1<<i)), answer(k,mask)+cost[k][i])*\n\n\n\nOne thing to note here is k is always equal to the number set bits in mask , so we can remove that. So the dp state now is just (mask), and if we have answer(mask), then\n\n*answer(mask|(1<<i)) = min(answer(mask|(1<<i)), answer(mask)+cost[x][j])*\n\nhere x = number of set bits in mask.\nComplete algorithm is given below:\n\n```\nassign(N, cost)\n    for i = 0 to power(2,N)\n        dp[i] = INFINITY\n    dp[0] = 0\n    for mask = 0 to power(2, N)\n        x = count_set_bits(mask)\n        for j = 0 to N\n            if jth bit is not set in i\n                dp[mask|(1<<j)] = min(dp[mask|(1<<j)], dp[mask]+cost[x][j])\n    return dp[power(2,N)-1]                \n\n```\n\nTime complexity of above algorithm  is O(N*2^N) and space complexity is O(2^N).\nThis is just one problem that can be solved using DP+bitmasking. There's a whole lot.\n<!-- Bit Masking + DP -->\n\n<!-- Extended Euclidean Algorithm -->\n\n\n## 2. Extended Euclidean Algorithm\n\nWhile the Euclidean algorithm calculates only the greatest common divisor (GCD) of two integers a and b, the extended version also finds a way to represent GCD in terms of a and b, i.e. coefficients x and y for which:\n\nax+by=gcd(a,b)\n\nIt's important to note, that we can always find such a representation, for instance, gcd(55,80)=5 therefore we can represent 5 as a linear combination with the terms 55 and 80, 55x3+80x(−2)=5.\n\n#### Algorithm\nWe will denote the GCD of a and b with g in this section.\n\nThe changes to the original algorithm are very simple. If we recall the algorithm, we can see that the algorithm ends with b=0 and a=g. For these parameters, we can easily find coefficients, namely gx1+0x0=g.\n\nStarting from these coefficients (x,y)=(1,0), we can go backwards up the recursive calls. All we need to do is to figure out how the coefficients x and y change during the transition from (a,b) to (b, a mod b).\n\nLet us assume we found the coefficients (x1,y1) for (b,amodb):\n\n*b⋅x1+(amodb)⋅y1=g*\n\nand we want to find the pair (x,y) for (a,b):\n\n*a⋅x+b⋅y=g*\n\nWe can represent amodb as:\n\n*amodb=a−⌊a/b⌋⋅b*\n\nSubstituting this expression in the coefficient equation of (x1,y1) gives:\n\n*g=b⋅x1+(amodb)⋅y1=b⋅x1+(a−⌊a/b⌋⋅b)⋅y1*\n\nand after rearranging the terms:\n\n*g=a⋅y1+b⋅(x1−y1⋅⌊a/b⌋)*\n\nWe found the values of x and y:\n\n*x=y1*\n\n*y=x1−y1⋅⌊a/b⌋*\n\n\n#### Implementation\n```java\nclass Extended {\n    // extended Euclidean Algorithm\n    public static int gcdExtended(int a, int b, int x, int y)\n    {\n        // Base Case\n        if (a == 0) {\n            x = 0;\n            y = 1;\n            return b;\n        }\n  \n        int x1 = 1, y1 = 1; // To store results of recursive call\n        int gcd = gcdExtended(b % a, a, x1, y1);\n  \n        // Update x and y using results of recursive\n        // call\n        x = y1 - (b / a) * x1;\n        y = x1;\n  \n        return gcd;\n    }\n  \n    // Driver Program\n    public static void main(String[] args)\n    {\n        int x = 1, y = 1;\n        int a = 35, b = 15;\n        int g = gcdExtended(a, b, x, y);\n        System.out.print(\"gcd(\" + a + \", \" + b + \") = \" + g);\n    }\n}\n\n```\n\n\n<!-- Extended Euclidean Algorithm -->\n\n<!-- Modulo Muliplicative Inverse  -->\n\n## 3. Modulo Multiplicative Inverse\n\nIn modular arithmetic we do not have a division operation. However, we do have modular inverses.\n- The modular inverse of A (mod C) is A^-1\n- (A * A^-1) ≡ 1 (mod C) or equivalently (A * A^-1) mod C = 1\n- Only the numbers coprime to C (numbers that share no prime factors with C) have a modular inverse (mod C)\n\n##### Example: A=3, C=7\n- 3 * 0 ≡ 0 (mod 7)\n- 3 * 1 ≡ 3 (mod 7)\n- 3 * 2 ≡ 6 (mod 7)\n- 3 * 3 ≡ 9 ≡ 2 (mod 7)\n- 3 * 4 ≡ 12 ≡ 5 (mod 7)\n- 3 * 5 ≡ 15 (mod 7) ≡ 1 (mod 7)   <------ ​*FOUND INVERSE!*\n- 3 * 6 ≡ 18 (mod 7) ≡ 4 (mod 7)\n\n#### Implementation -1 (Naive)\nA Naive method is to try all numbers from 1 to m. For every number x, check if (a*x)%m is 1.\n\nTime Complexity: O(m).\n\n\n````java\nclass Modulo{\n    static int modInverse(int a, int m)\n    {\n      \n        for (int x = 1; x < m; x++)\n            if (((a%m) * (x%m)) % m == 1)\n                return x;\n        return 1;\n    }\n \n    public static void main(String args[])\n    {\n        int a = 3, m = 11;\n       \n        // Function call\n        System.out.println(modInverse(a, m));\n    }\n}\n\n````\n\n#### Implementation -2 (Extended Euler’s GCD algorithm - Iterative) \nThe idea is to use Extended Euclidean algorithms that takes two integers ‘a’ and ‘b’, finds their gcd and also find ‘x’ and ‘y’ such that \n\nax + by = gcd(a, b)\n\nTime Complexity: O(Log m)\n\n````java\nclass Modulo{\n \n    // Returns modulo inverse of a with\n    // respect to m using extended Euclid\n    // Algorithm Assumption: a and m are\n    // coprimes, i.e., gcd(a, m) = 1\n    static int modInverse(int a, int m)\n    {\n        int m0 = m;\n        int y = 0, x = 1;\n \n        if (m == 1)\n            return 0;\n \n        while (a > 1) {\n            // q is quotient\n            int q = a / m;\n \n            int t = m;\n \n            // m is remainder now, process\n            // same as Euclid's algo\n            m = a % m;\n            a = t;\n            t = y;\n \n            // Update x and y\n            y = x - q * y;\n            x = t;\n        }\n \n        // Make x positive\n        if (x < 0)\n            x += m0;\n \n        return x;\n    }\n \n    // Driver code\n    public static void main(String args[])\n    {\n        int a = 3, m = 11;\n         \n        // Function call\n        System.out.println(\"Modular multiplicative \"\n                           + \"inverse is \"\n                           + modInverse(a, m));\n    }\n}\n \n````\n\n#### Implementation-3 (Works when m is prime)\nIf we know m is prime, then we can also use Fermats’s little theorem to find the inverse. \n\nam-1 ≅ 1 (mod m)\n\nTime Complexity: O(Log m)\n\n\n````java\nclass Modulo{\n \n    // Function to find modular inverse of a\n    // under modulo m Assumption: m is prime\n    static void modInverse(int a, int m)\n    {\n        int g = gcd(a, m);\n        if (g != 1)\n            System.out.println(\"Inverse doesn't exist\");\n        else\n        {\n            // If a and m are relatively prime, then modulo\n            // inverse is a^(m-2) mode m\n            System.out.println(\n                \"Modular multiplicative inverse is \"\n                + power(a, m - 2, m));\n        }\n    }\n   \n      static int power(int x, int y, int m)\n    {\n        if (y == 0)\n            return 1;\n        int p = power(x, y / 2, m) % m;\n        p = (int)((p * (long)p) % m);\n        if (y % 2 == 0)\n            return p;\n        else\n            return (int)((x * (long)p) % m);\n    }\n \n    // Function to return gcd of a and b\n    static int gcd(int a, int b)\n    {\n        if (a == 0)\n            return b;\n        return gcd(b % a, a);\n    }\n \n    // Driver Code\n    public static void main(String args[])\n    {\n        int a = 3, m = 11;\n        \n        // Function call\n        modInverse(a, m);\n    }\n}\n````\n<!-- Modulo Muliplicative Inverse  -->\n\n<!-- Linear Diophantine Equations -->\n\n## 4. Linear Diophantine Equations\n\nA Diophantine equation is a polynomial equation, usually in two or more unknowns, such that only the integral solutions are required. An Integral solution is a solution such that all the unknown variables take only integer values.\nGiven three integers a, b, c representing a linear equation of the form : ax + by = c. Determine if the equation has a solution such that x and y are both integral values.\n```\nInput : a = 3, b = 6, c = 9\nOutput: Possible\nExplanation : The Equation turns out to be, \n3x + 6y = 9 one integral solution would be \nx = 1 , y = 1\n\nInput : a = 3, b = 6, c = 8\nOutput : Not Possible\nExplanation : o integral values of x and y \nexists that can satisfy the equation 3x + 6y = 8\n\nInput : a = 2, b = 5, c = 1\nOutput : Possible\nExplanation : Various integral solutions\npossible are, (-2,1) , (3,-1) etc.\n\n```\n\n#### Solution: \nFor linear Diophantine equation equations, integral solutions exist if and only if, the GCD of coefficients of the two variables divides the constant term perfectly. In other words the integral solution exists if, GCD(a ,b) divides c.\nThus the algorithm to determine if an equation has integral solution is pretty straightforward. \n \n\n- Find GCD of a and b\n- Check if c % GCD(a ,b) ==0\n- If yes then print Possible\n- Else print Not Possible\n\nBelow is the implementation of above approach.\n\n````java\nclass Equation {\n     \n    // Utility function to find the GCD\n    // of two numbers\n    static int gcd(int a, int b)\n    {\n        return (a % b == 0) ?\n                Math.abs(b) : gcd(b,a%b);\n    }\n     \n    // This function checks if integral\n    // solutions are possible\n    static boolean isPossible(int a, int b, int c)\n    {\n        return (c % gcd(a, b) == 0);\n    }\n     \n    // Driver function\n    public static void main (String[] args)\n    {\n        // First example\n        int a = 3, b = 6, c = 9;\n        if(isPossible(a, b, c))\n            System.out.println( \"Possible\" );\n        else\n            System.out.println( \"Not Possible\");\n     \n        // Second example\n        a = 3; b = 6; c = 8;\n        if(isPossible(a, b, c))\n            System.out.println( \"Possible\") ;\n        else\n            System.out.println( \"Not Possible\");\n     \n        // Third example\n        a = 2; b = 5; c = 1;\n        if(isPossible(a, b, c))\n            System.out.println( \"Possible\" );\n        else\n            System.out.println( \"Not Possible\");\n    }\n} \n ````\n\n````\nOutput : \n\nPossible\nNot Possible\nPossible\n````\n<!-- Linear Diophantine Equations -->\n\n\n<!-- Matrix Exponentiation -->\n\n## 5. Matrix Exponentiation\n\nThe concept of matrix exponentiation in its most general form is very useful in solving questions that involve calculating the nth term of a linear recurrence relation in time of the order of log(n).\n\n````\nFor solving the matrix exponentiation we are assuming a\nlinear recurrence equation like below:\n\nF(n) = a*F(n-1) + b*F(n-2) + c*F(n-3)   for n >= 3 \n                                 . . . . . Equation (1)\nwhere a, b and c are constants. \n\nFor this recurrence relation, it depends on three previous values. \nNow we will try to represent Equation (1) in terms of the matrix. \n\n[First Matrix] = [Second matrix] * [Third Matrix]\n| F(n)   |     =   Matrix 'C'    *  | F(n-1) |\n| F(n-1) |                          | F(n-2) |\n| F(n-2) |                          | F(n-3) |\n \nDimension of the first matrix is 3 x 1 . \nDimension of the third matrix is also 3 x 1. \n\nSo the dimension of the second matrix must be 3 x 3 \n[For multiplication rule to be satisfied.]\n\nNow we need to fill the Matrix 'C'. \n\nSo according to our equation. \nF(n) = a*F(n-1) + b*F(n-2) + c*F(n-3)\nF(n-1) = F(n-1)\nF(n-2) = F(n-2)\n\nC = [a b c\n     1 0 0\n     0 1 0]\n\nNow the relation between matrix becomes : \n[First Matrix]  [Second matrix]       [Third Matrix]\n| F(n)   |  =  | a b c |         *    | F(n-1) |\n| F(n-1) |     | 1 0 0 |              | F(n-2) |\n| F(n-2) |     | 0 1 0 |              | F(n-3) |\n\nLets assume the initial values for this case :- \nF(0) = 0\nF(1) = 1\nF(2) = 1\n\nSo, we need to get F(n) in terms of these values.\n\nSo, for n = 3 Equation (1) changes to \n| F(3) |  =  | a b c |      *       | F(2) |\n| F(2) |     | 1 0 0 |              | F(1) |\n| F(1) |     | 0 1 0 |              | F(0) |\n\nNow similarly for n = 4 \n| F(4) |  =  | a b c |      *       | F(3) |\n| F(3) |     | 1 0 0 |              | F(2) |\n| F(2) |     | 0 1 0 |              | F(1) |\n\n             - - - -  2 times - - -\n| F(4) |  =  | a b c |  * | a b c |    *    | F(2) |\n| F(3) |     | 1 0 0 |    | 1 0 0 |         | F(1) |\n| F(2) |     | 0 1 0 |    | 0 1 0 |         | F(0) |\n\n\nSo for n, the Equation (1) changes to \n\n                - - - - - - - - n -2 times - - - -  -       \n| F(n)   |  =  | a b c | * | a b c | * ... * | a b c | * | F(2) |\n| F(n-1) |     | 1 0 0 |   | 1 0 0 |         | 1 0 0 |   | F(1) |\n| F(n-2) |     | 0 1 0 |   | 0 1 0 |         | 0 1 0 |   | F(0) |\n\n\n| F(n)   |  =  [ | a b c | ] ^ (n-2)   *  | F(2) |\n| F(n-1) |     [ | 1 0 0 | ]              | F(1) |\n| F(n-2) |     [ | 0 1 0 | ]              | F(0) |\n\n\n````\n\nSo we can simply multiply our Second matrix n-2 times and then multiply it with the third matrix to get the result. Multiplication can be done in (log n) time using Divide and Conquer algorithm for power. Let us consider the problem of finding n’th term of a series defined using below recurrence.\n\n````\nn'th term,\n    F(n) = F(n-1) + F(n-2) + F(n-3), n >= 3\nBase Cases :\n    F(0) = 0, F(1) = 1, F(2) = 1\n````\n\nWe can find n’th term using following : \n \n\n````Putting a = 1, b = 1 and c = 1 in above formula\n\n| F(n)   |  =  [ | 1 1 1 | ] ^ (n-2)   *  | F(2) |\n| F(n-1) |     [ | 1 0 0 | ]              | F(1) |\n| F(n-2) |     [ | 0 1 0 | ]              | F(0) |\n````\n\n##### Java Implementation\nTime Complexity: O(logN)\nAuxiliary Space: O(logN) \n````java\n// JAVA program to find value of f(n) where\n// f(n) is defined as\n// F(n) = F(n-1) + F(n-2) + F(n-3), n >= 3\n// Base Cases :\n// F(0) = 0, F(1) = 1, F(2) = 1\n\nclass Matrix {\n\t\n\t// A utility function to multiply two\n\t// matrices a[][] and b[][].\n\t// Multiplication result is\n\t// stored back in b[][]\n\tstatic void multiply(int a[][], int b[][])\n\t{\n\t\t// Creating an auxiliary matrix to\n\t\t// store elements of the\n\t\t// multiplication matrix\n\t\tint mul[][] = new int[3][3];\n\t\tfor (int i = 0; i < 3; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tmul[i][j] = 0;\n\t\t\t\tfor (int k = 0; k < 3; k++)\n\t\t\t\t\tmul[i][j] += a[i][k]\n\t\t\t\t\t\t\t\t* b[k][j];\n\t\t\t}\n\t\t}\n\t\n\t\t// storing the multiplication\n\t\t// result in a[][]\n\t\tfor (int i=0; i<3; i++)\n\t\t\tfor (int j=0; j<3; j++)\n\t\t\t\n\t\t\t\t// Updating our matrix\n\t\t\t\ta[i][j] = mul[i][j];\n\t}\n\t\n\t// Function to compute F raise to\n\t// power n-2.\n\tstatic int power(int F[][], int n)\n\t{\n\t\tint M[][] = {{1, 1, 1}, {1, 0, 0},\n\t\t\t\t\t\t\t{0, 1, 0}};\n\t\n\t\t// Multiply it with initial values\n\t\t// i.e with F(0) = 0, F(1) = 1,\n\t\t// F(2) = 1\n\t\tif (n == 1)\n\t\t\treturn F[0][0] + F[0][1];\n\t\n\t\tpower(F, n / 2);\n\t\n\t\tmultiply(F, F);\n\t\n\t\tif (n%2 != 0)\n\t\t\tmultiply(F, M);\n\t\n\t\t// Multiply it with initial values\n\t\t// i.e with F(0) = 0, F(1) = 1,\n\t\t// F(2) = 1\n\t\treturn F[0][0] + F[0][1] ;\n\t}\n\t\n\t// Return n'th term of a series defined\n\t// using below recurrence relation.\n\t// f(n) is defined as\n\t// f(n) = f(n-1) + f(n-2) + f(n-3), n>=3\n\t// Base Cases :\n\t// f(0) = 0, f(1) = 1, f(2) = 1\n\tstatic int findNthTerm(int n)\n\t{\n\t\tint F[][] = {{1, 1, 1}, {1, 0, 0},\n\t\t\t\t\t\t\t\t{0, 1, 0}} ;\n\t\n\t\treturn power(F, n-2);\n\t}\n\t\n\t// Driver code\n\tpublic static void main (String[] args) {\n\t\t\n\t\tint n = 5;\n\t\t\n\t\tSystem.out.println(\"F(5) is \"\n\t\t\t\t\t\t+ findNthTerm(n));\n\t}\n}\n\n//This code is contributed by vt_m.\n\n````\n\n\n## 6. Combinatorics\n\nCombinatorial mathematics, the field of mathematics concerned with problems of selection, arrangement, and operation within a finite or discrete system. Included is the closely related area of combinatorial geometry.\n\nOne of the basic problems of combinatorics is to determine the number of possible configurations (e.g., graphs, designs, arrays) of a given type. Even when the rules specifying the configuration are relatively simple, enumeration may sometimes present formidable difficulties. The mathematician may have to be content with finding an approximate answer or at least a good lower and upper bound.\n\nIn mathematics, generally, an entity is said to “exist” if a mathematical example satisfies the abstract properties that define the entity. In this sense it may not be apparent that even a single configuration with certain specified properties exists. This situation gives rise to problems of existence and construction. There is again an important class of theorems that guarantee the existence of certain choices under appropriate hypotheses. Besides their intrinsic interest, these theorems may be used as existence theorems in various combinatorial problems.\n\n\n*Here we will be discussing a few problems that can be implemented using the concepts of Combinatorics*\n\n#### Generating Permutations\n\nA permutation is an act of rearranging a sequence in such a way that it has a different order.\n\nAs we know from math, for a sequence of n elements, there are n! different permutations. n! is known as a factorial operation:\n\n```\nn! = 1 * 2 * … * n\n```\n\n#### Algorithm\nIt's a good idea to think about generating permutations in a recursive manner. Let's introduce the idea of the state. It will consist of two things: the current permutation and the index of the currently processed element.\n\nThe only work to do in such a state is to swap the element with every remaining one and perform a transition to a state with the modified sequence and the index increased by one.\n\nLet's illustrate with an example.\n\nWe want to generate all permutations for a sequence of four elements – [1, 2, 3, 4]. So, there will be 24 permutations. The illustration below presents the partial steps of the algorithm:\n\n![image](images/permutation.png)\n\nEach node of the tree can be understood as a state. The red digits across the top indicate the index of the currently processed element. The green digits in the nodes illustrate swaps.\n\nSo, we start in the state [1, 2, 3, 4] with an index equal to zero. We swap the first element with each element – including the first, which swaps nothing – and move on to the next state.\n\n##### Java Impelementation\n\n```java\nprivate static void permutationsInternal(List<Integer> sequence, List<List<Integer>> results, int index) {\n    if (index == sequence.size() - 1) {\n        permutations.add(new ArrayList<>(sequence));\n    }\n\n    for (int i = index; i < sequence.size(); i++) {\n        swap(sequence, i, index);\n        permutationsInternal(sequence, permutations, index + 1);\n        swap(sequence, i, index);\n    }\n}\n```\n\n### Generating the Powerset of a Set\n\nPowerset (or power set) of set S is the set of all subsets of S including the empty set and S itself\n\nSo, for example, given a set [a, b, c], the powerset contains eight subsets:\n\n```\n[]\n\n[a]\n\n[b]\n\n[c]\n\n[a, b]\n\n[a, c]\n\n[b, c]\n\n[a, b, c]\n```\n\n##### Java Implementation\n```java\nprivate static void powersetInternal(\n  List<Character> set, List<List<Character>> powerset, List<Character> accumulator, int index) {\n    if (index == set.size()) {\n        results.add(new ArrayList<>(accumulator));\n    } else {\n        accumulator.add(set.get(index));\n        powerSetInternal(set, powerset, accumulator, index + 1);\n        accumulator.remove(accumulator.size() - 1);\n        powerSetInternal(set, powerset, accumulator, index + 1);\n    }\n}\n```\n\n#### Generating Combinations\nNow, it's time to tackle combinations. We define it as follows:\n\n*k-combination of a set S is a subset of k distinct elements from S, where an order of items doesn't matter*\n\nThe number of k-combinations is described by the binomial coefficient:\n\n![image](images/combination_equation.png)\n\nSo, for example, for the set [a, b, c] we have three 2-combinations:\n\n```\n[a, b]\n\n[a, c]\n\n[b, c]\n```\n\n##### Java Implementation\n\n``` java\nprivate static void combinationsInternal(\n  List<Integer> inputSet, int k, List<List<Integer>> results, ArrayList<Integer> accumulator, int index) {\n  int needToAccumulate = k - accumulator.size();\n  int canAcculumate = inputSet.size() - index;\n\n  if (accumulator.size() == k) {\n      results.add(new ArrayList<>(accumulator));\n  } else if (needToAccumulate <= canAcculumate) {\n      combinationsInternal(inputSet, k, results, accumulator, index + 1);\n      accumulator.add(inputSet.get(index));\n      combinationsInternal(inputSet, k, results, accumulator, index + 1);\n      accumulator.remove(accumulator.size() - 1);\n  }\n} \n```\n"
  },
  {
    "path": "lessons/num-two.md",
    "content": "---\npath: \"/num-two\"\ntitle: \"Number Theory Part-B\"\norder: \"10D\"\nsection: \"Maths for DSA\"\ndescription: \"learn maths required in DSA\"\n---\n"
  },
  {
    "path": "lessons/operators.md",
    "content": "---\npath: \"/operators\"\ntitle: \"Operators in Java\"\norder: \"3B\"\nsection: \"Learn Java\"\ndescription: \"Learn java\"\n---\n\nOperators are symbols that tell the compiler to perform some specfic operations.\nIn JAVA, there are many operators, and they are grouped into several categories.\nWe are going to learn some of the important operators only. You will see these operators in most of the section and this will cover almost every problem you will encounter in your programming journey.\n\nOk, So there are basically 6 categories of operators:\n\n- Arithmetic Operators\n- Relational Operators\n- Logical Operators\n- Assignment Operators\n- Bitwise Operators\n- Other Operators\n\nIn the last one _Other Operators_ I have put the miscellaneous operators, which are not grouped into any of the above categories. Ok so let's learn them one by one.\n\n## **Arithmetic Operators**\n\nArithmetric operators are used to perform arithmetic operations. They are used to perform addition, subtraction, multiplication, division, modulus, exponentiation, and negation. That's all you need to know. It has some types:\n\n- `Binary Operator`: used to perform addition(**+**), subtraction(**-**), multiplication(**\\***), division(**/**), modulus(**%**), exponentiation(**\\*\\***) etc.\n- `Unary Operator`: used to perform operation using the single operand. like\n  Incrementer(**++**), Decrementer(**--**), negation(**!**), Complement(**~**), etc.\n\nOk so let's learn about the incrementer and decrementer operators now because they are very important.\n\n### Incrementer and Decrementer Operators/ Unary Operators\n\nIn Java there are two types of incrementer and decrementer operators:\n\n- **Incrementer Operator**: used to increment the value of the operand by 1.\n- **Decrementer Operator**: used to decrement the value of the operand by 1.\n\n---\n\nThere are two types to each of them:\n\n- **Prefix Incrementer Operator**: used to increment the value of the operand by 1.\n- **Postfix Incrementer Operator**: used to increment the value of the operand by 1.\n- **Prefix Decrementer Operator**: used to decrement the value of the operand by 1.\n- **Postfix Decrementer Operator**: used to decrement the value of the operand by 1.\n  now do some question based on the above operators.\n\n| **Operators**     | **Representation** | **Description**                                                                                            | **Example**                                                                     |\n| ----------------- | ------------------ | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |\n| Prefix Increment  | **++x**            | Increment `x` instantly                                                                                    | int x = 10; int y; y = ++x; `System.out.println(x+\" , \"+y)` **Output: 11 , 11** |\n| Postfix Increment | **x++**            | Current value of `x` is preserved temporarily. `x` will get incremented before next statement is executed. | int x = 10; int y; y = x++; `System.out.println(x+\" , \"+y)` **Output: 11 , 10** |\n| Prefix Decrement  | **--x**            | Decrement `x` instantly                                                                                    | int x = 10; int y; y = --x; `System.out.println(x+\" , \"+y)` **Output: 9 , 9**   |\n| Postfix Decrement | **x--**            | Current value of `x` is preserved temporarily. `x` will get decremented before next statement is executed. | int x = 10; int y; y = x--; `System.out.println(x+\" , \"+y)` **Output: 9 , 10**  |\n\n## **Relational Operators**\n\nRelational operators are used to compare the values of two operands. They are used to compare the values of two operands using the following operators:\n\n- `== or = =`: used to compare two operands if they are equal. It gives true if both the operands have equal values.\n- `!= or ! =`: used to compare two operands if they are not equal. It gives true if both the operands have not same values.\n- `<`: used to compare two operands if the first operand is less than the second operand. It gives true if the first operand is less than the second operand.\n- `>`: used to compare two operands if the first operand is greater than the second operand. It gives true if the first operand is greater than the second operand.\n- `<=`: used to compare two operands if the first operand is less than or equal to the second operand. It gives true if the first operand is less than or equal to the second operand.\n- `>=`: used to compare two operands if the first operand is greater than or equal to the second operand. It gives true if the first operand is greater than or equal to the second operand.\n\n## **Logical Operators**\n\nLogical operators are used to perform logical operations. They are used to perform the following operations:\n\n- `&&` and `&`: Java unlike many other languages has two AND operators to perform logical AND operation. It returns true if both the operands (being compared) have a truthy value. Even though both the `&` and `&&` operators perform the same AND operation; the `&&` operator is a logical operator and it can improve the efficiency of your code since it evaluates the second expression only if the first expression is true unlike the bitwise `&` operator which evaluates the second expression nonetheless.\n\n- `||` and `|`: OR is used to perform logical OR operation. It returns true if either of the operands have a truthy value. The difference between `|` and `||` is that the `|` operator is a bitwise operator and it compares each operand bitwise whereas the `||` operator is the logical OR operator. It operates on both the operands and returns true if either of the operands have a truthy value.\n- `!`: NOT used to perform logical NOT operation. It gives true if the operand has false value.\n\nlet's see an example:\n\n```Java\n   // program to find whether a number is divible by both 3 and 5\n   // or divisible by only one of them\nimport java.util.Scanner;\npublic class Main {\n\tpublic static void main(String[] args)\n      {\n        Scanner sc = new Scanner(System.in);\n        System.out.println(\"Enter a number: \");\n        int a = sc.nextInt();\n\n        if (a % 3 == 0 && a % 5 == 0)\n            System.out.println(\"The number is divisible by both 3 and 5\");\n        else if (a % 3 == 0 || a % 5 == 0)\n            System.out.println(\"The numbers is divisible by only one of them\");\n        else\n            System.out.println(\"The numbers is not divisible by any of them\");\n      }\n}\n```\n\nlet's see the explanation:\n\n- `a%3==0 && a%5==0`: it checks whether the value of `a` is divisible by both 3 and 5. if its divisible by both 3 and also divisible by 5 then it gives true. that's why we use `&&` operator here.\n- `a%3==0 || a%5==0`: it checks whether the value of `a` is divisible by either 3 or 5. if its divisible by 3 or 5 then it gives true. if its divisible by 5 then it gives true. that's why we use `||` operator here.\n- but `a` is neither divisible by 3 nor divisible by 5. so it gives false. so we'll be priting `the numbers is not divisible by any of them`.\n\n## **Assignment Operators**\n\nAssignment operators are used to assign the value of one operand to another. They are used to assign the value of one operand to another using the following operators:\n\n- `=`: used to assign the value of one operand to another. It assigns the value of the right operand to the left operand.\n- `+=`: used to add the value of one operand to another. It adds the value of the right operand to the left operand and assigns the result to the left operand.\n- `-=`: used to subtract the value of one operand from another. It subtracts the value of the right operand from the left operand and assigns the result to the left operand.\n- `*=`: used to multiply the value of one operand with another. It multiplies the value of the right operand with the left operand and assigns the result to the left operand.\n- `/=`: used to divide the value of one operand with another. It divides the value of the right operand with the left operand and assigns the result to the left operand.\n- `%=`: used to find the remainder of the division of one operand with another. It divides the value of the right operand with the left operand and assigns the remainder to the left operand.\n\n## **Bitwise Operators**\n\nBitwise operators are operatr on bits and perform bit-by-bit operations. They are used to perform the following operations:\n\n- `&`: **AND operator**. It gives the value of the left operand if it is set in the right operand.\n\neg: let a=5, b=6 then a&b==?\n| Variable | Value | Binary |\n|:--------:|:-----:|:------:|\n| a | 5 | 0101 |\n| b | 6 | 0110 |\n| a&b | 4 | 0100 |\n\n<br>\n\n- `|`: **OR operator**. It gives the value of the left operand if it is set in the right operand.\n\neg: let a=5, b=6 then a|b==?\n| Variable | Value | Binary |\n|:--------:|:-----:|:------:|\n| a | 5 | 0101 |\n| b | 6 | 0110 |\n| a|b | 7 | 0111 |\n\n<br>\n\n- `^`: **XOR operator**. It gives the value of the left operand if it is set in the right operand.\n\neg: let a=5, b=6 then a^b==?\n| Variable | Value | Binary |\n|:--------:|:-----:|:------:|\n| a | 5 | 0101 |\n| b | 6 | 0110 |\n| a^b | 3 | 0011 |\n\n- `~`: **NOT operator**. It gives the value of the left operand if it is set in the right operand.\n\neg: let a=5, ~a==?\n| Variable | Value | Binary |\n|:--------:|:-----:|:------:|\n| a | 5 | 0101 |\n| ~a | | 1010 |\n\n- `<<`: **LEFT SHIFT operator**. It shifts the bits of the left operand to the left and assigns the result to the left operand.\n\n```js\neg: let 8 << 1 == ?\n  (01000) << 1 == (10000) ==> 16\n```\n\n- `>>`: **RIGHT SHIFT operator**. It shifts the bits of the left operand to the right and assigns the result to the left operand.\n\n```js\neg: let 8 >> 1 == ?\n  (1000) >> 1 == (0100) ==> 4\n```\n\nhere one thing to keep in mind that `>>` operator shifts the bits to the right and `<<` shifts the bits to the left. there is a way to find right shift and left shift of a number.\n\n```java\nRight Shift --> a >> n ==> a * 2^n\nLeft Shift --> a << n ==> a / 2^n\n```\n\n## **Other Operators**\n\nThis category contains the following operators:\n\n- `condition ? true_expression : false_expression`: it evaluates the true_expression if the condition is true and false_expression if the condition is false.\n\n```java\n    // syntax\n    // variable = Expression1 ? Expression2 : Expression3;\n\n  public class Main {\n    public static void main(String[] args) {\n        int num = 15;\n        String msg = num > 10 ? \"Number is greater than 10\" : \"Number is less than or equal to 10\";\n        System.out.println(msg);\n    }\n}\n\n```\n\n- `typecasting`: it converts the value of the operand to the type of the right operand.\neg:\n```java\npublic class Main {\n    public static void main(String[] args) {\n        char ch = 'a';\n        int typecasted_character = (int) 'a';\n        System.out.println(ch);\n        System.out.println(typecasted_character);\n    }\n}\n```\n## **Operators Precedence**\n\nOperators Precedence is the order in which the operators are evaluated. Below is the precedence of the operators.\n![precedence](./images/precedence_java.jpg)\n\n```java\npublic class Main {\n\tpublic static void main(String[] args) {\n\t  int a = 2, b = 10, c = 0, d = 40, e = 40, f = 30;\n \n        // precedence rules for arithmetic operators.\n        // (* = / = %) > (+ = -)\n        // prints a+(b/d)\n        System.out.println(\"a+b/d = \" + (a + b / d));\n \n        // if same precendence then associative\n        // rules are followed (evaluation occurs by the order \n        //in which the operators are present from left to right)\n        // e/f -> b*d -> a+(b*d) -> a+(b*d)-(e/f)\n        System.out.println(\"a+b*d-e/f = \"\n                           + (a + b * d - e / f));\n\t}\n}\n```\nOutput:\n```\na+b/d = 2\na+b*d-e/f = 401\n```\n"
  },
  {
    "path": "lessons/practise-question.md",
    "content": "---\npath: \"/practise-question\"\ntitle: \"Practise Questions\"\norder: \"5I\"\nsection: \"Searching & Sorting\"\ndescription: \"learn Searching & sorting algorithms\"\n---\n\n**Q1) Move All Zeros to End of an Array**<br>\nYou have been given a random integer array of size N. You have been required to push all the zeros that are present in the array to the end of it such that the relative order of the non-zero elements should be maintained.\n\n```java\nSample Input/Output\n​Input:  arr[]={3,0,1,5,0,5}\nOutput: arr[]={3,1,5,5,0,0}\n```\n\n## Approach\n\nBefore we discuss the approach for this question let’s see what exactly the question requires us to do. It seems that we have to push all the 0s in the array towards the end of the array. It can also be looked at as pushing all the non-zero elements in the array towards the beginning of the array.<br>\nFirst, traverse the whole array and initialize a variable count whose value should be equal to zero. Now, check each element of the array whether it is equal to zero or not. If the element is not equal to zero,put that element at the count position of the array(arr[count]) and increment the value of count by one.<br>\nNow, after traversing the whole array fill the remaining positions of the array with zeroes.\n\n## Program\n\n```java\npackage main;\nimport java.util.*;\npublic class Main {\n\tpublic static void pushZerosToEnd(int[] arr, int n) {\n        int count=0;\n        for(int i=0;i<arr.length;i++)\n        {\n            if(arr[i]!=0)\n            {\n                arr[count++]=arr[i];\n            }\n        }\n        for(int j=count;j<n;j++)\n        {\n            arr[count++]=0;\n        }}\n\tpublic static void main(String[] args) {\n\t\tint arr[]= {3,0,5,4,0,2,2};\n\t\tpushZerosToEnd(arr,7);\n\t\tfor(int i=0;i<7;i++)\n\t\t{\n\t          System.out.print(arr[i]);\n\t\t}}\n}\n```\n\n```java\nOutput\n3542200\n```\n\n## Explanation\n\n- Initialize a variable count with a value equal to zero.<br>\n- Make a function named pushZeroToEnd and input an array.<br>\n- Traverse through the array and check each element whether it is equal to zero or not.<br>\n- If the element is not equal to zero, put the element at the countth position of the array.<br>\n- Increase the value of count by 1.<br>\n- At last, fill the remaining positions of the array with 0.<br>\n\n## Time Complexity\n\nSince we will be traversing the whole array twice therefore the time complexity of algorithm would be:\n\n- **Time complexity of first loop O(N) + Time complexity of second loop O(N) = O(N)**,\n  where n is number of elements in input array.\n"
  },
  {
    "path": "lessons/print-patterns.md",
    "content": "---\npath: \"/print-patterns\"\ntitle: \"Printing Patterns\"\norder: \"4C\"\nsection: \"Arrays\"\ndescription: \"learn Arrays\"\n---\n\nJava pattern program enhances the coding skill, logic, and looping concepts. It is mostly asked in Java interview to check the logic and thinking of the programmer. We can print a Java pattern program in different designs. To learn the pattern program, we must have a deep knowledge of the Java loop, such as for loop do-while loop. In this section, we will learn how to print a pattern in Java.\n\n## **We have classified the Java pattern program into three categories:**\n- Star Pattern\n- Number Pattern\n- Character Pattern\n\n### **Here we explain each category with examples :**\n\n## **Star Pattern :**\n\n_**Qn1 : Right Triangle Star Pattern**_\n\n### **Code :**\n```java\npublic class RightTriangleStarPattern   \n{   \n    public static void main(String args[])   \n    {   \n        //i for rows and j for columns      \n        //row denotes the number of rows you want to print  \n        int i, j, row = 4;   \n        //outer loop for rows  \n        for(i=0; i<row; i++)   \n        {   \n            //inner loop for columns  \n            for(j=0; j<=i; j++)   \n            {   \n                //prints stars   \n                System.out.print(\"* \");   \n            }   \n            //throws the cursor in a new line after printing each line  \n            System.out.println();   \n        }   \n    }   \n}  \n```\n### **Output :**\n```\n*  \n* *  \n* * *  \n* * * * \n```\n\n### **Explanation & Approch of Solution :**\nWhenever you design logic for a pattern program, first draw that pattern in the blocks, as we have shown in the following image. The figure presents a clear look of the pattern.\n\n\n![Img](./images/pattern-print.png)\n\nIn the above pattern, the row is denoted by i and the column is denoted by j. We see that the first row prints only a star. The second-row prints two stars, and so on. The colored blocks print the spaces.\n\n### **Iteration-1 :**\n```\nFor i=0, 0<4 (true)\nFor j=0, j<=0 (true)\n```\nThe first print statement prints a star at the first row and the second println statement prints the spaces and throws the cursor at the next line.\n\n**Output Console :**\n```\n*\n```\n\n### **Iteration-2 :**\n```\nFor i=1, 1<4 (true)\nFor j=1, 1<=1 (true)\n```\nThe first print statement prints two stars at the second row and the second println statement prints the spaces and throws the cursor at the next line.\n\n**Output Console :**\n```\n*\n* *\n```\n\n### **Iteration-3 :**\n```\nFor i=2, 2<4 (true)\nFor j=2, 2<=2 (true)\n```\nThe first print statement prints three stars at the third row and the second println statement prints the spaces and throws the cursor at the next line.\n\n**Output Console :**\n```\n*\n* *\n* * *\n```\n\n### **Iteration-4 :**\n```\nFor i=3, 3<4 (true)\nFor j=3, 3<=3 (true)\n```\nThe first print statement prints four stars at the fourth row and the second println statement prints the spaces and throws the cursor at the next line.\n\n**Output Console :**\n```\n*\n* *\n* * *\n* * * *\n```\n**Now the value of i and j is increased to 4.**\n\n```\nFor i=4, 4<4 (false)\n```\nThe execution of the program will terminate when the value of i will be equal to the number of rows.\n\n\n## **Number Pattern :**\n\n_**Qn1 : Right Triangle Number Pattern**_\n\n### **Code :**\n```java\npublic class RightTriangleNumberPattern   \n{   \n    public static void main(String[] args)\n    {\n        //i for rows and j for columns      \n        //row denotes the number of rows you want to print  \n        int i, j, row = 4;\n        //outer loop for rows\n        for (i = 1; i <= row; i++)\n        {\n            //inner loop for columns\n            for (j = 1; j <= i; j++)\n            {\n                //print the current value of j\n                System.out.print(j + \" \");\n            }\n            //throws the cursor in a new line after printing each line\n            System.out.println();\n        }\n    } \n}  \n```\n### **Output :**\n```\n1 \n1 2 \n1 2 3 \n1 2 3 4 \n```\n\n\n## **Character Pattern :**\n\n_**Qn1 : Right Triangle Character Pattern**_\n\n### **Code :**\n```java\npublic class RightTriangleCharacterPattern   \n{   \n    public static void main(String[] args)\n    {\n        //i for rows and j for columns      \n        //row denotes the number of rows you want to print  \n        int i, j, row = 4;\n        //declear alphabet variable to print the value \n        int alphabet = 65;\n        //outer loop for rows\n        for (i = 1; i <= row; i++)\n        {\n            //inner loop for columns\n            for (j = 1; j <= i; j++)\n            {\n                //print the current value of alphabet in character form\n                System.out.print((char) alphabet + \" \");\n            }\n            //increment the alphabet variable by 1\n            alphabet++;\n            //throws the cursor in a new line after printing each line\n            System.out.println();\n        }\n    } \n}  \n```\n### **Output :**\n```\nA \nB B \nC C C \nD D D D \n```\n<br>\nHappy Learning 👍"
  },
  {
    "path": "lessons/properties.md",
    "content": "---\npath: \"/properties\"\ntitle: \"Properties of OOP\"\norder: \"11C\"\nsection: \"Object Oriented Programming\"\ndescription: \"complete introduction to object oriented programming\"\nicon: \"object-ungroup\"\n---\n"
  },
  {
    "path": "lessons/quicksort.md",
    "content": "---\npath: \"/quicksort\"\ntitle: \"Quick Sort\"\norder: \"8F\"\nsection: \"Recursion\"\ndescription: \"learn Recursion from scratch\"\n---\n\nQuick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into smaller arrays. A large array is partitioned into two arrays one of which holds values smaller than the specified value, say pivot, based on which the partition is made and another array holds values greater than the pivot value.\nQuicksort partitions an array and then calls itself recursively twice to sort the two resulting subarrays. This algorithm is quite efficient for large-sized data sets as its average and worst-case complexity are O(n^2), respectively.\n\n\nQuicksort picks an element as pivot, and then it partitions the given array around the picked pivot element. In quick sort, a large array is divided into two arrays in which one holds values that are smaller than the specified value (Pivot), and another array holds the values that are greater than the pivot.\n\n\nAfter that, left and right sub-arrays are also partitioned using the same approach. It will continue until the single element remains in the sub-array.\n\n## Choosing the Pivot\nPicking a good pivot is necessary for the fast implementation of quicksort. However, it is typical to determine a good pivot. Some of the ways of choosing a pivot are as follows:\n\n- Pivot can be random, i.e. select the random pivot from the given array.\n- Pivot can either be the rightmost element of the leftmost element of the given array.\n- Select median as the pivot element.\n- Algorithm\n\n## Quick Sort Algorithm\n\n### Algorithm:\n```Java\nQUICKSORT (array A, start, end)     \n{  \nif (start < end)     \n {  \n p = partition(A, start, end)  \n QUICKSORT (A, start, p - 1)    \n QUICKSORT (A, p + 1, end)    \n }   \n}  \n```\n\n## Example for better understanding\n\nLet the elements of array are -\n\n```\n24 9 29 14 19 27\n```\n\nSo, in this case, a[left] = 24, a[right] = 27 and a[pivot] = 24.\nSince, pivot is at left, so algorithm starts from right and move towards left.\nSo, a[pivot] < a[right], so algorithm moves forward one position towards left.\nAlso after this, a[left] = 24, a[right] = 19, and a[pivot] = 24.\nBecause, a[pivot] > a[right], so, algorithm will swap a[pivot] with a[right], and pivot moves to right.\n```\n19 9 29 14 24 27\n```\n\nNow, a[left] = 19, a[right] = 24, and a[pivot] = 24. Since, pivot is at right, so algorithm starts from left and moves to right.\nAs a[pivot] > a[left], so algorithm moves one position to right .So, a[left] = 9, a[right] = 24, and a[pivot] = 24. As a[pivot] > a[left], so algorithm moves one position to right.\n```\n19 9 24 14 29 27\n```\n\nSince, pivot is at left, so algorithm starts from right, and move to left. Now, a[left] = 24, a[right] = 29, and a[pivot] = 24. As a[pivot] < a[right], so algorithm moves one position to left.So, a[pivot] = 24, a[left] = 24, and a[right] = 14. As a[pivot] > a[right]. so, swap a[pivot] and a[right], now pivot is at right.\n```\n19 9 14 24 29 27\n```\n\nNow, a[pivot] = 24, a[left] = 14, and a[right] = 24. Pivot is at right, so the algorithm starts from left and move to right. a[pivot] = 24, a[left] = 24, and a[right] = 24. So, pivot, left and right are pointing the same element. It represents the termination of procedure.Element 24, which is the pivot element is placed at its exact position.\nElements that are right side of element 24 are greater than it, and the elements that are left side of element 24 are smaller than it.\nAlso, in a similar manner, quick sort algorithm is separately applied to the left and right sub-arrays. After sorting gets done, the array will be:\n```\n9 14 19 24 27 29\n```\n\n## Implementation of Quick Sort\n\n```Java\n// Java implementation of QuickSort\nimport java.io.*;\n\nclass QuickSort{\n\t\n// A utility function to swap two elements\nstatic void swap(int[] arr, int i, int j)\n{\n\tint temp = arr[i];\n\tarr[i] = arr[j];\n\tarr[j] = temp;\n}\n\nstatic int partition(int[] arr, int low, int high)\n{\n\t\n\t// pivot\n\tint pivot = arr[high];\n\t\n\t// Index of smaller element and\n\t// indicates the right position\n\t// of pivot found so far\n\tint i = (low - 1);\n\n\tfor(int j = low; j <= high - 1; j++)\n\t{\n\t\t\n\t\t// If current element is smaller\n\t\t// than the pivot\n\t\tif (arr[j] < pivot)\n\t\t{\n\t\t\t\n\t\t\t// Increment index of\n\t\t\t// smaller element\n\t\t\ti++;\n\t\t\tswap(arr, i, j);\n\t\t}\n\t}\n\tswap(arr, i + 1, high);\n\treturn (i + 1);\n}\n\nstatic void quickSort(int[] arr, int low, int high)\n{\n\tif (low < high)\n\t{\n\t\t\n\t\t// pi is partitioning index, arr[p]\n\t\t// is now at right place\n\t\tint pi = partition(arr, low, high);\n\n\t\t// Separately sort elements before\n\t\t// partition and after partition\n\t\tquickSort(arr, low, pi - 1);\n\t\tquickSort(arr, pi + 1, high);\n\t}\n}\n\n// Function to print an array\nstatic void printArray(int[] arr, int size)\n{\n\tfor(int i = 0; i < size; i++)\n\t\tSystem.out.print(arr[i] + \" \");\n\t\t\n\tSystem.out.println();\n}\n\n// Driver Code\npublic static void main(String[] args)\n{\n\tint[] arr = { 10, 7, 8, 9, 1, 5 };\n\tint n = arr.length;\n\t\n\tquickSort(arr, 0, n - 1);\n\tSystem.out.println(\"Sorted array: \");\n\tprintArray(arr, n);\n}\n}\n\n```\n\n### Output\n\n```\nSorted array: \n1 5 7 8 9 10 \n````\n\n## Time Complexity and Space Complexity\n\n### Time Complexity\n\n- **Best Case Complexity:** In Quicksort, the best-case occurs when the pivot element is the middle element or near to the middle element. The best-case time complexity of quicksort is O(n*logn).\n- **Average Case Complexity:** It occurs when the array elements are in jumbled order that is not properly ascending and not properly descending. The average case time complexity of quicksort is O(n*logn).\n- **Worst Case Complexity:** In quick sort, worst case occurs when the pivot element is either greatest or smallest element. Suppose, if the pivot element is always the last element of the array, the worst case would occur when the given array is sorted already in ascending or descending order. The worst-case time complexity of quicksort is O(n2).\n\n### Space Complexity\n- **Space Complexity:** The space complexity of quicksort is O(n*logn).\n\n## The Uses and Real-time application of Quicksort\n- Commercial Computing is used in various government and private organizations for the purpose of sorting various data like sorting files by name/date/price, sorting of students by their roll no., sorting of account profile by given id, etc.\n- The sorting algorithm is used for information searching and as Quicksort is the fastest algorithm so it is widely used as a better way of searching.\n- It is used everywhere where a stable sort is not needed.\n- Quicksort is a cache-friendly algorithm as it has a good locality of reference when used for arrays.\n- It is tail -recursive and hence all the call optimization can be done.\n- It is an in-place sort that does not require any extra storage memory.\n- It is used in operational research and event-driven simulation.\n- Numerical computations and in scientific research, for accuracy in calculations most of the efficiently developed algorithm uses priority queue and quick sort is used for sorting.\n\n## 3 way Quick Sort\nThe idea of 3 way Quick Sort is to process all occurrences of the pivot and is based on Dutch National Flag algorithm. \n\nThe three-way quicksort is similar, but there are three sections. array arr[1 to n] is divided into three parts.\n\n- arr[1 to i]\n- arr[i + 1, j]\n- arr[j + 1, n]\n\n## Implementaion of 3 way Quick Sort\n\n```Java\npublic class QuickSort3 {\n   \n    public void sort(int[] A) {\n        if (A == null || A.length <= 1) return;\n        quicksort(A, 0, A.length - 1);\n    }\n\n    private void quicksort(int[] A, int start, int end) {\n        if (start >= end)   return;\n\n        // choose the middle element as the pivot\n        int mid = start + (end - start) / 2;\n        int pivot = A[mid];\n\n        // move pivot to the front\n        swap(A, start, mid);\n\n        // lt: index to store next element < pivot\n        // gt: index to store next element > pivot\n        int lt = start, gt = end, i = start + 1;\n        // 1: i <= gt not i <= end\n        while (i <= gt) {\n            // move elements < pivot to the front\n            if (A[i] < pivot)    swap(A, i++, lt++);\n            // NOTE: don't move i, as we don't know whether value of the element\n            // from the end that got swap to current i and we need to check it\n            else if (A[i] > pivot)    swap(A, i, gt--);\n            // keep elements == pivot on the same positition\n            else    i++;\n        }\n        quicksort(A, start, lt - 1);\n        quicksort(A, gt + 1, end);\n    }\n\n    private void swap(int[] A, int i, int j) {\n        int temp = A[i];\n        A[i] = A[j];\n        A[j] = temp;\n    }\n}\n```\n\n\n"
  },
  {
    "path": "lessons/radixsort.md",
    "content": "---\npath: \"/radixsort\"\ntitle: \"Radix Sort\"\norder: \"5G\"\nsection: \"Searching & Sorting\"\ndescription: \"learn radix sort algorithms\"\n---\n\nRadix sort is a sorting algorithm that sorts the elements by first grouping the individual digits of the same place value. Then, sort the elements according to their increasing/decreasing order.\n\nSuppose, we have an array of 8 elements. First, we will sort elements based on the value of the unit place. Then, we will sort elements based on the value of the tenth place. This process goes on until the last significant place.\n\n## Algorithm\n\n1. Find the largest element in the array, i.e. max. Let X be the number of digits in max. X is calculated because we have to go through all the significant places of all elements.\n\nfor example in the array [121, 432, 564, 23, 1, 45, 788], we have the largest number 788. It has 3 digits. Therefore, the loop should go up to hundreds place (3 times).\n\n2. Now, go through each significant place one by one.\n   Use any stable sorting technique to sort the digits at each significant place. We have used counting sort for this.\n\nSort the elements based on the unit place digits (X=0).\n\n3. Now, sort the elements based on digits at tens place.\n\n4. Finally, sort the elements based on the digits at hundreds place.\n\n## Code Implementation\n\n```java\n// Radix Sort in Java Programming\nimport java.util.Arrays;\n\nclass RadixSort {\n\n  // Using counting sort to sort the elements in the basis of significant places\n  void countingSort(int array[], int size, int place) {\n    int[] output = new int[size + 1];\n    int max = array[0];\n    for (int i = 1; i < size; i++) {\n      if (array[i] > max)\n        max = array[i];\n    }\n    int[] count = new int[max + 1];\n\n    for (int i = 0; i < max; ++i)\n      count[i] = 0;\n\n    // Calculate count of elements\n    for (int i = 0; i < size; i++)\n      count[(array[i] / place) % 10]++;\n\n    // Calculate cumulative count\n    for (int i = 1; i < 10; i++)\n      count[i] += count[i - 1];\n\n    // Place the elements in sorted order\n    for (int i = size - 1; i >= 0; i--) {\n      output[count[(array[i] / place) % 10] - 1] = array[i];\n      count[(array[i] / place) % 10]--;\n    }\n\n    for (int i = 0; i < size; i++)\n      array[i] = output[i];\n  }\n\n  // Function to get the largest element from an array\n  int getMax(int array[], int n) {\n    int max = array[0];\n    for (int i = 1; i < n; i++)\n      if (array[i] > max)\n        max = array[i];\n    return max;\n  }\n\n  // Main function to implement radix sort\n  void radixSort(int array[], int size) {\n    // Get maximum element\n    int max = getMax(array, size);\n\n    // Apply counting sort to sort elements based on place value.\n    for (int place = 1; max / place > 0; place *= 10)\n      countingSort(array, size, place);\n  }\n\n  // Driver code\n  public static void main(String args[]) {\n    int[] data = { 121, 432, 564, 23, 1, 45, 788 };\n    int size = data.length;\n    RadixSort rs = new RadixSort();\n    rs.radixSort(data, size);\n    System.out.println(\"Sorted Array in Ascending Order: \");\n    System.out.println(Arrays.toString(data));\n  }\n}\n```\n\n## Complexity analysis\n\nTime Complexity\n\nBest Case: **O(n+k)**\n\nAverage Case: **O(n+k)**\n\nWorst Case: **O(n+k)**\n\nSpace Complexity: **O(max)**\n\nStability: **Yes**\n\nFor the radix sort that uses counting sort as an intermediate stable sort, the time complexity is **O(d(n+k)).**\nHere, d is the number cycle and O(n+k) is the time complexity of counting sort.\nThus, radix sort has linear time complexity which is better than O(nlog n) of comparative sorting algorithms.\nIf we take very large digit numbers or the number of other bases like 32-bit and 64-bit numbers then it can perform in linear time however the intermediate sort takes large space.\nThis makes radix sort space inefficient. This is the reason why this sort is not used in software libraries.\n"
  },
  {
    "path": "lessons/recurrence.md",
    "content": "---\npath: \"/recurrence\"\ntitle: \"Recurrence Relations\"\norder: \"7D\"\nsection: \"Space & Time Complexity\"\ndescription: \"learn about time and space complexity for various algorithms\"\n---\n"
  },
  {
    "path": "lessons/recursion-arrays.md",
    "content": "---\npath: \"/recursion-arrays\"\ntitle: \"Recursion & Array\"\norder: \"8C\"\nsection: \"Recursion\"\ndescription: \"learn Recursion from scratch\"\n---\n"
  },
  {
    "path": "lessons/recursion-practise.md",
    "content": "---\npath: \"/recursion-practise\"\ntitle: \"Standard Practise Questions\"\norder: \"8G\"\nsection: \"Recursion\"\ndescription: \"learn Recursion from scratch\"\n---\n\n## **Q1 : Recursive Solution of Pow(x, n)**\n\nImplement `pow(x, n)`\n\nwhich calculates `x` raised to the power `n` i.e.  `x^n`\n\n***Example 1:***\n```\nInput: x = 2, n = 9\nOutput: 512\n```\n\n***Example 2:***\n```\nInput: x = 5, n = 3\nOutput: 125\n```\n\n### **Solution & Approach :**\n<center>\n<img src=\"images/rec-relation.png\" alt=\"Rec-Relation\" width=\"600\" />\n</center>\n\n#### ***Rcursive Tree :*** For,  **pow(2, 9) = 2<sup>9</sup>**\n<center>\n<img src=\"images/rec-tree.png\" alt=\"Rec-Relation\" width=\"600\" />\n</center>\n\n### **Time Complexity :**\nO(log(n))\n\n### **Code :**\n```java\nclass PowerProgram {\n    // power function\n    public static int pow(int x, int n){\n\t\tif (n==0) return 1;\n\t\telse if(n%2==0) {\n\t\t\tint temp = pow(x, n/2);\n\t\t\treturn temp*temp;\n\t\t}\n\t\telse return x*pow(x, n-1);\n\t}\n    // Driver Code\n    public static void main(String args[])\n    {\n        int n = 2, x = 9;\n        int result = pow(n, x);\n        System.out.print(result);\n    }\n}\n\n```\n\n### **Output :**\n```\n512\n```\n\n## **Q2 : Recursive program to find all Indices of a Number from an Array**\n\nGiven an array `arr` of size `N` and an integer `X`. The task is to find all the indices of the integer `X` in the array\nExamples: \n \n```\nInput: arr = {1, 2, 3, 2, 2, 5}, X = 2 \nOutput: 1 3 4 \n\nAs Element 2 is present at indices 1, 3, 4 (0 based indexing)\n ```\n\n### **Solution & Approach :**\n- If the start index reaches the length of the array, then return empty array\n\n- Else keep the first element of the array with yourself and pass the rest of the array to recursion. \n\n- If the element at start index is not equal to x then just simply return the answer which came from recursion. \n \n- Else if the element at start index is equal to x then shift the elements of the array (which is the answer of recursion) one step to the right and then put the start index in the front of the array (which came through recursion) \n\n### **Code :**\n```java\npublic class FindAllIndices {\n\tpublic static int[] printAllIndex(int[] input, int x, int startIndex) {\n\t\tif (startIndex == input.length) {\n\t\t\tint[] output = new int[0];\n\t\t\treturn output;\n\t\t}\n\t\tint[] smallOutput = printAllIndex(input, x, startIndex + 1);\n\t\tif (input[startIndex] == x) {\n\t\t\tint[] output = new int[smallOutput.length + 1];\n\t\t\toutput[0] = startIndex;\n\t\t\tfor (int i = 0; i < smallOutput.length; i++) {\n\t\t\t\toutput[i + 1] = smallOutput[i];\n\t\t\t}\n\t\t\treturn output;\n\t\t} else {\n\t\t\treturn smallOutput;\n\t\t}\n\t}\n\tpublic static int[] printAllIndex(int[] input) {\n\t\treturn printAllIndex(input, 2, 0);\n\t}\n\tpublic static void main(String[] args) {\n\t\tint[] arr = { 1, 2, 3, 2, 2, 5 };\n\t\tarr = printAllIndex(arr);\n\t\tfor (int j : arr) {\n\t\t\tSystem.out.print(j + \" \");\n\t\t}\n\t}\n}\n```\n### **Output :**\n```\n1 3 4\n```\n\n\n## **Q3 : Count Good Numbers**\n\nA digit string is good if the digits (0-indexed) at `even` indices are `even` and the digits at `odd` indices are `prime` (2, 3, 5, or 7).\n\n- For example, `2582` is good because the digits `(2 and 8)` at even positions are even and the digits `(5 and 2)` at odd positions are prime. However, `3245` is not good because `3` is at an even index but is not even.\nGiven an integer `n`, return the total number of good digit strings of length n. Since the answer may be large, return it modulo` 10^9+7`.\n\nA digit string is a string consisting of digits 0 through 9 that may contain leading zeros.\n\n***Example-1***\n```\nInput: n = 1\nOutput: 5\nExplanation: The good numbers of length 1 are \"0\", \"2\", \"4\", \"6\", \"8\".\n```\n***Example-2***\n```\nInput: n = 50\nOutput: 564908303\n```\n\n### **Solution & Approach :**\n\n### **Code :**\n```java\nclass GoodNumber {\n    static int mod=(int)1e9+7;\n    public static int countGoodNumbers(long n) {\n  \n        if(n%2==0){\n            long a= power(4,n/2);\n            long b=power(5,n/2);\n                  long z=a*b %mod;\n                    return (int)(z);  \n        }else{\n              long a= power(4,n/2);\n              long b=power(5,(n/2)+1);\n               long z=a*b%mod;\n                    return (int)(z);  \n        }\n    }\n    // power function\n    public static long power(long x,long y){ \n        long temp;\n        if(y==0) return 1; \n        temp=power(x,y/2); \n        if(y%2==0) return (temp*temp)%mod;  \n        else return (x*temp*temp)%mod; \n\t\t \n    }\n    // Driver Code\n    public static void main(String args[])\n    {\n        int n = 1;\n        int result = countGoodNumbers(n);\n        System.out.print(result);\n    }\n}\n```\n### **Output :**\n```\n5\n```\n\n\n<br><br>\nHappy Learning 👍\n"
  },
  {
    "path": "lessons/recursion-string.md",
    "content": "---\npath: \"/recursion-string\"\ntitle: \"Recursion & Strings\"\norder: \"8D\"\nsection: \"Recursion\"\ndescription: \"learn Recursion from scratch\"\n---\n\nThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily.\n\nFor example, we can define the operation \"find your way home\" as:\n\n- If you are at home, stop moving.\n\n- Take one step toward home.\n\n- \"find your way home\".\n\nHere the solution to finding your way home is two steps (three steps). First, we don't go home if we are already home. Secondly, we do a very simple action that makes our situation simpler to solve. Finally, we redo the entire algorithm.\n\nHere we are going to see some important examples based on strings using Recursion:-\n\n### 1)String Reverse :-\n\nExamples:-\n\n1) Input - nissan is a good company\n   Output - ynapmoc doog a si nassin\n\n2) Input - He is my brother \n   Output - rehtorb ym si eh\n\n### Approach/Algorithm:- \n\nImplement a recursive function that will reverse a string,\n\nApproach:-\n- If string length is null or less than equal to 1, then return the\n  original string\n\n- Else call the function within itself and pass the substring of s\n  from start index 0 to end index(length of string - 1).\n\n\n```java\nstring_rev(String s)\n{\n    IF(s = Null or length of s <= 1){\n        RETURN\n    }\n    ELSE{\n        Call string_rev(substring of s from start index 0 to\n        end index (length of s - 1))\n    }\n}\n```\n\n### Code Implementation:-\n\n```java\nclass StringReverse\n{\n    void string_rev(String s)\n    {\n        if ((s==null)||(s.length() <= 1))\n           System.out.println(s);\n        else\n        {\n            System.out.print(s.charAt(s.length()-1));\n            string_rev(s.substring(0,s.length()-1));\n        }\n    }\n     \n    public static void main(String[]args)\n    {\n        String s = \"He is my Brother\";\n        StringReverse obb = new StringReverse();\n        obb.string_rev(s);\n    }   \n}\n```\n\n### OUTPUT:- \"rehtorB ym si eH\"\n\n### 2) Remove consecutive character duplicates using recursion:-\n\nExamples:-\n\nInput:- aaabbccc\nOutput:- abc\n\nInput:- aaaaaaabbbbb\nOutput:- ab\n\n### Approach/Algorithm:-\n\nThe steps to solve this problem with recursion are as follows, \n\n1) IF the String is null/empty, then simply return\n\n\n2) ELSE compare the adjacent characters. IF the characters are identical, then shift the characters one by one to the left of the string.\nCall the function again(perform recursion) and pass the updated string S as the value.\n\n\n3) ELSE if they are not similar, then call recursion on the string from the next portion of the string.\n\n```java\nremove_dup(String S)\n{\n    IF(length of S <= 1){\n        RETURN S\n    }\n    IF(S[0] = S[1]){\n        RETURN call remove_dup() and pass the substring of S from index 1 to end.\n    }\n    ELSE{\n        RETURN 1st character + call remove_dup() and pass the substring of S from index 1 to end.\n    }\n}\n```\n\n### Code Implementation:-\n\n```java\nimport java.io.*;\nclass Program {\n    public static String remove_dup(String s) {\n        if(s.length()<=1)\n            return s;\n        if(s.charAt(0)==s.charAt(1))\n            return remove_dup(s.substring(1));\n        else\n            return s.charAt(0) + remove_dup(s.substring(1));\n    }\n    public static void main(String[] args)\n    {\n        String s = \"aabcca\";\n        System.out.println(remove_dup(s));\n    }\n}\n```\n### Output:- abca\n\n3) Tower of Hanoi(Using recursion):-\n\nExplanation:- \n\nTower of Hanoi is a mathematical puzzle where we have three rods and N disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:-\n1) Only one disk can be moved at a time.\n2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.\n3) No larger disk may be placed on top of a smaller disk.\n\n### Code Implementation:-\n\n```java\nclass Program\n{\n    /*A- Starting rod, B- Temporary rod, C- Destination rod */\n    public static void tower_of_hanoi(int n, char from_rod, char to_rod, char temp_rod)\n    {\n        if (n == 1)\n        {\n            System.out.println(\"Move disk 1 from rod \" +  from_rod + \" to rod \" + to_rod);\n            return;\n        }\n        tower_of_hanoi(n-1, from_rod, temp_rod, to_rod);\n        System.out.println(\"Disk \" + n + \" moved from rod \" +  from_rod + \" to rod \" + to_rod);\n        tower_of_hanoi(n-1, temp_rod, to_rod, from_rod);\n    }\n\n    public static void main(String args[])\n    {\n        int n = 4; // Number of disks\n        System.out.println(\"A- Starting tower\\nC- Destination tower\\nB- Temporary tower\");\n        tower_of_hanoi(n, \\'A\\', \\'C\\', \\'B\\');\n    }\n}\n```\n### Output:-\n\n```yml\nA- Starting tower\nC- Destination tower\nB- Temporary tower\nDisk 1 moved from rod 'A' to rod 'B'\nDisk 2 moved from rod 'A' to rod 'C'\nDisk 1 moved from rod 'B' to rod 'C'\nDisk 3 moved from rod 'A' to rod 'B'\nDisk 1 moved from rod 'C' to rod 'A'\nDisk 2 moved from rod 'C' to rod 'B'\nDisk 1 moved from rod 'A' to rod 'B'\nDisk 4 moved from rod 'A' to rod 'C'\nDisk 1 moved from rod 'B' to rod 'C'\nDisk 2 moved from rod 'B' to rod 'A'\nDisk 1 moved from rod 'C' to rod 'A'\nDisk 3 moved from rod 'B' to rod 'C'\nDisk 1 moved from rod 'A' to rod 'B'\nDisk 2 moved from rod 'A' to rod 'C'\nDisk 1 moved from rod 'B' to rod 'C'\n```\n\n"
  },
  {
    "path": "lessons/selectionsort.md",
    "content": "---\npath: \"/selectionsort\"\ntitle: \"Selection Sort\"\norder: \"5D\"\nsection: \"Searching & Sorting\"\ndescription: \"learn Sorting algorithms\"\n---\n\nSelection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list.\n\nThe smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array. This process continues moving unsorted array boundary by one element to the right.\n\nThe average and worst-case complexity of selection sort is `O(n^2)`, where n is the number of items. Due to this, it is not suitable for large data sets.\n\nSelection sort is generally used when:\n- A small array is to be sorted\n- Swapping cost doesn't matter\n- It is compulsory to check all elements\n\n\n## Selection Sort Algorithm\n\n```\nselectionSort(array, size)\n  repeat (size - 1) times\n  set the first unsorted element as the minimum\n  for each of the unsorted elements\n    if element < currentMinimum\n      set element as new minimum\n  swap minimum with first unsorted position\nend selectionSort\n```\n\n## Example for better understanding\n\nLet the elements of array are -\n```\n12 29 25 8 32 17 40\n```\n\nNow, for the first position in the sorted array, the entire array is to be scanned sequentially.At present, 12 is stored at the first position, after searching the entire array, it is found that 8 is the smallest value.\n```\n12 29 25 8 32 17 40\n```\nSo, swap 12 with 8. After the first iteration, 8 will appear at the first position in the sorted array.\n```\n8 29 25 12 32 17 40\n```\nFor the second position, where 29 is stored presently, we again sequentially scan the rest of the items of unsorted array. After scanning, we find that 12 is the second lowest element in the array that should be appeared at second position.\n```\n8 29 25 12 32 17 40\n```\nNow, swap 29 with 12. After the second iteration, 12 will appear at the second position in the sorted array. So, after two iterations, the two smallest values are placed at the beginning in a sorted way.\n```\n8 12 25 29 32 17 40\n```\nThe same process is applied to the rest of the array elements. So, the entire sorting process is shown below:\n```\n8 12 25 29 32 12 40\n```\n\n```\n8 12 17 29 32 25 40\n```\n\n```\n8 12 17 25 32 29 40\n```\n\n```\n8 12 17 25 29 32 40\n```\n\nNow, the array is completely sorted.\n\n## Implementation of Selection Sort\n\n```Java\n// Java program for implementation of Selection Sort\nclass SelectionSort\n{\n    void sort(int arr[])\n    {\n        int n = arr.length;\n \n        // One by one move boundary of unsorted subarray\n        for (int i = 0; i < n-1; i++)\n        {\n            // Find the minimum element in unsorted array\n            int min_idx = i;\n            for (int j = i+1; j < n; j++)\n                if (arr[j] < arr[min_idx])\n                    min_idx = j;\n \n            // Swap the found minimum element with the first\n            // element\n            int temp = arr[min_idx];\n            arr[min_idx] = arr[i];\n            arr[i] = temp;\n        }\n    }\n \n    // Prints the array\n    void printArray(int arr[])\n    {\n        int n = arr.length;\n        for (int i=0; i<n; ++i)\n            System.out.print(arr[i]+\" \");\n        System.out.println();\n    }\n \n    // Driver code to test above\n    public static void main(String args[])\n    {\n        SelectionSort ob = new SelectionSort();\n        int arr[] = {64,25,12,22,11};\n        ob.sort(arr);\n        System.out.println(\"Sorted array\");\n        ob.printArray(arr);\n    }\n}\n```\n### Output\n```\nSorted array \n11 12 22 25 64\n```\n\n## Time Complexity and Space Complexity\n\n### Time Complexity\n\n- **Best Case Complexity:** It occurs when there is no sorting required, i.e. the array is already sorted. The best-case time complexity of selection sort is `O(n^2)`.\n- **Average Case Complexity:** It occurs when the array elements are in jumbled order that is not properly ascending and not properly descending. The average case time complexity of selection sort is `O(n^2)`.\n- **Worst Case Complexity:** It occurs when the array elements are required to be sorted in reverse order. That means suppose you have to sort the array elements in ascending order, but its elements are in descending order. The worst-case time complexity of selection sort is `O(n^2)`.\n\n\n### Space Complexity\n- **Space Complexity:** The Space complexity of selection sort is `O(1)`. It is because, in selection sort, an extra variable is required for swapping.\n\n## The Application of Selection Sort\n\nThe selection sort is used when:\n- a small list is to be sorted\n- cost of swapping does not matter\n- checking of all the elements is compulsory\n- cost of writing to a memory matters like in flash memory \n\n## Comparison to other sorting algorithms\n- **Selection Sort vs QuickSort:** Quicksort, the most widely used sorting algorithm, is contrasted with the less efficient selection sort. Quicksort starts by picking an element, called a pivot , from the list. Selection sort first finds the minimum element in the list.\n\n\n- **Selection Sort vs Bubble Sort:** The main difference between bubble sort and selection sort is that the bubble sort operates by repeatedly swapping the adjacent elements if they are in the wrong order while the selection sort sorts an array by repeatedly finding the minimum element from the unsorted part and placing that at the beginning of the array.\n\n\n- **Selection Sort vs Merge Sort:** Selection sort may be faster than mergesort on small input arrays because it's a simpler algorithm with lower constant factors than the ones hidden by mergesort. If you're sorting, say, arrays of 16 or so elements, then selection sort might be faster than mergesort.\n"
  },
  {
    "path": "lessons/space-complexity.md",
    "content": "---\npath: \"/space-complexity\"\ntitle: \"Space Complexity\"\norder: \"7C\"\nsection: \"Space & Time Complexity\"\ndescription: \"learn about time and space complexity for various algorithms\"\n---\n\nNow that we have learned about the 'time' aspect of performance analysis of an algorithm, let's move on to memory aspect of the same.\n\n***Space complexity of an algorithm is basically the amount of memory it needs to run to completion, ie, to execute and produce the result.***\n\nCalculation of space complexity used to hold much more significance in early days of computing than it does now. This is because most machines today have large memories and the user does not need to worry about running out of memory for running a program or two. But it is a crucial estimate where the physical memory is limited or closely monitored.\n\n*Above all, it’s necessary to mention that space complexity depends on a variety of things such as the programming language, the compiler, or even the machine running the algorithm.*\n\n## Memory Usage while Execution\nWhile executing, an algorithm uses memory space for three reasons:\n- **Instruction Space**\n-- It's the amount of memory used to save the compiled version of instructions.\n\n- **Environmental Stack**\n-- Sometimes an algorithm(function) may be called inside another algorithm(function). In such a situation, the current variables are pushed onto the system stack, where they wait for further execution and then the call to the inside algorithm(function) is made.\\\nEx.  If a function A() calls function B() inside it, then all the variables of the function A() will get stored on the system stack temporarily, while the function B() is called and executed inside the function A().\n\n- **Data Space**\n-- Amount of space used by the variables and constants.\n\n\n\nSo in general for any algorithm, the memory may be used for the following: - `Variables (Data Space)`, `Program Instruction (Instruction Space)` and  `Execution (Environmental Space)`.\nBut while calculating the Space Complexity of any algorithm, we usually consider only Data Space and we neglect the Instruction Space and Environmental Stack.\n\n## Calculation of Space Complexity\n\nAn algorithm's space can be categorized into 2 parts:\\\n**1) Fixed Part** - It is independent of the characteristics of input and output.\\\nIt includes instruction(code) space, space for simple variables, fixed-size component variables and constants.\\\n**2) Variable Part** - It depends on instance characteristics.\\\nIt consists of the space needed by component variables whose size is dependent on the particular problem instance being solved, the space needed by referenced variables, and the recursion stack space.\n\nSometimes, ***Auxiliary Space*** is confused with Space Complexity. The Auxiliary Space is the extra space or the temporary space used by the algorithm during it's execution.\n\n`Space Complexity = Auxiliary Space + Input space`\n\n> Thus, space requirement S(M) of any algorithm M is:\n> S(M) = c + Sm (Instance characteristics), where c is constant\n\n\nWhile analyzing space complexity, we primarily concentrate on estimating Sm.\nConsider the following algorithm:\n\n```java\npublic int sum(int a, int b) {\n    return a + b;\n}\n```\nIn this particular method, three variables are used and allocated in memory: \n1. The first `int` argument, a\n2. The second `int` argument, b\n3. The returned sum result which is also an `int` like a and b\n\nIn Java, a single integer variable occupies `4` bytes of memory. In this example, we have three integer variables. Therefore, this algorithm always takes 12 bytes of memory to complete (3*4 bytes).\n\n> We can clearly see that the space complexity is constant, so, it can be expressed in big-O notation as O(1).\n\nNow let us see another example - \n```java\npublic int sumArray(int[] array) {\n    int size = array.length;\n    int sum = 0;\n    for (int i = 0; i < size; i++) {\n        sum += array[i];\n    }\n    return sum;\n}\n```\nAgain, let’s list all variables present in the above code:\n1. Array – the function’s only argument – the space taken by the array is equal to 4n bytes where n is the length of the array\n2. The `int` variable, size\n3. The `int` variable, sum\n4. The `int` iterator, i\n\nThe total space needed for this algorithm to complete is 4n + 4 + 4 + 4 (bytes). The highest order is of n in this equation. Thus, the space complexity of that code snippet is O(n).\nWhen the program consists of loops (In case of Iterative algorithms), it will have linear space complexity or O(n).\n\n> While dealing with operations on data structures, we can say that space complexity depends on size of the data structure. Ex, if an array stores N elements, its space complexity is O(N). A program with an array of N arrays will have space complexity O(N^2) and so on.\n\nNow, the space complexity analysis also takes into account the size of recursion stack in case of recursive algorithms. \nConsider the code below - \n```java\nAlgorithm fact(n)\n{\n  if (n<=0) \n    return 1;\n  else  \n    return n * (n - 1);\n}\n```\n\nIn this case there are 3 statements ( an `if` statement & 2`return` statements). The depth of recursion is *n + 1*. Thus the recursion stack space needed is >=3(n+1). So we can say, space complexity is O(n) i.e. linear.\n\n## Space Complexities of Common Algorithms\nThe space complexities of various algorithms is given below - \n| Algorithm | Space Complexity |\n| --------- | ---------------- |\n| Linear Search | O(1) |\n| Binary Search | O(1) |\n| Bubble Sort\t|\tO(1) |\n| Insertion Sort\t|\tO(1) |\n| Selection Sort\t|\tO(1) |\n| Heapsort\t|\tO(1) |\n| Shell Sort\t|\tO(1) |\n| Quicksort | O(log(n)) |\n| Mergesort\t|\tO(n) |\n| Timsort\t|\tO(n) |\n| Tree Sort\t|\tO(n) |\n| Bucket Sort |\t\tO(n) |\n| Radix Sort\t|\tO(n+k) |\n| Counting Sort\t|\tO(k) |\n"
  },
  {
    "path": "lessons/string-builder.md",
    "content": "---\npath: \"/string-builder\"\ntitle: \"StringBuilder in Java\"\norder: \"6B\"\nsection: \"Strings In Depth\"\ndescription: \"learn strings in depth\"\n---\n\n\nString Builder is a separate class just like Strings, which allows us to modify the values(mutability).\n### Need of String Builder:\nAs we know that Strings  are immutable ,because of which\neach and every time we need to create an object and that object will have no reference in later cases while running the loop , hence there will be huge memory wastage and due to this we use String Builder.\n### Code:\n```java\npublic class SB {\n    public static void main(String[] args) {\n        StringBuilder builder=new StringBuilder();\n        for(int i = 0;i<26;i++){\n            char ch=(char) ('a'+i);\n            builder.append(ch);\n        }\n        System.out.println(builder.toString());\n    }\n}\n\n```\n### Code Explanation:\n* This is a simple code which  demonstrates the use of String Builder class to print all alphabets from a-z, and to show how efficient it is in space and time complexity.\n* So inside the main function, we create a StringBuilder using \"new\" keyword, just like how we use to create for Strings.\n* Now inside the ```for``` loop we take ASCII value of the character 'a' and add it to the iterating variable ```i``` and finally typecast the ASCII value to a character and assign it to ```ch```.\n* In next step we add(```append```) each character to the builder and finally print it after converting them to String format by calling toString() Method.\n\n\n# Code Analysis:\n1. #### Now if we analyze the Time Complexity of using **Strings** for the above example:\n\n```[a,ab,abc,abcd,...........,abcdefghijklmnopqrstuvwxy] ```\n\n* Here, Size of each items are 1+2+3+4...+26 (N). This can be represented as N(N+1) /2 .\n\n* After eliminating constants and less dominating terms , we finally obtain O(N^2).\n\n* All of these large Strings will have no reference variable pointing towards it. [Wastage of Space].\n\n2. #### Now if we analyze the Time Complexity of using **String Builder**  for the above example:\n\n* Here instead of creating new object every time , it makes changes in the exsiting object itself[like how Arrays does], hence saving memory space and time.\n For example:\n```[\"abc\"+d -> \"abcd\"]```\n\n* Due to this the Time Complexity is O(N).\n"
  },
  {
    "path": "lessons/subarrays.md",
    "content": "---\npath: \"/subarrays\"\ntitle: \"Subarrays\"\norder: \"4E\"\nsection: \"Arrays\"\ndescription: \"arrays\"\n---\n\n> A subarray is a contiguous part of any given array. Basically speaking, an array that is present inside another array or a part of that array, but in a continuous manner.\nFor eg., consider the array [1, 2, 3, 4], There are 10 non-empty sub-arrays in this. \nThe subarrays are [1], [2], [3], [4], [1,2], [2,3], [3,4], [1,2,3], [2,3,4] and [1,2,3,4]. \nIn general, for an array/string of size n, there are n*(n+1)/2 non-empty subarrays/substrings.\n\n\n![java-subarray](./images/java-subarray.png)\n\n### How to generate all subarrays? \n- We can run two nested loops\n- The outer loop picks the starting element.\n- The inner loop considers all elements on right of the picked starting element as ending element of subarray. \n\n```java\n    class Test\n    {\n        static int arr[] = new int[]{1, 2, 3, 4};\n         \n        // Prints all subarrays in arr[0..n-1]\n        static void subArray( int n)\n        {\n            // Pick starting point\n            for (int i=0; i <n; i++)\n            {\n                // Pick ending point\n                for (int j=i; j<n; j++)\n                {\n                    // Print subarray between current starting\n                    // and ending points\n                    for (int k=i; k<=j; k++)\n                        System.out.print(arr[k]+\" \");\n                }\n            }\n        }\n     \n        // Driver method to test the above function\n        public static void main(String[] args)\n        {\n            System.out.println(\"All Non-empty Subarrays\");\n            subArray(arr.length);\n             \n        }\n    }\n```\n#####  Output -\nAll Non-empty Subarrays\n1 \n1 2 \n1 2 3 \n1 2 3 4 \n2 \n2 3 \n2 3 4 \n3 \n3 4 \n4\n**Time Complexity: O(n^2)**  \n\n\n### Generating subarrays using recursion\nInput : [1, 2, 3]\nOutput : [1], [1, 2], [1, 3], [2], [1, 2, 3], [2, 3], [3]\n\nInput : [1, 2]\nOutput : [1], [1, 2], [2]\n\n \n\n#### Approach\n- We use two pointers, NAMELY, `start` and `end` to maintain the starting and ending point of the array and follow the steps given below: \n- Stop if we have reached the end of the array\n- Increment the `end` index if `start` has become greater than the `end` index.\n- Print the subarray from the `start` index to the `end` index and increment the `start` index.\n\nBelow is the implementation of the above approach.\n\n```java\n    class solution\n    {\n        // Recursive function to print all possible subarrays\n        // for given array\n        static void printSubArrays(int []arr, int start, int end)\n        {    \n            // Stop if we have reached the end of the array    \n            if (end == arr.length)\n                return;\n             \n            // Increment the end point and start from 0\n            else if (start > end)\n                printSubArrays(arr, 0, end + 1);\n                 \n            // Print the subarray and increment the starting point\n            else\n            {\n                System.out.print(\"[\");\n                \n                for (int i = start; i < end; i++){\n                    System.out.print(arr[i]+\", \");\n                }\n                 \n                System.out.println(arr[end]+\"]\");\n                printSubArrays(arr, start + 1, end);\n            }\n             \n            return;\n        }\n         \n        public static void main(String args[])\n        {\n            int []arr = {1, 2, 3};\n            printSubArrays(arr, 0, 0);\n        }\n    }\n```\n\n#####  Output -\n\n[1]\n[1, 2]\n[2]\n[1, 2, 3]\n[2, 3]\n[3]\n \n\n**Time Complexity: O(n^2) **  \n\n"
  },
  {
    "path": "lessons/this-constructor.md",
    "content": "---\npath: \"/this-constructor\"\ntitle: \"this Keyword & Constructor\"\norder: \"11B\"\nsection: \"Object Oriented Programming\"\ndescription: \"complete introduction to object oriented programming\"\n---\n"
  },
  {
    "path": "lessons/time-complexity.md",
    "content": "---\npath: \"/time-complexity\"\ntitle: \"Time Complexity\"\norder: \"7B\"\nsection: \"Space & Time Complexity\"\ndescription: \"learn about time and space complexity for various algorithms\"\n---\nTime Complexity is a function / relationship that tells us how the time increases as input size increases. \n\n## Types of Notations:\n\n### Big O Notation, O : \n- Word Definition - The notation Ο(n) is the formal way to express the strict upper bound of an algorithm's running time. It measures the worst case time complexity or the longest amount of time an algorithm can possibly take to complete.\n- Mathematical Definition - \n![BigOh](./images/BigOh.png)\nIf f(n) = O(g(n)), then there exists positive constants c, n0 such that 0 ≤ f(n) ≤ c.g(n), for all n ≥ n0, where f(n) are g(n) are asymptotic functions.\n\n### Big Omega Notation, Ω : \n- Word Definition - The notation Ω(n) is the formal way to express the strict lower bound of an algorithm's running time. It is opposite of Big Oh notation. \n- Mathematical Definition -\n![Big Omega](./images/BigOmega.png)\nIf f(n) = Ω(g(n)), then there exists positive constants c, n0 such that 0 ≤ c.g(n) ≤ f(n), for all n ≥ n0\n\n### Theta Notation, θ : \n- Word Definition - The notation θ(n) is the formal way to express both the lower bound and the upper bound of an algorithm's running time.\n- Mathematical Definition -\n![Theta](./images/Theta.png)\nIf f(n) = Θ(g(n)), then there exists positive constants c1, c2, n0 such that 0 ≤ c1.g(n) ≤ f(n) ≤ c2.g(n), for all n ≥ n0\n\n### Little O Notation, o : \n- Word Definition - The notation o(n) is the formal way to express the loose upper bound of an algorithm's running time.\n- Mathematical Definition -\n![LittleOh](./images/LittleOh.png)\nIf f(n) = o(g(n)), then there exists positive constants c, n0 such that 0 ≤ f(n) < c.g(n), for all n ≥ n0\n\n### Little Omega Notation, Ω : \n- Word Definition - The notation Ω(n) is the formal way to express the loose lower bound of an algorithm's running time.\n- Mathematical Definition -\n![LittleOmega](./images/LittleOmega.png)\nIf f(n) = ω(g(n)), then there exists positive constants c, n0 such that 0 ≤ c.g(n) < f(n), for all n ≥ n0\n\nNOTE : We use Big O and Big Omega notations mostly.\n\n## Points to remember while calculating time complexity\n\n- Consider larger inputs because relationship at this point persists.\n- Constants are ignored since actual time even differs for the same relationship.\n- Always ignore less dominating terms.\n- Look for the worst case complexity - this will be what we consider the Big O of our algorithm/function\n\n## Example\n\n#### 1)  f(n) = 5n<sup>3</sup> + 4n + 3\nTime Complexity - O(n<sup>3</sup>)\n\nExplanation - Ignoring the less dominating terms we are left with 5n<sup>3</sup>. Now ignoring the constants, we get n<sup>3</sup>. And this is the time complexity.\n\n#### 2)\n```java\nint sum = 0;\nfor(int i = 0; i < n; i++){\n    for(int j = 0; j < n; j++){\n        sum += i;\n    }\n}\n```\nTime Complexity - O(n<sup>2</sup>)\n\nExplanation - Adding i to sum is constant time operation. And if we fix the value of i, we are traversing the inner loop n times. So, that means for a particular value of i, inner loop has O(n) complexity. And if we notice the outer loop, it is also traversing n times. So, total = n * n times and that is the time complexity.\n\n## Guidelines for Asymptotic notation:\n\n### Loops: \nThe running time of a loop is, at most, the running time of the statements inside the loop,  multiplied number of iterations.\n```java\nfor(int i = 0; i < n; i++){\n    System.out.println(i);\n}\n```\nHere, no of iterations are n and printing statement is a constant time operation. So, time complexity becomes O(n * 1) i.e. O(n).\n\n### Nested Loops:\nThe total running time is the product of the sizes of all the loops.\n```java\nfor(int j = 0; j < n; j++){\n    for(int i = 0; i < n; i++){\n        System.out.println(i);\n    }\n}\n```\nHere, outer loop is  traversing n times(each loop having complexity O(n) as explained earlier).So total becomes O(n * n). \n\n### Consecutive statements:\nAdd the time complexity of each statement. \n```java\nint x = 0;\nx += 1;\nfor(int i = 0; i < n; i++){\n    System.out.println(i);\n}\nfor(int j = 0; j < n; j++){\n    for(int i = 0; i < n; i++){\n        System.out.println(i);\n    }\n}\n```\nHere, the topmost two lines of code take 2 units of time(each statement takes 1 unit of time). The loop next to them executes n times(as explained earlier). The nested loop takes n<sup>2</sup> time. Hence,the total becomes  n<sup>2</sup> + n + 2. Ignoring less dominating terms and constants, final time complexity is O(n<sup>2</sup>).\n\n### If-then-else statements:\nThe total running time is the the sum of time taken for checking the condition and the part(if or else) which takes the highest time. \n```java\nint val = 12;\nif(val < 18){\n    for(int i = 0; i < n; i++){\n        System.out.println(i);\n    }\n}\nelse{\n    System.out.println(val);\n}\n```\nHere, the first statement takes 1 unit of time. Then checking takes 1 unit of time.\n\"if\" part takes n unit of time. \"else\" part takes 1 unit of time. Larger among \"if\" and \"else\" is \"if\" (i.e. n unit of time). \n\nSo total = 1 + 1 + n = O(n<sup>2</sup>)\n\n### Logarithmic Complexity:\nIt is achieved when the problem size is cut down by a fraction.\n```java\nfor(int i = 1; i <= n;){\n    i *= 2;\n}\n```\nHere, in the first iteration, i = 1(i.e. 2<sup>0</sup>) <br />\n             second         , i = 2(i.e. 2<sup>1</sup>) <br />\n             third          , i = 4(i.e. 2<sup>2</sup>) <br />\n             fourth         , i = 8(i.e. 2<sup>3</sup>) <br />\n             ...</br>\n             kth            , i = n(i.e. 2<sup>k - 1</sup>)\n\nSo, we need to find the no of interations i.e. the value of k = log<sub>2</sub>n + 1.\nThat means, time complexity will be O(log<sub>2</sub>n)\n\n## Properties of Asymptotic Notation:\n\n#### 1) Reflexivity:\nIf f(n) is given then, f(n) = O(f(n)).Example:If f(n) = n<sup>3</sup> ⇒ O(n<sup>3</sup>)\n</br>\nSimilarly, f(n) = Ω(f(n)) and f(n) = Θ(f(n)).\n\n#### 2) Symmetry:\nf(n) = Θ(g(n)) if and only if g(n) = Θ(f(n)). Example:\nIf f(n) = n<sup>3</sup> and g(n) = n<sup>3</sup> then f(n) = Θ(n<sup>3</sup>) and g(n) = Θ(n<sup>3</sup>)\n\n#### 3) Transistivity:\nf(n) = O(g(n)) and g(n) = O(h(n)) ⇒ f(n) = O(h(n)). Example:\nIf f(n) = n, g(n) = n<sup>2</sup> and h(n) = n<sup>3</sup>\n⇒ n is O(n<sup>2</sup>) and n<sup>2</sup> is O(n<sup>3</sup>) then n is O(n<sup>3</sup>)\n\n#### 4) Transpose Symmetry:\nf(n) = O(g(n)) if and only if g(n) = Ω(f(n)).\nExample:\nIf f(n) = n and g(n) = n<sup>2</sup> then n is O(n<sup>2</sup>) and n<sup>2</sup> is Ω(n).\n"
  },
  {
    "path": "lessons/time_space_tradeoff.md",
    "content": "---\npath: \"/time_space_tradeoff\"\ntitle: \"Time Space Tradeoff\"\norder: \"7E\"\nsection: \"Space & Time Complexity\"\ndescription: \"learn about time-space tradeoff\"\n---\n\n# **Time-Space Trade-Off in Algorithms**\n\n Space-Time tradeoff in computer science is basically a problem solving technique in which we solve the problem:\n - Either in less time and using more space, or\n - In very little space by spending more time.\n \nThe best algorithm is the one which helps to solve a problem that requires less space in memory as well as takes less time to generate the output.But in general, it is not always possible to achieve both of these conditions at the same time.\n\nIf our problem is taking a long time but not much memory, a space-time trade-off would let us use more memory and solve the problem more quickly. Or, if it could be solved very quickly but requires more memory than we have, we can try to spend more time solving the problem in the limited memory.\n\n## Types of Time-Space Trade-Off\n\n- Lookup tables or Recalculation\n- Compressed or Uncompressed data\n- Re Rendering or Stored images\n- Smaller code or loop unrolling\n\n### *1. Lookup tables or Recalculation:*\n\n In a lookup table, an implementation can include the entire table which reduces computing time but increases the amount of memory required. It can recalculate i.e., compute table entries as needed, increasing computing time but reducing memory requirements.\n \n### *2. Compressed or Uncompressed data:*\n\nA space-time trade-off can be applied to the problem of data storage. If data stored is uncompressed, it takes more space but less time. But if the data is stored compressed, it takes less space but more time to run the decompression algorithm. \nThere are many instances where it is possible to directly work with compressed data. In that case of compressed bitmap indices, where it is faster to work with compression than without compression.\n \n### *3. Re Rendering or Stored images:*\n\n In this case, storing only the source and rendering it as an image would take more space but less time i.e., storing an image in the cache is faster than re-rendering but requires more space in memory.\n \n### *4. Smaller code or loop unrolling:*\n\nSmaller code occupies less space in memory but it requires high computation time that is required for jumping back to the beginning of the loop at the end of each iteration. Loop unrolling can optimize execution speed at the cost of increased binary size. It occupies more space in memory but requires less computation time.\n\n\n### Example:\n\nThere are many algorithms that make use of time-space tradeoffs. Some of the algorithms are:\n - In the field of cryptography, using space-time trade-off, the attacker is decreasing the exponential time required for a brute-force attack. **Rainbow tables** use partially precomputed values in the hash space of a cryptographic hash function to crack passwords in minutes instead of weeks. Decreasing the size of the rainbow table increases the time required to iterate over the hash space. The meet-in-the-middle attack uses a space-time trade-off to find the cryptographic key in only 2^{n+1} encryptions (and O(2^{n}) space) compared to the expected 2^{2n} encryptions (but only O(1) space) of the normal attack.\n\n- **Dynamic programming** is another example where the time of solving problems can be decreased by using more memory. Fibonacci problem can be solved faster with DP.\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"dsa-java\",\n  \"description\": \"a gatsby seed project to get your education site started\",\n  \"version\": \"1.0.0\",\n  \"author\": \"Utkarsh Mishra <Utkarshmishra73444@gmail.com>\",\n  \"dependencies\": {\n    \"@fontsource/open-sans\": \"^4.5.0\",\n    \"@fortawesome/fontawesome-free\": \"^5.15.3\",\n    \"bootstrap\": \"^5.0.2\",\n    \"front-matter\": \"^4.0.2\",\n    \"gatsby\": \"^3.9.1\",\n    \"gatsby-cli\": \"^3.14.1\",\n    \"gatsby-link\": \"^3.9.0\",\n    \"gatsby-plugin-layout\": \"^2.9.0\",\n    \"gatsby-plugin-react-helmet\": \"^4.9.0\",\n    \"gatsby-plugin-react-svg\": \"^3.0.1\",\n    \"gatsby-plugin-sharp\": \"^3.9.0\",\n    \"gatsby-remark-autolink-headers\": \"^4.6.0\",\n    \"gatsby-remark-copy-linked-files\": \"^4.6.0\",\n    \"gatsby-remark-images\": \"^5.6.0\",\n    \"gatsby-remark-prismjs\": \"^5.6.0\",\n    \"gatsby-source-filesystem\": \"^3.9.0\",\n    \"gatsby-transformer-remark\": \"^4.6.0\",\n    \"global\": \"^4.4.0\",\n    \"is-url-superb\": \"^5.0.0\",\n    \"parse-markdown-links\": \"^1.0.4\",\n    \"prismjs\": \"^1.24.1\",\n    \"react\": \"^17.0.2\",\n    \"react-dom\": \"^17.0.2\",\n    \"react-helmet\": \"^6.1.0\"\n  },\n  \"keywords\": [\n    \"gatsby\",\n    \"gatsby-starter\",\n    \"course\",\n    \"education\"\n  ],\n  \"license\": \"(CC-BY-NC-4.0 OR Apache-2.0)\",\n  \"main\": \"n/a\",\n  \"scripts\": {\n    \"build\": \"gatsby build --prefix-paths\",\n    \"csv\": \"node csv.js\",\n    \"dev\": \"gatsby develop\",\n    \"format\": \"prettier --write \\\"src/**/*.{js,jsx,md,css}\\\"\",\n    \"lint\": \"eslint \\\"src/**/*.{js,jsx}\\\"\"\n  },\n  \"devDependencies\": {\n    \"@babel/polyfill\": \"^7.12.1\",\n    \"babel-eslint\": \"^10.1.0\",\n    \"core-js\": \"^3.15.2\",\n    \"eslint\": \"^7.31.0\",\n    \"eslint-config-prettier\": \"^8.3.0\",\n    \"eslint-plugin-import\": \"^2.23.4\",\n    \"eslint-plugin-jsx-a11y\": \"^6.4.1\",\n    \"eslint-plugin-react\": \"^7.24.0\",\n    \"prettier\": \"^2.3.2\"\n  }\n}\n"
  },
  {
    "path": "src/components/TOCCard.js",
    "content": "import React from \"react\";\nimport Link from \"gatsby-link\";\nimport Bg from \"../layouts/corner-image.svg\";\nimport * as helpers from \"../util/helpers\";\n\nconst sortFn = helpers.sorter;\n\nconst LessonCard = ({ content, title }) => {\n  console.log(sortFn);\n\n  const sections = content\n    .map((lesson) => lesson.node.frontmatter)\n    .sort(sortFn)\n    .reduce((acc, lesson) => {\n      if (!acc.length) {\n        acc.push([lesson]);\n        return acc;\n      }\n\n      const lastSection = acc[acc.length - 1][0].section.split(\",\")[0];\n      if (lastSection === lesson.section.split(\",\")[0]) {\n        acc[acc.length - 1].push(lesson);\n      } else {\n        acc.push([lesson]);\n      }\n\n      return acc;\n    }, []);\n\n  return (\n    <div className=\"main-card\">\n      <h1 className=\"lesson-title\">{title}</h1>\n      <div className=\"lesson-content\">\n        <ol className=\"sections-name\">\n          {sections.map((section) => (\n            <li key={section[0].section}>\n              <div className=\"lesson-details\">\n                <div className=\"lesson-preface\">\n                  <i\n                    className={`fas fa-${\n                      section[0].icon ? section[0].icon : \"dumpster-fire\"\n                    }`}\n                  ></i>\n                </div>\n                <div className=\"lesson-text\">\n                  <h3 className=\"lesson-section-title\">{section[0].section}</h3>\n                  <ol>\n                    {section.map((lesson) => (\n                      <li key={lesson.path}>\n                        <Link to={lesson.path}>{lesson.title}</Link>\n                      </li>\n                    ))}\n                  </ol>\n                </div>\n                <div className=\"details-bg\">\n                  <Bg />\n                </div>\n              </div>\n            </li>\n          ))}\n        </ol>\n      </div>\n    </div>\n  );\n};\n\nexport default LessonCard;\n"
  },
  {
    "path": "src/layouts/Footer.css",
    "content": ".footer {\n  width: 100%;\n  padding: 50px 15px;\n  background-color: var(--primary);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  color: var(--text-footer);\n}\n\n.socials {\n  display: flex;\n  align-items: center;\n  max-width: 900px;\n  width: 100%;\n  margin: 0;\n  padding: 0;\n}\n\n.social {\n  display: inline-block;\n  list-style: none;\n  margin-right: 40px;\n}\n\n.social img:hover {\n  opacity: 0.4;\n}\n\n.social img {\n  transition: opacity 0.25s;\n  width: 30px;\n}\n\n.terms {\n  font-size: 10px;\n}\n\n.terms p {\n  margin: 3px;\n}\n\n.footer a {\n  color: inherit;\n  text-decoration: underline;\n}\n\n.social svg {\n  transition: opacity 0.25s;\n}\n\n.social svg:hover {\n  opacity: 0.4;\n}\n"
  },
  {
    "path": "src/layouts/Footer.js",
    "content": "import React from \"react\";\nimport { graphql, StaticQuery } from \"gatsby\";\nimport Gh from \"./github-social.svg\";\nimport Tw from \"./twitter-social.svg\";\nimport Li from \"./linkedin-social.svg\";\n\nimport \"./Footer.css\";\n\nexport default function Footer({ twitter, linkedin, github }) {\n  return (\n    <footer className=\"footer\">\n      <ul className=\"socials\">\n        {twitter ? (\n          <li className=\"social\">\n            <a href=\"https://twitter.com/umishra1504\">\n              <Tw />\n            </a>\n          </li>\n        ) : null}\n        {linkedin ? (\n          <li className=\"social\">\n            <a href=\"https://linkedin.com/in/umishra1504\">\n              <Li />\n            </a>\n          </li>\n        ) : null}\n        {github ? (\n          <li className=\"social\">\n            <a href=\"https://github.com/utkarsh1504\">\n              <Gh />\n            </a>\n          </li>\n        ) : null}\n        <li className=\"social\">\n          <div className=\"terms\">\n            <p>Content Licensed Under Apache 2.0</p>\n            <p>Code Samples and Excercise Licensed Under Apache 2.0</p>\n            <p>\n              Site Designed by{\" \"}\n              <a href=\"https://www.alexdanielson.com/\">Alex Danielson</a>\n            </p>\n          </div>\n        </li>\n      </ul>\n    </footer>\n  );\n}\n"
  },
  {
    "path": "src/layouts/index.css",
    "content": "@import url(./variables.css);\n\nbody {\n  font-family: \"Open Sans\";\n  background: linear-gradient(90deg, var(--bg-main) 15px, transparent 1%) center,\n    linear-gradient(var(--bg-main) 15px, transparent 1%) center, var(--bg-dots);\n  background-size: 16px 16px;\n}\n\na {\n  color: var(--text-links);\n}\n\n.navbar {\n  border-bottom: 1px solid #ccc;\n  position: fixed;\n  width: 100%;\n  top: 0;\n  z-index: 10;\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  background-color: var(--bg-main);\n  padding: 10px;\n}\n\n.navbar h1 {\n  font-size: 20px;\n  margin: inherit;\n  padding: inherit;\n  font-weight: bold;\n  color: var(--text-main);\n}\n\n.navbar h2 {\n  font-size: 14px;\n  margin: inherit;\n  padding: inherit;\n  text-transform: uppercase;\n}\n\n.jumbotron {\n  padding: 0;\n}\n\n.jumbotron .courseInfo,\n.jumbotron .courseIcon {\n  padding: 20px;\n}\n\n.jumbotron .courseInfo,\n.jumbotron .courseIcon {\n  text-align: center;\n}\n\n.author {\n  margin-top: 40px;\n  display: flex;\n  justify-content: center;\n}\n\n@media (min-width: 1000px) {\n  .jumbotron {\n    display: flex;\n    width: 100%;\n    min-height: 45vh;\n  }\n  .jumbotron .courseInfo,\n  .jumbotron .courseIcon {\n    display: flex;\n    justify-content: center;\n    align-items: center;\n  }\n  .jumbotron .courseInfo {\n    width: 65%;\n    text-align: right;\n  }\n  .jumbotron .courseIcon {\n    width: 35%;\n    display: flex;\n    align-items: center;\n    justify-content: center;\n  }\n\n  .author {\n    justify-content: flex-end;\n  }\n  .jumbotron .courseInfo-inner {\n    max-width: 85%;\n  }\n}\n\n.jumbotron h1,\n.jumbotron h2 {\n  color: var(--text-main-headers);\n}\n\n.jumbotron h1 {\n  font-size: 50px;\n  margin-bottom: 20px;\n}\n\n.jumbotron .courseInfo {\n  background: var(--primary);\n}\n\n.jumbotron .courseIcon {\n  background: var(--secondary);\n}\n\n.jumbotron .courseIcon img {\n  max-width: 180px;\n}\n\n.author .info {\n  padding: 10px;\n}\n\n.author .name {\n  font-size: 18px;\n  font-weight: bold;\n  color: var(--text-main-headers);\n}\n\n.author .company {\n  color: var(--text-main-headers);\n  font-size: 16px;\n}\n\n.author .image {\n  border-radius: 75px;\n  overflow: hidden;\n  height: 75px;\n  width: 75px;\n}\n\n.navbar-brand.navbar-brand {\n  text-transform: uppercase;\n  font-weight: bold;\n  color: var(--text-main-headers);\n}\n\n.lesson-section-title {\n  color: var(--text-main-headers);\n}\n\n.lesson-container {\n  position: relative;\n  max-width: 900px;\n  margin: 0 auto 45px auto;\n  padding: 10px 40px;\n  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);\n  background-color: var(--bg-lesson);\n  border-radius: 5px;\n  margin-top: 40px;\n}\n\n.lesson {\n  margin: 15px;\n  padding: 15px;\n  border-radius: 8px;\n}\n\n.lesson > h1 {\n  color: var(--lesson);\n  font-size: 24px;\n}\n\n.lesson h2 {\n  font-size: 24px;\n  margin-top: 20px;\n  margin-bottom: 10px;\n}\n\n.lesson h2::after {\n  content: \"\";\n  display: block;\n  height: 3px;\n  margin-top: 5px;\n  background: var(--lesson);\n  max-width: 300px;\n}\n\n.lesson p {\n  clear: both;\n}\n\n.lesson p,\n.lesson li {\n  line-height: 180%;\n}\n\n.lesson-links {\n  font-size: 18px;\n  padding: 15px 0;\n}\n\n.next {\n  float: right;\n}\n\n.prev {\n  float: left;\n}\n\n.lesson-title {\n  text-transform: uppercase;\n  font-weight: bold;\n}\n\n.gatsby-highlight {\n  padding: 4px;\n  border-radius: 4px;\n  display: flex;\n  justify-content: space-between;\n  flex-direction: column;\n  align-items: stretch;\n}\n\n.lesson-content td {\n  border: 1px solid black;\n  padding: 8px;\n}\n\n.lesson-content td input {\n  min-width: 300px;\n}\n\n.lesson-flex {\n  display: flex;\n  flex-direction: column;\n  justify-content: center;\n  align-items: center;\n}\n\n.random-tweet {\n  width: 100%;\n  margin-top: 100px;\n}\n\n.fem-link {\n  text-align: center;\n}\n\n.content-container {\n  display: flex;\n  flex-direction: column;\n  justify-content: space-between;\n  min-height: 100vh;\n  padding-top: 50px;\n}\n\nblockquote {\n  padding: 15px;\n  background-color: var(--emphasized-bg);\n  border: 2px solid var(--emphasized-border);\n  border-radius: 5px;\n}\n\nblockquote > *:last-child {\n  margin-bottom: 0;\n}\n\n.lesson-content img {\n  max-width: 100%;\n}\n\n.main-card {\n  max-width: 900px;\n  margin: 0 auto;\n  overflow: hidden;\n}\n\n.lesson-title {\n  font-size: 30px;\n  padding: 15px 30px;\n}\n\n.lesson-content {\n  line-height: 1.5;\n}\n\n.lesson-text {\n  width: 100%;\n  padding: 25px 5px 25px 35px;\n  min-height: 200px;\n}\n\n.sections-name {\n  margin: 0;\n  padding: 0;\n}\n\nol.sections-name {\n  counter-reset: my-awesome-counter;\n  list-style: none;\n  padding-left: 40px;\n  width: 98%;\n  margin: 0;\n  padding: 0;\n}\n\nol.sections-name > li {\n  counter-increment: my-awesome-counter;\n  display: flex;\n  flex-direction: row;\n  flex-wrap: wrap;\n  margin-bottom: 35px;\n  width: 100%;\n  box-shadow: 0 4px 10px 0 rgba(0, 0, 0, 0.2);\n  border-bottom-right-radius: 5px;\n  border-top-right-radius: 5px;\n}\nol.sections-name .lesson-preface {\n  /* content: counter(my-awesome-counter); */\n  color: var(--icons);\n  display: flex;\n  position: relative;\n  align-items: center;\n  justify-content: center;\n  background: var(--bg-lesson-preface);\n  font-size: 30px;\n  padding: 25px;\n  width: 30%;\n}\n\n.lesson-preface .fas {\n  font-size: 60px;\n}\n\nol.sections-name .lesson-preface::before {\n  content: counter(my-awesome-counter);\n  position: absolute;\n  top: 0;\n  left: 5px;\n  font-size: 20px;\n  font-weight: bold;\n  color: var(--icons);\n}\n\nol.sections-name .lesson-details {\n  display: flex;\n  flex-basis: 100%;\n  flex: 1;\n  background: var(--bg-lesson);\n  min-width: 600px;\n  position: relative;\n}\n\n.details-bg {\n  --corner-fill: var(--corner-inactive);\n  transition: fill 0.25s;\n  width: 10%;\n  height: 0;\n  padding-bottom: 10%;\n  background-size: cover;\n  background-repeat: no-repeat;\n  position: absolute;\n  top: 0;\n  right: 0;\n}\n\n.details-bg > svg {\n  width: 100%;\n  height: auto;\n}\n\n.details-bg > svg path {\n  transition: fill 0.25s;\n}\n\n.lesson-details:hover .details-bg,\n.lesson-container .details-bg {\n  --corner-fill: var(--corner-active);\n}\n\n@media (min-width: 1000px) {\n  ol.sections-name > li::before {\n    border-bottom-left-radius: 5px;\n    border-top-left-radius: 5px;\n  }\n  ol.sections-name .lesson-details {\n    border-bottom-right-radius: 5px;\n    border-top-right-radius: 5px;\n  }\n}\n\n.lesson-details h3 {\n  font-size: 22px;\n  border-bottom: 1px solid var(--less);\n  padding-bottom: 10px;\n  display: inline-block;\n  font-weight: bold;\n  margin-bottom: 20px;\n}\n\n.lesson-links {\n  margin-top: 45px;\n  margin-bottom: 80px;\n}\n\n.lesson-links a {\n  border-radius: 10px;\n  background: var(--nav-buttons);\n  color: var(--nav-buttons-text);\n  padding: 15px 20px;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  text-decoration: none;\n}\n\n.lesson-links a.prev {\n  padding-left: 10px;\n}\n\n.lesson-links a.next {\n  padding-right: 10px;\n}\n\n.lesson-links a:hover {\n  text-decoration: none;\n}\n\n.lesson-links .arrow {\n  font-size: 24px;\n  line-height: 24px;\n  padding: 0px 5px;\n}\n"
  },
  {
    "path": "src/layouts/index.js",
    "content": "import React from \"react\";\nimport Link from \"gatsby-link\";\nimport Helmet from \"react-helmet\";\nimport { graphql, StaticQuery } from \"gatsby\";\n\nimport \"@fontsource/open-sans\";\nimport \"bootstrap/dist/css/bootstrap.css\";\nimport \"@fortawesome/fontawesome-free/css/all.css\";\nimport \"./index.css\";\n\nimport Footer from \"./Footer\";\n// import jpg from \"../../static/posterframe.jpg\";\n\nconst TemplateWrapper = (props) => {\n  return (\n    <StaticQuery\n      render={(data) => {\n        const frontmatter =\n          props.data && props.data.markdownRemark\n            ? props.data.markdownRemark.frontmatter\n            : null;\n\n        return (\n          <div>\n            <Helmet\n              title={\n                frontmatter\n                  ? `${frontmatter.title} – ${frontmatter.section} – ${data.site.siteMetadata.title}`\n                  : data.site.siteMetadata.title\n              }\n              meta={[\n                {\n                  name: \"og:title\",\n                  content: frontmatter\n                    ? `${frontmatter.title} – ${frontmatter.section} – ${data.site.siteMetadata.title}`\n                    : data.site.siteMetadata.title,\n                },\n                {\n                  name: \"description\",\n                  content: frontmatter\n                    ? frontmatter.description\n                    : data.site.siteMetadata.description,\n                },\n                {\n                  name: \"og:description\",\n                  content: frontmatter\n                    ? frontmatter.description\n                    : data.site.siteMetadata.description,\n                },\n                {\n                  name: \"twitter:card\",\n                  content: \"summary_large_image\",\n                },\n                // {\n                //   name: \"og:image\",\n                //   content: \"https://btholt.github.io\" + jpg,\n                // },\n                // {\n                //   name: \"og:url\",\n                //   content:\n                //     \"https://btholt.github.io/complete-intro-to-computer-science\" +\n                //     (frontmatter && frontmatter.path ? frontmatter.path : \"\"),\n                // },\n                {\n                  name: \"keywords\",\n                  content: data.site.siteMetadata.keywords.join(\", \"),\n                },\n                {},\n              ]}\n            />\n            <div className=\"navbar\">\n              <Link to=\"/\" className=\"navbar-brand\">\n                <h1>{data.site.siteMetadata.title}</h1>\n              </Link>\n              {!frontmatter ? null : (\n                <h2>{`${frontmatter.section} – ${frontmatter.title}`}</h2>\n              )}\n            </div>\n            <div className=\"content-container\">\n              <div className=\"main\">{props.children}</div>\n              <Footer\n                twitter={data.site.siteMetadata.twitter}\n                github={data.site.siteMetadata.github}\n                linkedin={data.site.siteMetadata.linkedin}\n              />\n            </div>\n          </div>\n        );\n      }}\n      query={graphql`\n        query HomePage($path: String!) {\n          markdownRemark(frontmatter: { path: { eq: $path } }) {\n            html\n            frontmatter {\n              path\n              title\n              order\n              section\n              description\n            }\n          }\n          site {\n            pathPrefix\n            siteMetadata {\n              title\n              subtitle\n              description\n              keywords\n              twitter\n              linkedin\n              github\n            }\n          }\n        }\n      `}\n    />\n  );\n};\n\nexport default TemplateWrapper;\n"
  },
  {
    "path": "src/layouts/variables.css",
    "content": "/* \n  change your syntax highlighting theme here\n  https://github.com/PrismJS/prism/tree/master/themes \n*/\n@import \"prismjs/themes/prism-solarizedlight.css\";\n\n:root {\n  --primary: #4fa4e2;\n  --secondary: #fed7aa;\n  --highlight: #0b151e;\n  --lesson: #713f12;\n\n  --text-header: var(--primary);\n  --text-main-headers: var(--highlight);\n  --text-links: #1d608f;\n  --text-footer: #05304f;\n\n  --bg-main: white;\n  --bg-dots: var(--primary);\n  --bg-lesson: white;\n  --bg-lesson-preface: var(--primary);\n\n  --nav-buttons: var(--highlight);\n  --nav-buttons-text: white;\n\n  --corner-active: var(--highlight);\n  --corner-inactive: #f4f4f4;\n  --icons: var(--highlight);\n\n  --emphasized-bg: #dce8ff;\n  --emphasized-border: #aab6d2;\n}\n"
  },
  {
    "path": "src/pages/404.js",
    "content": "import React from \"react\";\n\nconst NotFoundPage = () => (\n  <div>\n    <h1>NOT FOUND</h1>\n    <p>You just hit a route that doesn&#39;t exist... the sadness.</p>\n  </div>\n);\n\nexport default NotFoundPage;\n"
  },
  {
    "path": "src/pages/index.js",
    "content": "import React from \"react\";\nimport { StaticQuery, graphql } from \"gatsby\";\nimport Card from \"../components/TOCCard\";\n\nconst IndexPage = () => (\n  <StaticQuery\n    query={graphql`\n      query HomepageTOC {\n        site {\n          siteMetadata {\n            title\n            subtitle\n            description\n            keywords\n            courseImage\n          }\n        }\n        allMarkdownRemark(sort: { order: ASC, fields: [frontmatter___order] }) {\n          edges {\n            node {\n              id\n              frontmatter {\n                order\n                path\n                title\n                section\n                description\n                icon\n              }\n            }\n          }\n        }\n      }\n    `}\n    render={(props) => (\n      <div className=\"index\">\n        <div className=\"jumbotron\">\n          <div className=\"courseInfo\">\n            <div className=\"courseInfo-inner\">\n              <h1>{props.site.siteMetadata.title}</h1>\n              <h2>{props.site.siteMetadata.subtitle}</h2>\n              {/* <div className=\"author\">\n                <div className=\"image\">\n                  <img\n                    className=\"image\"\n                    src={props.site.siteMetadata.authorImage}\n                  />\n                </div>\n                <div className=\"info\">\n                  <div className=\"name\">{props.site.siteMetadata.author}</div>\n                  <div className=\"company\">\n                    {props.site.siteMetadata.authorSubtitle}\n                  </div>\n                </div>\n              </div> */}\n            </div>\n          </div>\n          <div className=\"courseIcon\">\n            <img src={props.site.siteMetadata.courseImage} />\n          </div>\n        </div>\n\n        <Card\n          title=\"Table of Contents\"\n          content={props.allMarkdownRemark.edges}\n        />\n      </div>\n    )}\n  />\n);\n\nexport default IndexPage;\n"
  },
  {
    "path": "src/templates/lessonTemplate.js",
    "content": "import React from \"react\";\nimport Link from \"gatsby-link\";\nimport { graphql } from \"gatsby\";\nimport * as helpers from \"../util/helpers\";\nimport Bg from \"../layouts/corner-image.svg\";\n\nconst sortFn = helpers.sorter;\n\nexport default function Template(props) {\n  let { markdownRemark, allMarkdownRemark } = props.data; // data.markdownRemark holds our post data\n\n  const sections = allMarkdownRemark.edges\n    .map((lesson) => lesson.node.frontmatter)\n    .sort(sortFn);\n\n  const { frontmatter, html } = markdownRemark;\n\n  const index = sections.findIndex((el) => el.path === frontmatter.path);\n\n  const prevLink =\n    index > 0 ? (\n      <Link className=\"prev\" to={sections[index - 1].path}>\n        <span className=\"arrow\">←</span>\n        {\" \" + sections[index - 1].title}\n      </Link>\n    ) : null;\n  const nextLink =\n    index < sections.length - 1 ? (\n      <Link className=\"next\" to={sections[index + 1].path}>\n        {sections[index + 1].title + \" \"}\n        <span className=\"arrow\">→</span>\n      </Link>\n    ) : null;\n  return (\n    <div className=\"lesson-container\">\n      <div className=\"lesson\">\n        <h1>{frontmatter.title}</h1>\n        <h2>{frontmatter.date}</h2>\n        <div\n          className=\"lesson-content\"\n          dangerouslySetInnerHTML={{ __html: html }}\n        />\n        <div className=\"lesson-links\">\n          {prevLink}\n          {nextLink}\n        </div>\n      </div>\n      <div className=\"details-bg\">\n        <Bg />\n      </div>\n    </div>\n  );\n}\n\nexport const pageQuery = graphql`\n  query LessonByPath($path: String!) {\n    markdownRemark(frontmatter: { path: { eq: $path } }) {\n      html\n      frontmatter {\n        path\n        title\n        order\n        section\n      }\n    }\n    allMarkdownRemark(limit: 1000) {\n      edges {\n        node {\n          frontmatter {\n            order\n            path\n            title\n          }\n        }\n      }\n    }\n  }\n`;\n"
  },
  {
    "path": "src/util/helpers.js",
    "content": "function splitSections(str) {\n  const validSectionTest = /^\\d+[A-Z]+$/;\n  const numbersRegex = /^\\d+/;\n  const lettersRegex = /[A-Z]+$/;\n  if (!validSectionTest.test(str)) {\n    throw new Error(\n      `${str} does not match the section format. It must be <numbers><capital letters>, like 16A or 5F (case sensitive)`\n    );\n  }\n\n  return [numbersRegex.exec(str)[0], lettersRegex.exec(str)[0]];\n}\n\nconst getCharScore = str =>\n  str\n    .split(\"\")\n    .map((char, index) => char.charCodeAt(0) * 10 ** index)\n    .reduce((acc, score) => acc + score);\n\nfunction sorter(a, b) {\n  let aOrder, bOrder;\n\n  if (a.attributes && a.attributes.order) {\n    aOrder = a.attributes.order;\n    bOrder = b.attributes.order;\n  } else {\n    aOrder = a.order;\n    bOrder = b.order;\n  }\n\n  const [aSec, aSub] = splitSections(aOrder);\n  const [bSec, bSub] = splitSections(bOrder);\n\n  // sections first\n  if (aSec !== bSec) {\n    return aSec - bSec;\n  }\n\n  // subsections next\n  return getCharScore(aSub) - getCharScore(bSub);\n}\n\nmodule.exports.splitSections = splitSections;\nmodule.exports.sorter = sorter;\n"
  },
  {
    "path": "static/theme.css",
    "content": "code[class*=\"language-\"],\npre[class*=\"language-\"] {\n  color: #000000;\n  background: none;\n  font-size: 17px;\n  font-family: \"Source Code Pro\", \"Cascadia Code\", Consolas, Monaco,\n    \"Andale Mono\", \"Ubuntu Mono\", monospace;\n  text-align: left;\n  white-space: pre;\n  word-spacing: normal;\n  word-break: normal;\n  word-wrap: break-word;\n  line-height: 1.5;\n  -moz-tab-size: 4;\n  -o-tab-size: 4;\n  tab-size: 4;\n  -webkit-hyphens: none;\n  -moz-hyphens: none;\n  -ms-hyphens: none;\n  hyphens: none;\n}\n\npre[class*=\"language-\"]::-moz-selection,\npre[class*=\"language-\"] ::-moz-selection,\ncode[class*=\"language-\"]::-moz-selection,\ncode[class*=\"language-\"] ::-moz-selection {\n  background: #fff;\n}\n\npre[class*=\"language-\"]::selection,\npre[class*=\"language-\"] ::selection,\ncode[class*=\"language-\"]::selection,\ncode[class*=\"language-\"] ::selection {\n  background: #8acaff;\n}\n\n/* Code blocks */\npre[class*=\"language-\"] {\n  padding: 0.1rem 0.3rem 0.2rem;\n  margin: 0.2rem;\n  overflow: auto;\n}\n\n:not(pre) > code[class*=\"language-\"],\npre[class*=\"language-\"] {\n  /* background: #fefce8; */\n  background: #fafaf9;\n}\n\n/* Inline code */\n:not(pre) > code[class*=\"language-\"] {\n  padding: 0.1rem 0.3rem 0.2rem;\n  border-radius: 0.2rem;\n  white-space: normal;\n}\n\n.token.comment,\n.token.prolog,\n.token.doctype,\n.token.cdata {\n  color: #66303e;\n}\n\n.token.punctuation {\n  color: #111b27;\n}\n\n.token.delimiter.important,\n.token.selector .parent,\n.token.tag,\n.token.tag .token.punctuation {\n  color: #006d6d;\n}\n\n.token.attr-name,\n.token.boolean,\n.token.boolean.important,\n.token.number,\n.token.constant,\n.token.selector .token.attribute {\n  color: #755f00;\n}\n\n.token.class-name,\n.token.key,\n.token.parameter,\n.token.property,\n.token.property-access,\n.token.variable {\n  color: #005a8e;\n}\n\n.token.attr-value,\n.token.inserted,\n.token.color,\n.token.selector .token.value,\n.token.string,\n.token.string .token.url-link {\n  color: #585858;\n}\n\n.token.builtin,\n.token.keyword-array,\n.token.package,\n.token.regex {\n  color: #af00af;\n}\n\n.token.function,\n.token.selector .token.class,\n.token.selector .token.id {\n  color: #7c00aa;\n}\n\n.token.atrule .token.rule,\n.token.combinator,\n.token.keyword,\n.token.operator,\n.token.pseudo-class,\n.token.pseudo-element,\n.token.selector,\n.token.unit {\n  color: #2d4ddf;\n}\n\n.token.deleted,\n.token.important {\n  color: #c22f2e;\n}\n\n.token.keyword-this,\n.token.this {\n  color: #005a8e;\n}\n\n.token.important,\n.token.keyword-this,\n.token.this,\n.token.bold {\n  font-weight: bold;\n}\n\n.token.delimiter.important {\n  font-weight: inherit;\n}\n\n.token.italic {\n  font-style: italic;\n}\n\n.token.entity {\n  cursor: help;\n}\n\n.language-markdown .token.title,\n.language-markdown .token.title .token.punctuation {\n  color: #005a8e;\n  font-weight: bold;\n}\n\n.language-markdown .token.blockquote.punctuation {\n  color: #af00af;\n}\n\n.language-markdown .token.code {\n  color: #006d6d;\n}\n\n.language-markdown .token.hr.punctuation {\n  color: #005a8e;\n}\n\n.language-markdown .token.url > .token.content {\n  color: #116b00;\n}\n\n.language-markdown .token.url-link {\n  color: #755f00;\n}\n\n.language-markdown .token.list.punctuation {\n  color: #af00af;\n}\n\n.language-markdown .token.table-header {\n  color: #111b27;\n}\n\n.language-json .token.operator {\n  color: #111b27;\n}\n\n.language-scss .token.variable {\n  color: #006d6d;\n}\n\n/* overrides color-values for the Show Invisibles plugin\n * https://prismjs.com/plugins/show-invisibles/\n */\n.token.tab:not(:empty):before,\n.token.cr:before,\n.token.lf:before,\n.token.space:before {\n  color: #3c526d;\n}\n\n/* overrides color-values for the Toolbar plugin\n * https://prismjs.com/plugins/toolbar/\n */\ndiv.code-toolbar > .toolbar a,\ndiv.code-toolbar > .toolbar button {\n  color: #e3eaf2;\n  background: #005a8e;\n}\n\ndiv.code-toolbar > .toolbar a:hover,\ndiv.code-toolbar > .toolbar a:focus,\ndiv.code-toolbar > .toolbar button:hover,\ndiv.code-toolbar > .toolbar button:focus {\n  color: #e3eaf2;\n  background: #005a8eda;\n  text-decoration: none;\n}\n\ndiv.code-toolbar > .toolbar span,\ndiv.code-toolbar > .toolbar span:hover,\ndiv.code-toolbar > .toolbar span:focus {\n  color: #e3eaf2;\n  background: #3c526d;\n}\n\n/* overrides color-values for the Line Highlight plugin\n * http://prismjs.com/plugins/line-highlight/\n */\n.line-highlight {\n  background: #8da1b92f;\n  background: linear-gradient(to right, #8da1b92f 70%, #8da1b925);\n}\n\n.line-highlight:before,\n.line-highlight[data-end]:after {\n  background-color: #3c526d;\n  color: #e3eaf2;\n  box-shadow: 0 1px #8da1b9;\n}\n\npre[id].linkable-line-numbers span.line-numbers-rows > span:hover:before {\n  background-color: #3c526d1f;\n}\n\n/* overrides color-values for the Line Numbers plugin\n * http://prismjs.com/plugins/line-numbers/\n */\n.line-numbers .line-numbers-rows {\n  border-right: 1px solid #8da1b97a;\n  background: #d0dae77a;\n}\n\n.line-numbers-rows > span:before {\n  color: #3c526dda;\n}\n\n/* overrides color-values for the Match Braces plugin\n * https://prismjs.com/plugins/match-braces/\n */\n.rainbow-braces .token.punctuation.brace-level-1,\n.rainbow-braces .token.punctuation.brace-level-5,\n.rainbow-braces .token.punctuation.brace-level-9 {\n  color: #753e00;\n}\n\n.rainbow-braces .token.punctuation.brace-level-2,\n.rainbow-braces .token.punctuation.brace-level-6,\n.rainbow-braces .token.punctuation.brace-level-10 {\n  color: #af00af;\n}\n\n.rainbow-braces .token.punctuation.brace-level-3,\n.rainbow-braces .token.punctuation.brace-level-7,\n.rainbow-braces .token.punctuation.brace-level-11 {\n  color: #005a8e;\n}\n\n.rainbow-braces .token.punctuation.brace-level-4,\n.rainbow-braces .token.punctuation.brace-level-8,\n.rainbow-braces .token.punctuation.brace-level-12 {\n  color: #7c00aa;\n}\n\n/* overrides color-values for the Diff Highlight plugin\n * https://prismjs.com/plugins/diff-highlight/\n */\npre.diff-highlight > code .token.deleted:not(.prefix),\npre > code.diff-highlight .token.deleted:not(.prefix) {\n  background-color: #c22f2e1f;\n}\n\npre.diff-highlight > code .token.inserted:not(.prefix),\npre > code.diff-highlight .token.inserted:not(.prefix) {\n  background-color: #116b001f;\n}\n\n/* overrides color-values for the Command Line plugin\n * https://prismjs.com/plugins/command-line/\n */\n.command-line-prompt {\n  border-right: 1px solid #8da1b97a;\n}\n\n.command-line-prompt > span:before {\n  color: #3c526dda;\n}\n"
  }
]