├── .github ├── ISSUE_TEMPLATE │ ├── bug.md │ ├── documentation.md │ ├── feature.md │ ├── proposal.md │ └── question.md ├── pull_request_template.md └── workflows │ ├── Watcher.yml │ ├── conflicts.yml │ └── main.yml ├── .gitignore ├── ARTICLE-TEMPLATE.mdx ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── babel.config.js ├── blog └── welcome-to-neoalgo-docs.md ├── doc-guideline.md ├── docs ├── backtracking │ ├── backtracking.md │ └── n-queens.mdx ├── bit-manipulation │ ├── bit-manipulation.md │ ├── brian-kernighan-algorithm.md │ ├── reverse-bits.mdx │ └── toggle-kth-bit.mdx ├── code-playgrounds │ ├── java-playground.md │ └── python-playground.md ├── competitive-programming │ ├── N-Queens.mdx │ ├── activity-selection.mdx │ ├── all-permutations.mdx │ ├── anagram-numbers.md │ ├── balanced-brackets.mdx │ ├── bigmod-algorithm.mdx │ ├── competitive-programming.md │ ├── diameter-of-BT.mdx │ ├── dnf-sort.mdx │ ├── factorial-of-large-number.mdx │ ├── first-occurence-1.mdx │ ├── generate-subsequences.mdx │ ├── generate-valid-parantheses.mdx │ ├── identical-BT.mdx │ ├── left-view-of-BT.mdx │ ├── max-number-from-array.mdx │ ├── next-greatest-left.mdx │ ├── next-greatest-to-right.mdx │ ├── next-smallest-left.mdx │ ├── next-smallest-right.mdx │ ├── phone-keypad.mdx │ ├── postfix-to-prefix.mdx │ ├── prefix-sum-algorithm.mdx │ ├── reverse-of-string.mdx │ ├── reverse-words-in-string.mdx │ ├── right-view-of-BT.mdx │ ├── top-view-of-BT.mdx │ ├── wave-sort.mdx │ └── wine-selling.mdx ├── computational-geometry │ ├── computational-geometry.md │ └── jarvis-algorithm.md ├── create-a-blog-post.md ├── create-a-document.md ├── create-a-page.md ├── cryptography │ ├── affine-cipher.mdx │ ├── autokey-cipher.mdx │ ├── burrows-wheeler-transform.mdx │ ├── caesar-cipher.mdx │ ├── columnar-transposition-cipher.mdx │ ├── cryptography.mdx │ ├── hill-cipher.mdx │ ├── homophonic-cipher.mdx │ ├── keyword-cipher.mdx │ ├── playfair-cipher.mdx │ ├── railfence-cipher.mdx │ ├── vernam-cipher.mdx │ └── vigenere-cipher.mdx ├── data-structures │ ├── Circular-Linked-list.mdx │ ├── Singly-Linked-list.mdx │ ├── binary-search-tree.mdx │ ├── binary-tree.mdx │ ├── ceil_in_bst.mdx │ ├── circular-queue.mdx │ ├── data-structures.mdx │ ├── depth-of-tree.mdx │ ├── double-ended-queue.mdx │ ├── floor_in_bst.mdx │ ├── height_BST.mdx │ ├── infix-to-postfix.mdx │ ├── inorder_traversal.mdx │ ├── invert-binary-tree.mdx │ ├── maximum-in-bst.mdx │ ├── middle-element-of-LL.mdx │ ├── minimum-in-bst.mdx │ ├── palindromic-linked-list.mdx │ ├── postorder_traversal.mdx │ ├── preorder_traversal.mdx │ ├── queue.mdx │ ├── size-of-binary-tree.mdx │ ├── stack-data-structure.mdx │ ├── swap-nodes-in-LL.mdx │ └── tower-of-hanoi.mdx ├── doc-guideline.md ├── dynamic-programming │ ├── catalan-number.mdx │ ├── coin-change-problem.mdx │ ├── cutting-a-rod.mdx │ ├── dynamic-programming.md │ ├── edit-distance.mdx │ ├── egg-dropping-problem.md │ ├── equal-sum-partition.mdx │ ├── golomb-sequence.mdx │ ├── kadane-algorithm.mdx │ ├── median-of-two-arrays.mdx │ ├── painting-fence.mdx │ └── unbounded-knapsack.mdx ├── getting-started.md ├── graph-algorithms │ ├── breadth-first-search.md │ ├── depth-first-search.mdx │ ├── fractional-knapsack.mdx │ ├── graph-algorithms.md │ ├── kosarajus-algorithm.mdx │ ├── kruskals-algorithm.mdx │ ├── prims-algorithm.mdx │ └── topological-sorting.mdx ├── introduction │ ├── About-NeoAlgo.md │ ├── contributor-handbook.md │ └── development-setup.md ├── machine-learning │ ├── linear-regression.md │ └── machine-learning.md ├── markdown-features.mdx ├── mathematics │ ├── Kth-smallest.mdx │ ├── ackermann-function.mdx │ ├── anagram-number.mdx │ ├── anti-diagonal-traversal-of-matrix.mdx │ ├── armstrong-number.mdx │ ├── automorphic-number.mdx │ ├── binary-exponentiation.mdx │ ├── boolean-matrix.mdx │ ├── catalan-number.mdx │ ├── count-bits.mdx │ ├── count-of-digits.mdx │ ├── count-of-divisors.mdx │ ├── decimal-to-binary.mdx │ ├── double-factorial.mdx │ ├── euler-totient-function.mdx │ ├── extended-euclidean-Algorithm.mdx │ ├── factorial-of-number.mdx │ ├── fibonacci-recursion.mdx │ ├── gcd-of-two-numbers.mdx │ ├── hamming-distance.mdx │ ├── happy-number.mdx │ ├── hexagonal-number.mdx │ ├── krishnamurthy-number.mdx │ ├── lcm-of-two-numbers.mdx │ ├── lucas-theorem.mdx │ ├── lucky-numbers.mdx │ ├── magic-number.mdx │ ├── mathematics.md │ ├── matrix-addition.mdx │ ├── matrix-multiplication.mdx │ ├── matrix-transpose.mdx │ ├── mystery-number.mdx │ ├── neon-number.mdx │ ├── next-permutation.mdx │ ├── next-prime-number.mdx │ ├── noble-integer.mdx │ ├── number-power-of-2.mdx │ ├── occurrence-of-no.-in-array.mdx │ ├── palindrome-number.mdx │ ├── pascal-triangle.mdx │ ├── perfect-cube.mdx │ ├── perfect-number.mdx │ ├── perfect-square.mdx │ ├── power-linear.mdx │ ├── prime-number.mdx │ ├── product-of-count-of-bits-of-each-elements.mdx │ ├── reverse-a-number.mdx │ ├── rotate-matrix-by-90-degree.mdx │ ├── row-with-max-one.mdx │ ├── searching-in-matrix.mdx │ ├── sieve-of-eratosthenes.mdx │ ├── smallest-prime-factor-of-any-number.mdx │ ├── snake-traversal-of-matrix.mdx │ ├── spiral-traversal-of-matrix.mdx │ ├── sum-of-digits.mdx │ ├── sum-of-divisors.mdx │ ├── tetrahedral-number.mdx │ ├── triangular-numbers.mdx │ └── ugly-numbers.mdx ├── miscellaneous │ ├── miscellaneous.md │ ├── moore-voting-algorithm.mdx │ └── sudoku-solver.md ├── operating-systems │ ├── banker-algorithm.md │ └── operating-systems.md ├── searching-algorithms │ ├── binary-search.mdx │ ├── exponential-search.mdx │ ├── interpolation-search.mdx │ ├── jump-search.mdx │ ├── linear-search.mdx │ ├── searching-algorithms.mdx │ └── two-pointer.mdx ├── sorting-algorithms │ ├── bead-sort.mdx │ ├── bubble-sort.md │ ├── circle-sort.mdx │ ├── cocktail-sort.mdx │ ├── counting-sort.mdx │ ├── heap-sort.mdx │ ├── insertion-sort.mdx │ ├── merge-sort.mdx │ ├── quick-sort.mdx │ ├── radix-sort.mdx │ ├── selection-sort.mdx │ ├── shell-sort.mdx │ ├── sleep-sort.mdx │ ├── sorting-algorithms.md │ ├── stooge-sort.mdx │ └── wiggle-sort.mdx └── thank-you.md ├── docusaurus.config.js ├── package.json ├── sidebars.js ├── src ├── components │ └── comments │ │ ├── index.js │ │ ├── styles.css │ │ └── styles.module.css ├── css │ └── custom.css ├── pages │ ├── index.js │ ├── markdown-page.md │ ├── styles.module.css │ └── team.md └── theme │ └── DocItem │ └── index.js ├── static ├── .nojekyll ├── img │ ├── favicon.ico │ ├── logo.svg │ ├── main-logo.png │ ├── powered-by-vercel.svg │ ├── pwa │ │ ├── android │ │ │ ├── android-launchericon-144-144.png │ │ │ ├── android-launchericon-192-192.png │ │ │ ├── android-launchericon-48-48.png │ │ │ └── android-launchericon-512-512.png │ │ ├── chrome │ │ │ ├── chrome-estension-48-48.png │ │ │ ├── chrome-favicon-16-16.png │ │ │ └── chrome-installicon-128-128.png │ │ └── firefox │ │ │ ├── firefox-general-128-128.png │ │ │ ├── firefox-general-16-16.png │ │ │ ├── firefox-general-48-48.png │ │ │ └── firefox-marketplace-512-512.png │ ├── tesseract-coding-algorithms.svg │ ├── tesseract-coding-programming.svg │ └── tesseract-coding-trees.svg └── manifest.json └── yarn.lock /.github/ISSUE_TEMPLATE/bug.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🐛 Bug Report 3 | about: Submit a bug report to help us improve 4 | labels: "bug" 5 | --- 6 | 7 | ## 🐛 Bug Report 8 | 9 | (A clear and concise description of what the bug is.) 10 | 11 | ### Have you read the [Contributing Guidelines on Pull Requests](https://github.com/TesseractCoding/NeoAlgo/blob/master/CONTRIBUTING.md#reporting-new-issues)? 12 | 13 | (Write your answer here.) 14 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/documentation.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 📚 Documentation 3 | about: Report an issue related to documentation 4 | labels: "documentation" 5 | --- 6 | 7 | ## 📚 Documentation 8 | 9 | (A clear and concise description of what the issue is.) 10 | 11 | ### Have you read the [Contributing Guidelines on Pull Requests](https://github.com/TesseractCoding/NeoAlgo/blob/master/CONTRIBUTING.md#reporting-new-issues)? 12 | 13 | (Write your answer here.) 14 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🚀 Feature 3 | about: Submit a proposal for a new feature 4 | labels: "feature" 5 | --- 6 | 7 | ## 🚀 Feature 8 | 9 | (A clear and concise description of what the feature is.) 10 | 11 | ### Have you read the [Contributing Guidelines on Pull Requests](https://github.com/TesseractCoding/NeoAlgo/blob/master/CONTRIBUTING.md#reporting-new-issues)? 12 | 13 | (Write your answer here.) 14 | 15 | ## Motivation 16 | 17 | (Please outline the motivation for the proposal.) 18 | 19 | ## Pitch 20 | 21 | (Please explain why this feature should be implemented and how it would be used.) 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/proposal.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 💥 Proposal 3 | about: Propose a non-trivial change to NeoAlgo 4 | labels: "proposal" 5 | --- 6 | 7 | ## 💥 Proposal 8 | 9 | (A clear and concise description of what the proposal is.) 10 | 11 | ### Have you read the [Contributing Guidelines on Pull Requests](https://github.com/TesseractCoding/NeoAlgo/blob/master/CONTRIBUTING.md#reporting-new-issues)? 12 | 13 | (Write your answer here.) 14 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: ❓ Questions and Help 3 | about: If you have questions, please check the below links 4 | labels: "question" 5 | --- 6 | 7 | ## ❓ Questions and Help 8 | 9 | ### Please note that this issue tracker is not a help form and this issue will be closed. 10 | 11 | Please contact us instead. 12 | 13 | - [Website](https://www.tesseractcoding.tech/) 14 | - [Email](team@tesseractcoding.tech) 15 | - [GitHub](https://github.com/TesseractCoding) 16 | - [Instagram](https://www.instagram.com/tesseractcoding/) 17 | - [LinkedIn](https://www.linkedin.com/company/tesseract-coding/) 18 | - [Medium](https://medium.com/tesseract-coding) 19 | - [Telegram](https://t.me/tesseractcoding) 20 | - [YouTube](https://www.youtube.com/c/TesseractCoding/) 21 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 10 | 11 | ### Have you read the [Contributing Guidelines on Pull Requests](https://github.com/TesseractCoding/NeoAlgo/blob/master/CONTRIBUTING.md#pull-requests)? 12 | 13 | (Write your answer here.) 14 | 15 | ### Description 16 | 17 | (Write your answer here.) 18 | 19 | ### Checklist 20 | 21 | - [ ] I've read the contribution guidelines. 22 | - [ ] I've checked the issue list before deciding what to submit. 23 | - [ ] I've edited the `README.md` and link to my code. 24 | 25 | ## Related Issues or Pull Requests 26 | 27 | (Write your answer here.) 28 | -------------------------------------------------------------------------------- /.github/workflows/Watcher.yml: -------------------------------------------------------------------------------- 1 | name: Issue_watcher 2 | 3 | on: 4 | issues: 5 | types: [opened] 6 | 7 | jobs: 8 | first-job: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout code 12 | uses: actions/checkout@main 13 | - name: Run Action 14 | uses: TesseractCoding/Issue_Watcher@main 15 | with: 16 | token: '${{ secrets.GITHUB_TOKEN }}' 17 | author: '${{github.actor}}' 18 | repo: TesseractCoding/NeoAlgo-Docs 19 | maxIssue: 2 20 | -------------------------------------------------------------------------------- /.github/workflows/conflicts.yml: -------------------------------------------------------------------------------- 1 | name: 'Merge Conflict Watcher' 2 | on: 3 | pull_request: 4 | types: [opened, synchronize, edited] 5 | branches: 6 | - main 7 | pull_request_review_comment: 8 | types: [created, deleted] 9 | jobs: 10 | triage: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: mschilde/auto-label-merge-conflicts@master 14 | with: 15 | CONFLICT_LABEL_NAME: 'merge-conflicts' 16 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 17 | MAX_RETRIES: 5 18 | WAIT_MS: 5000 19 | create_comment: 20 | needs: triage 21 | runs-on: ubuntu-latest 22 | steps: 23 | - uses: actions/checkout@v2 24 | - uses: actions-ecosystem/action-create-comment@v1 25 | if: contains(github.event.pull_request.labels.*.name, 'merge-conflicts') 26 | with: 27 | github_token: ${{ secrets.GITHUB_TOKEN }} 28 | body: | 29 | Hello, @${{ github.actor }}! Your pull request has merge conflicts with the base branch. You can resolve those conflicts by following the instructions [here.](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/resolving-a-merge-conflict-using-the-command-line) 30 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Build and test 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | jobs: 11 | test: 12 | runs-on: ${{matrix.os}} 13 | strategy: 14 | matrix: 15 | os: 16 | - ubuntu-18.04 17 | node-version: 18 | - 12.x 19 | steps: 20 | - name: Checkout 21 | uses: actions/checkout@master 22 | - name: setup node ${{matrix.node-version}} 23 | uses: actions/setup-node@v1.4.4 24 | with: 25 | node-version: ${{matrix.node-version}} 26 | - name: Get yarn cache directory path 27 | id: yarn-cache-dir-path 28 | run: echo "::set-output name=dir::$(yarn cache dir)" 29 | 30 | - uses: actions/cache@v2 31 | id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`) 32 | with: 33 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 34 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 35 | restore-keys: | 36 | ${{ runner.os }}-yarn- 37 | - name: install packages 38 | run: yarn install 39 | - name: build 40 | run: yarn build -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Dependencies 2 | /node_modules 3 | 4 | # Production 5 | /build 6 | 7 | # Generated files 8 | .docusaurus 9 | .cache-loader 10 | 11 | # Misc 12 | .DS_Store 13 | .env.local 14 | .env.development.local 15 | .env.test.local 16 | .env.production.local 17 | .idea 18 | 19 | npm-debug.log* 20 | yarn-debug.log* 21 | yarn-error.log* 22 | -------------------------------------------------------------------------------- /ARTICLE-TEMPLATE.mdx: -------------------------------------------------------------------------------- 1 | // Guideline : Copy the raw version of this file before making any changes 2 | 3 | --- 4 | title: Title 5 | slug: /Folder name/file name 6 | --- 7 | 8 | ## Introduction 9 | 10 | //write here in single line 11 | 12 | ## Explanation 13 | 14 | // write here in single line 15 | 16 | Let's have one example: 17 | ``` 18 | Give example here 19 | ``` 20 | 21 | ## Algorithm 22 | 23 | //write here in bullet point format or pseudo code 24 | 25 | ## Code 26 | 27 | import Tabs from '@theme/Tabs'; 28 | import TabItem from '@theme/TabItem'; 29 | 30 | 37 | 38 | 39 | ```cpp/java 40 | //start writing here 41 | ``` 42 | 43 | 44 | 45 | 46 | ```py 47 | //start writing here 48 | ``` 49 | 50 | 51 | 52 | 53 | ## Sample Input and Output 54 | 55 | ### Input: 56 | 57 | ``` 58 | //write here 59 | ``` 60 | 61 | ### Output: 62 | 63 | ``` 64 | //write here 65 | ``` 66 | 67 | ## Complexity Analysis 68 | 69 | - Time complexity - 70 | - Space complexity - 71 | 72 | ## Credits 73 | 74 | - [name](github profile-link) contributed the [C++/Java implementation](Code link from NeoAlgo) 75 | - [name](github profile-link) contributed the [Python implementation](Code link from NeoAlgo) 76 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Tesseract Coding 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NeoAlgo-Docs 2 | 3 | Bringing an all Open-Source Platform to study Data Structures and Algorithms ⚡ 4 | 5 | ## 🔧 Installation 6 | 7 | You will need to have NodeJS and Yarn installed, if you haven't done that yet - get started [here](https://nodejs.org/en/download/) and [here](https://yarnpkg.com/lang/en/docs/install/). Then, follow the steps below ⬇️ 8 | 9 | ``` 10 | $ git clone git@github.com:TesseractCoding/NeoAlgo-Docs.git 11 | $ cd NeoAlgo-Docs 12 | $ yarn 13 | $ yarn start 14 | ``` 15 | Finally, navigate to http://localhost:3000 and you should see our app is now up and running ⚡ 16 | 17 | [![Powered by Vercel](./static/img/powered-by-vercel.svg)](https://vercel.com?utm_source=NeoAlgo-Docs&utm_campaign=oss/) -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [require.resolve('@docusaurus/core/lib/babel/preset')], 3 | }; 4 | -------------------------------------------------------------------------------- /blog/welcome-to-neoalgo-docs.md: -------------------------------------------------------------------------------- 1 | --- 2 | slug: welcome-to-neoalgo-docs 3 | title: Welcome to NeoAlgo Docs 4 | author: Harsh Mishra 5 | author_title: Tesseract Coding Core Team 6 | author_url: https://github.com/harshcasper 7 | author_image_url: https://i.imgur.com/Owk4NoA.jpg 8 | tags: [welcome, neoalgo, announcement] 9 | --- 10 | 11 | Welcome to NeoAlgo Docs! -------------------------------------------------------------------------------- /docs/backtracking/backtracking.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Backtracking 3 | slug: /backtracking 4 | --- 5 | 6 | This page would serve our needs for documentation of the Backtracking algorithms. -------------------------------------------------------------------------------- /docs/bit-manipulation/bit-manipulation.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Bit Manipulation 3 | slug: /bit-manipulation 4 | --- 5 | 6 | This page would serve our needs for documentation of Bit Manipulation Algorithms. -------------------------------------------------------------------------------- /docs/bit-manipulation/brian-kernighan-algorithm.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Brian Kernighan Algorithm 3 | slug: /bit-manipulation/brian-kernighan-algorithm 4 | --- 5 | 6 | This page would serve our needs for documentation of the Brian Kernighan Algorithm. -------------------------------------------------------------------------------- /docs/bit-manipulation/toggle-kth-bit.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Toggle K'th bit 3 | slug: /bit-manipulation/toggle-kth-bit 4 | --- 5 | 6 | ## Introduction 7 | 8 | Given a number, toggle the `k`'th bit of the given number, i.e. If the `k`th bit is `1` toggle it to `0` else if it is `0`, toggle it to `1`. Inorder to solve the problem, it is good to have knowledge about Left and Right shift bit operations. The left shift operation denoted by `x<>y` shifts `y` number of bits in `x` to right. It is equivalent to dividing `x` with `2^y`. 9 | 10 | ## Explanation 11 | 12 | Consider a number `n` = `24`. Assume that we have to toggle the `k` = `3`th bit. 13 | 14 | ``` 15 | Consider n = 24, k = 3 16 | 17 | Binary equivalent of n = 11000 18 | Here the third bit is '0'. So we need to toggle it to '1'. 19 | 20 | Binary equivalent of n after toggling its third bit(from the LSB) = 11100 (28) 21 | ``` 22 | 23 | Hence `28` is the number obtained after toggling the k'th bit. 24 | 25 | ## Algorithm 26 | 27 | Let us assume that the given number be `n` and the value of k be `k` 28 | 29 | - Set `temp` the value of 1 with its bits shifted to left by `k-1` places 30 | - Set `ans` the value of `n` xor `temp` 31 | - Return `ans` 32 | 33 | ## Code 34 | 35 | import Tabs from "@theme/Tabs"; 36 | import TabItem from "@theme/TabItem"; 37 | 38 | 45 | 46 | 47 | 48 | ```cpp 49 | /* 50 | Program to Toggle kth bit of a number. 51 | Given a number we want to toggle the kth bit of a number . 52 | 53 | Ex:-6 (110) and k=2 54 | after toggling 2nd bit our number would be (100) 4. 55 | Approach: 56 | firstly we will left shift the given number k-1 times. 57 | After then we will xor the left shifted result with given number and return 58 | */ 59 | 60 | #include 61 | using namespace std; 62 | 63 | int toggle_k_bit(int n,int k) 64 | { 65 | int temp=1<<(k-1); 66 | 67 | return n^temp; 68 | } 69 | 70 | int main() 71 | { 72 | int n,k; 73 | 74 | cout<<"Enter the number: "; 75 | cin>>n; 76 | cout<<"Enter the value of k(where you need to toggle the k'th bit): "; 77 | cin>>k; 78 | 79 | cout<<"The given number, after toggling the k-th bit is "<< toggle_k_bit(n,k)<<"\n"; 80 | 81 | return 0; 82 | } 83 | 84 | ``` 85 | 86 | 87 | 88 | 89 | ```python 90 | # Python program to toggle the k-th bit of a number. 91 | def toggle(num, k): 92 | return (num ^ (1 << (k-1))) 93 | 94 | 95 | if __name__ == '__main__': 96 | print("Enter the number: ", end="") 97 | n = int(input()) 98 | print("Enter the value of k(where you need to toggle the k'th bit): ", end="") 99 | b = int(input()) 100 | res = toggle(n, b) 101 | print("The given number, after toggling the k-th bit is {}".format(res)) 102 | 103 | ``` 104 | 105 | 106 | 107 | 108 | ## Sample Input and Output 109 | 110 | #### Input 111 | 112 | ``` 113 | Enter the number: 33 114 | Enter the value of k(where you need to toggle the k'th bit): 12 115 | ``` 116 | 117 | #### Output 118 | 119 | ``` 120 | The given number, after toggling the k-th bit is 2081. 121 | ``` 122 | 123 | ## Complexity Analysis 124 | 125 | - Time complexity - `O(1)` 126 | - Space complexity - `O(1)` 127 | 128 | ## Credits 129 | 130 | - [Faiz Alam](https://github.com/zhcet19) for the [C++ Implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/Bit--Manipulation/togglebit.cpp) 131 | - [Hari Krishnan U](https://github.com/Harikrishnan6336) for the [Python Implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/Python/Bit--Manipulation/toggle_kth_bit.py) 132 | -------------------------------------------------------------------------------- /docs/code-playgrounds/java-playground.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Java Playground 3 | slug: /code-playgrounds/java 4 | --- 5 | 6 | Run your Java code on the fly with the **Java Plaground**. The Java Playground currently supports Java programming language and you can use the live interactive code editor to test your algorithmic skills. We are using [Trinket](https://trinket.io/) for our purpose and it is highly advisable to have your progress saved by remixing the Trinket. Happy Hacking! 7 | 8 | 9 | -------------------------------------------------------------------------------- /docs/code-playgrounds/python-playground.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Python Playground 3 | slug: /code-playgrounds/python 4 | --- 5 | 6 | Run your Python code on the fly with the **Python Plaground**. The Python Playground currently supports Python-3 programming language and you can use the live interactive code editor to test your algorithmic skills. We are using [Trinket](https://trinket.io/) for our purpose and it is highly advisable to have your progress saved by remixing the Trinket. Happy Hacking! 7 | 8 | -------------------------------------------------------------------------------- /docs/competitive-programming/all-permutations.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: All Permutations of a string 3 | slug: /competitive-programming/all-permutations 4 | --- 5 | 6 | ## Introduction 7 | 8 | You are given a string containing numbers, the task is to print all the permutations of the entered string. 9 | 10 | ## Explanation 11 | 12 | First we can input the string from the user, 13 | At first we will include the first character of the string and then recursively call the function to include the permutations starting with it. 14 | Likewise we will visit the second character, make recursive calls to include the permutations starting with it. 15 | And at last when all the characters are visited, we get all possible permutations. 16 | 17 | Let's have few examples: 18 | ``` 19 | Input 1: 20 | abc 21 | Output 1: 22 | abc 23 | acb 24 | bac 25 | bca 26 | cab 27 | cba 28 | Input 2: 29 | def 30 | Output 2: 31 | def 32 | dfe 33 | edf 34 | efd 35 | fde 36 | fed 37 | ``` 38 | 39 | ## Algorithm 40 | 41 | - If the input string reaches its end 42 | - Print the string 43 | 44 | - make a for loop of 'j' from 0 to end of the string 45 | - swap the elements in[i] and in[j] 46 | - Make a recursive call furthur to incorporate furthur permutations 47 | - Backtrack by swapping again 48 | 49 | ## Code 50 | 51 | import Tabs from '@theme/Tabs'; 52 | import TabItem from '@theme/TabItem'; 53 | 54 | 61 | 62 | 63 | ```cpp 64 | #include 65 | using namespace std; 66 | 67 | void permute(string in, int i) 68 | { 69 | if(in[i]=='\0') 70 | { 71 | cout<>in; 87 | cout<<"all permutations are: "< 93 | 94 | 95 | 96 | ```python 97 | # All permutations 98 | def permutations(word): 99 | if len(word)==1: 100 | return [word] 101 | perms=permutations(word[1:]) 102 | char=word[0] 103 | result=[] 104 | for perm in perms: 105 | for i in range(len(perm)+1): 106 | result.append(perm[:i]+char+perm[i:]) 107 | return result 108 | 109 | word=input("Enter string: ") 110 | print(permutations(word)) 111 | ``` 112 | 113 | 114 | 115 | 116 | ## Sample Input and Output 117 | 118 | #### Input : 119 | 120 | ``` 121 | abc 122 | ``` 123 | 124 | #### Output : 125 | 126 | ``` 127 | abc 128 | acb 129 | bac 130 | bca 131 | cab 132 | cba 133 | ``` 134 | 135 | ## Complexity Analysis 136 | 137 | - Time Complexity: `O(N)` 138 | - Space Complexity: `O(N)` 139 | -------------------------------------------------------------------------------- /docs/competitive-programming/anagram-numbers.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Anagram Numbers 3 | slug: /competitive-programming/anagram-numbers 4 | --- 5 | 6 | This page would serve our needs for documentation of the Anagram Numbers. -------------------------------------------------------------------------------- /docs/competitive-programming/competitive-programming.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Competitive Programming 3 | slug: /competitive-programming 4 | --- 5 | 6 | This page would serve our needs for documentation of the Competitive Programming codes. -------------------------------------------------------------------------------- /docs/competitive-programming/dnf-sort.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Dutch National Flag 3 | slug: /competitive-programming/dnf-sort 4 | --- 5 | 6 | ## Introduction 7 | Given an unsorted array consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. 8 | The functions should put all 0s first, then all 1s and all 2s in last. 9 | 10 | ## Explanation 11 | 12 | First we will take a mid pointer which will be initialised to 0, a high pointer initialised to n-1 and a low pointer initialized to 0. 13 | Now while mid pointer is less than high pointer, swap the mid pointer with the low pointer, this will bring all the zeros at the start. 14 | Likewise if we encounter a one, then we won't swap anything because the ones are supposed to be in the middle of the array. 15 | If we encounter a two, then we swap the mid and the high pointers, this will bring all the twos at the end. 16 | 17 | Let's have few examples: 18 | ``` 19 | Input 1: 20 | 5 21 | 1 2 0 2 1 22 | Output 1: 23 | 0 1 1 2 2 24 | Input 2: 25 | 7 26 | 1 2 0 2 1 2 1 27 | Output 2: 28 | 0 1 1 1 2 2 2 29 | ``` 30 | 31 | ## Algorithm 32 | 33 | - Take the input array 34 | - lo=0,mid=0,hi=n-1 35 | - while mid <= hi 36 | - if array[mid]=0 37 | - swap array[mid], array[lo] 38 | - increment lo and mid pointers 39 | - if array[mid]=1 40 | - increment mid pointer 41 | - if array[hi]=2 42 | - swap array[mid], array[hi] 43 | - decrement mid 44 | 45 | ## Code 46 | 47 | import Tabs from '@theme/Tabs'; 48 | import TabItem from '@theme/TabItem'; 49 | 50 | 57 | 58 | 59 | ```cpp 60 | #include 61 | using namespace std; 62 | 63 | void DNFSort(int arr[],int n ) 64 | { 65 | int lo = 0; 66 | int mid = 0; 67 | int hi = n-1; 68 | while(mid<=hi) 69 | { 70 | if(arr[mid] == 0) 71 | { 72 | swap(arr[mid], arr[lo]); 73 | lo++; 74 | mid++; 75 | } 76 | else if(arr[mid] == 1) 77 | { 78 | mid++; 79 | } 80 | else if(arr[mid] == 2) 81 | { 82 | swap(arr[mid], arr[hi]); 83 | hi--; 84 | } 85 | } 86 | return; 87 | } 88 | 89 | int main() 90 | { 91 | int n; 92 | cout<<"Enter total numbers: "<>n; 94 | int arr[1000]; 95 | cout<<"Enter array elements: "<>arr[i]; 99 | } 100 | DNFSort(arr, n); 101 | cout<<"Sorted array is: "< 111 | 112 | 113 | 114 | ```python 115 | # Dutch National Flag Sort 116 | def dnf_sort(alist): 117 | lo = 0 118 | mid = 0 119 | hi = len(alist) - 1 120 | while mid<=hi: 121 | if alist[mid]==0: 122 | alist[mid],alist[lo] = alist[lo],alist[mid] 123 | lo=lo+1 124 | mid=mid+1 125 | if alist[mid]==1: 126 | mid=mid+1 127 | if alist[mid]==2: 128 | alist[mid],alist[hi] = alist[hi],alist[mid] 129 | hi=hi-1 130 | 131 | alist = input('Enter the list of numbers: ').split() 132 | alist = [int(x) for x in alist] 133 | dnf_sort(alist) 134 | print('Sorted list: ', end='') 135 | print(alist) 136 | ``` 137 | 138 | 139 | 140 | 141 | ## Sample Input and Output 142 | 143 | #### Input : 144 | 145 | ``` 146 | 5 147 | 1 2 0 2 1 148 | ``` 149 | 150 | #### Output : 151 | 152 | ``` 153 | 0 1 1 2 2 154 | ``` 155 | 156 | ## Complexity Analysis 157 | 158 | - Time Complexity: `O(N)` 159 | - Space Complexity: `O(N)` -------------------------------------------------------------------------------- /docs/competitive-programming/first-occurence-1.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: First occurence of 1 in a sorted array of 0 and 1 3 | slug: /competitive-programming/first-occurence-1 4 | --- 5 | 6 | ## Introduction 7 | 8 | Given an array of 0s and 1s in the sorted array, our objective is to find the position of the occurence of the first `1`. 9 | 10 | ## Explanation 11 | 12 | Binary search algorithm is used in the problem. We divide the array continuously into halves and search for the first index of `1` in each subparts. Let us take an example to illustrate the same. Let the array be `0,0,1,1`. 13 |
14 | 15 | ## Algorithm 16 | 17 | - Find the middle index. 18 | - Check whether the element at the middle index is `1` or not. 19 | - Check whether the middle index is zero or whether the element at the position just before the middle index is zero or not. 20 | - If the above conditions are true then the middle index is the first occurrence of `1` in the array. 21 | - If the middle index is not zero and the element at the position just before the middle index is not zero: 22 | - Then repeat the above process for the subarray before the middle index if the middle element is `1`. 23 | - Then repeat the above process for the right subarray if the middle element is not `1`. 24 | 25 | ## Examples 26 | 27 | #### Example 1 28 | 29 | ``` 30 | Let the array be 0,1,1. 31 | The lower index is 0 and upper index is 2. 32 | The middle index is 1. 33 | The element present at index 1 is 1 and the element before it is 0. 34 | So the index 1 is the first occurence of first 1 in array. The position is 2. 35 | ``` 36 | 37 | #### Example 2 38 | 39 | ``` 40 | Let the array be 0,0. 41 | The lower index is 0 and upper index is 1. 42 | The middle index is 0. 43 | The element at the middle index is 0. 44 | The lower index is changed to middle index+1. 45 | However the lower index has become equal to the upper index. So -1 is returned. Occurence of 1 not found. 46 | ``` 47 | 48 | ## Code 49 | 50 | import Tabs from "@theme/Tabs"; 51 | import TabItem from "@theme/TabItem"; 52 | 53 | 59 | 60 | 61 | 62 | ```cpp 63 | #include 64 | using namespace std; 65 | int binSearch(int a[],int n) 66 | { 67 | int l=0,r=n-1,mid=0; 68 | while(l<=r) 69 | { 70 | mid=(l+r)/2; 71 | if(a[mid]==1 && (mid==0 || a[mid-1]==0)) 72 | return mid+1; 73 | else if(a[mid]==1) 74 | r=mid-1; 75 | else l=mid+1; 76 | } 77 | return -1; 78 | } 79 | int main() 80 | { 81 | cout<<"Enter the number of elements: "; 82 | int n; 83 | cin>>n; 84 | int a[n]; 85 | cout<<"Enter only 1 and 0 in sorted order\n"; 86 | for(int i=0;i>a[i]; 88 | sort(a,a+n); 89 | cout<<"Position of the first 1 = "< 93 | 94 | 95 | ## Sample Input and Output 96 | 97 | #### Input 98 | 99 | ``` 100 | Enter the number of elements: 5 101 | Enter only 1 and 0 in sorted order 102 | 1 1 1 1 1 103 | ``` 104 | ### Output 105 | ``` 106 | Position of the first 1 = 1 107 | ``` 108 | 109 | ### Input 110 | 111 | ``` 112 | Enter the number of elements: 3 113 | Enter only 1 and 0 in sorted order 114 | 0 0 1 115 | ``` 116 | 117 | ### Output 118 | ``` 119 | Position of the first 1 = 3 120 | ``` 121 | 122 | ## Complexity Analysis 123 | 124 | * Time Complexity: `O(nlogn)` 125 | * Space Complexity : `O(1)` 126 | 127 | ## Credit 128 | 129 | * [Sayani Mallick](https://github.com/SAY-droid427/) for the [C++ implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/cp/first1_binsearch.cpp) 130 | -------------------------------------------------------------------------------- /docs/competitive-programming/generate-subsequences.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Generate All Subsequences of a String 3 | slug: /competitive-programming/generate-subsequences 4 | --- 5 | 6 | ## Introduction 7 | 8 | Given a string containing n characters, find out all the subsequences of the string. 9 | 10 | ## Explanation 11 | 12 | We can do it by first taking an empty string. Initially, there will be two separate cases, 13 | Firstly, including the current character in the output string and then recursively calling the function. 14 | The second will be, excluding the current encountered character and then recursively calling the function. 15 | 16 | Let's have few examples: 17 | ``` 18 | Input 1: 19 | Enter string: 20 | abc 21 | Output 1: 22 | The subsequences are: abc ab ac a bc b c 23 | Input 2: 24 | Enter string: 25 | abcd 26 | Output 2: 27 | The subsequences are: abcd abc abd ab acd ac ad a bcd bc bd b cd c d 28 | ``` 29 | 30 | ## Algorithm 31 | 32 | - Initialize an empty array(out) 33 | - If the input string reaches its end 34 | - Add a NULL character at the end 35 | - Print the subsequence 36 | 37 | - Include the current character out[j]=in[i] 38 | - recursively call the function 39 | 40 | - Exclude the current character 41 | - recursively call the function 42 | 43 | ## Code 44 | 45 | import Tabs from '@theme/Tabs'; 46 | import TabItem from '@theme/TabItem'; 47 | 48 | 55 | 56 | 57 | ```cpp 58 | #include 59 | using namespace std; 60 | 61 | void generate_subsequence(char *in,char *out,int i,int j) 62 | { 63 | if(in[i]=='\0') 64 | { 65 | out[j]='\0'; 66 | cout<>input; 81 | cout<<"The subsequences are: "; 82 | generate_subsequence(input,output,0,0); 83 | return 0; 84 | } 85 | ``` 86 | 87 | 88 | 89 | 90 | ```python 91 | # Generate all subsets of a string 92 | def printSubsets(str,output): 93 | if len(str)==0: 94 | print(output) 95 | return 96 | printSubsets(str[1:],output) 97 | newOutput=output+str[0] 98 | printSubsets(str[1:],newOutput) 99 | return 100 | 101 | if __name__ == '__main__': 102 | str=input("Enter string: ") 103 | printSubsets(str,"") 104 | ``` 105 | 106 | 107 | 108 | 109 | ## Sample Input and Output 110 | 111 | #### Input : 112 | 113 | ``` 114 | Enter string: 115 | abc 116 | ``` 117 | 118 | #### Output : 119 | 120 | ``` 121 | The subsequences are: abc ab ac a bc b c 122 | ``` 123 | 124 | ## Complexity Analysis 125 | 126 | - Time Complexity: `O(N)` 127 | - Space Complexity: `O(N)` 128 | -------------------------------------------------------------------------------- /docs/competitive-programming/generate-valid-parantheses.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Generate Valid Parantheses 3 | slug: /competitive-programming/generate-valid-parantheses 4 | --- 5 | 6 | ## Introduction 7 | 8 | You are given a number `n`, and your job is to find all the n balanced parentheses combinations possible. 9 | 10 | ## Explanation 11 | 12 | We can do it by first taking an empty string. First, we can place either an opening or a closing bracket, but by checking conditions, 13 | if the count of the opening brackets is less than the total number of brackets, then we can put an opening bracket. 14 | If the count of the closing brackets is less than that of the opening brackets, then we can put a closing bracket. 15 | We can recursively call the function and print when we reach twice the size of the number of brackets because that is the maximum number of brackets possible. 16 | 17 | Let's have few examples: 18 | ``` 19 | Input 1: 20 | 2 21 | Output 1: 22 | (()) 23 | ()() 24 | Input 2: 25 | 3 26 | Output 2: 27 | ((())) 28 | (()()) 29 | (())() 30 | ()(()) 31 | ()()() 32 | ``` 33 | 34 | ## Algorithm 35 | 36 | - Initialize open=0,close=0,index=0 37 | - If the current index is equal to (2*total) 38 | - Add a NULL character at the end 39 | - Print the character array 40 | 41 | - If open 61 | 62 | 63 | ```cpp 64 | #include 65 | using namespace std; 66 | 67 | void FindValidParenthesis(char *out, int n, int index, int open, int close) 68 | { 69 | if (index == 2 *n) 70 | { 71 | out[index] = '\0'; 72 | cout << out << endl; 73 | return; 74 | } 75 | 76 | //If the number of open brackets is less than n 77 | if (open < n) 78 | { 79 | out[index] = '('; 80 | FindValidParenthesis(out, n, index + 1, open + 1, close); 81 | } 82 | 83 | //If the number of close brackets is less than the number of open brackets 84 | if (close < open) 85 | { 86 | out[index] = ')'; 87 | FindValidParenthesis(out, n, index + 1, open, close + 1); 88 | } 89 | 90 | return; 91 | } 92 | 93 | int main() 94 | { 95 | int n; 96 | cin >> n; 97 | char out[1000]; 98 | int index = 0; 99 | FindValidParenthesis(out, n, 0, 0, 0); 100 | return 0; 101 | } 102 | ``` 103 | 104 | 105 | 106 | 107 | ```python 108 | # Generate valid parantheses 109 | def generateParantheses(openB,closeB,total,s=[]): 110 | if(closeB==total): 111 | print(''.join(s)) 112 | return 113 | else: 114 | if(openB>closeB): 115 | s.append(')') 116 | generateParantheses(openB,closeB+1,total,s) 117 | s.pop() 118 | if(openB 129 | 130 | 131 | 132 | ## Sample Input and Output 133 | 134 | #### Input : 135 | 136 | ``` 137 | n = 3 138 | ``` 139 | 140 | #### Output : 141 | 142 | ``` 143 | ((())) 144 | (()()) 145 | (())() 146 | ()(()) 147 | ()()() 148 | ``` 149 | 150 | ## Complexity Analysis 151 | 152 | - Time Complexity: `O(N)` 153 | - Space Complexity: `O(N)` 154 | -------------------------------------------------------------------------------- /docs/competitive-programming/max-number-from-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Maximum number formed from numbers in an array 3 | slug: /competitive-programming/max-number-from-array 4 | --- 5 | 6 | ## Introduction 7 | 8 | Given an array of a combination of two-digit and single-digit numbers, we have to form the maximum possible number from the given numbers.To form the maximum number possible from an array of single-digit numbers, we have to sort the array in descending order. The numbers appended in the descending order give the maximum number. However, the same algorithm cannot be used for array containing both two-digit and single-digit numbers. 9 | 10 | ## Explanation 11 | 12 | If the array contains two elements, `2` and `21`, then according to the algorithm used for the single digits, if we sort the array in descending order and append them, then the maximum number will be `212`. But this is wrong. The maximum number that can be formed from this array is `221`. Therefore, we need to use a separate algorithm. 13 | 14 | ## Algorithm 15 | 16 | - Input the numbers as string. 17 | - Sort the array of strings based on the following comparison criteria. 18 | * While sorting the array using comparison, create two separate strings XY and YX, if X and Y are the two strings being compared. 19 | * XY is the string created by appending X and Y in order. 20 | * YX is the string created by appending Y and X in order. 21 | * Compare XY and YX and whichever is greater, should be placed before the other in the array. 22 | 23 | ## Examples 24 | 25 | #### Example 1 26 | 27 | ``` 28 | Let the array be {21,2}. 29 | While sorting, two strings are created : XY = 212 and YZ = 221 30 | As XYYX, the sorted array is {34,17} and the maximum number formed is 3417. 40 | ``` 41 | 42 | ## Code 43 | 44 | import Tabs from "@theme/Tabs"; 45 | import TabItem from "@theme/TabItem"; 46 | 47 | 53 | 54 | 55 | 56 | ```cpp 57 | 58 | #include 59 | using namespace std; 60 | int myCompare(string X, string Y) 61 | { 62 | string XY = X.append(Y); 63 | string YX = Y.append(X); 64 | return XY.compare(YX) > 0 ? 1 : 0; 65 | } 66 | int printLargest(vector str) 67 | { 68 | sort(str.begin(), str.end(), myCompare); 69 | for (int i = 0; i < str.size(); i++) 70 | cout << str[i]; 71 | } 72 | int main() 73 | { 74 | vector str; 75 | cout << "Enter the number of elements in array:\n"; 76 | long long int n; 77 | cin >> n; 78 | string s; 79 | cout<< "\nEnter the elements:\n"; 80 | for (int i = 0; i < n; i++) 81 | { 82 | cin >> s; 83 | str.push_back(s); 84 | } 85 | cout << "The maximum number : "; 86 | printLargest(str); 87 | } 88 | 89 | ``` 90 | 91 | 92 | 93 | ## Sample Input and Output 94 | 95 | #### Input : 96 | 97 | ``` 98 | Enter the number of elements in array: 99 | 3 100 | Enter the elements: 101 | 10 21 34 102 | ``` 103 | 104 | #### Output : 105 | 106 | ``` 107 | The maximum number : 342110 108 | ``` 109 | 110 | #### Input : 111 | 112 | ``` 113 | Enter the number of elements in array: 114 | 4 115 | Enter the elements: 116 | 12 21 33 26 117 | ``` 118 | 119 | #### Output : 120 | 121 | ``` 122 | The maximum number : 33262112 123 | ``` 124 | 125 | ## Complexity Analysis 126 | 127 | * Time Complexity: `O(n)` 128 | * Space Complexity : `O(1)` 129 | 130 | ## Credit 131 | 132 | * [Sayani Mallick](https://github.com/SAY-droid427/) for the [C++ implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/cp/maxNumber.cpp) 133 | -------------------------------------------------------------------------------- /docs/competitive-programming/next-greatest-left.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Next greatest element to the right 3 | slug: /competitive-programming/next-greatest-left 4 | --- 5 | 6 | ## Introduction 7 | 8 | Given an array of numbers, find out the next greatest element to the left. 9 | 10 | ## Algorithm 11 | 12 | - Declare an array and a stack 13 | - If the stack is empty, then no element to the left is greater than the present element 14 | - If the stack is not empty but the element present at the top of the stack is not greater than the current element then- 15 | - Pop the stack till the stack is not empty or the top element of stack is greater than the current element 16 | - If the stack is not empty and the element at the top of the stack is greater than the current element then push the topmost element to the stack 17 | 18 | ## Examples 19 | 20 | #### Example 1 21 | 22 | ``` 23 | Let the array be 3, 2. 24 | Traverse array from the left. 25 | The stack is empty, so no greater element to the left of 3 and -1 is pushed to array. 26 | Push 3 to stack. 27 | For next element 2, compare the topmost element of the stack. 28 | Topmost element is 3 which is greater than 2, so 3 is printed. 29 | The resultant array is -1,3. 30 | ``` 31 | 32 | #### Example 2 33 | 34 | ``` 35 | Let the array be 1,2. 36 | The stack is initially empty, so no greater element to the left of 1 and -1 is pushed to array. 37 | 1 is pushed into stack. 38 | For next element 2, the topmost element of stack, 1 is compared which is less than 2. 39 | 1 is popped from stack. 40 | Stack is now empty, so 2 has no greater element to its left. 41 | The resultant array is -1,-1. 42 | ``` 43 | 44 | ## Code 45 | 46 | import Tabs from "@theme/Tabs"; 47 | import TabItem from "@theme/TabItem"; 48 | 49 | 55 | 56 | 57 | 58 | ```cpp 59 | #include 60 | using namespace std; 61 | 62 | void nextGreatestToLeft(int a[],int n) 63 | { 64 | stack s; 65 | vector v; 66 | for(int i = 0; i < n; i++) 67 | { 68 | if(s.empty() == true) 69 | v.push_back(-1); 70 | else if(s.empty() != true && s.top() > a[i]) 71 | v.push_back(s.top()); 72 | else if(s.empty() != true && s.top() <= a[i]) 73 | { 74 | while(s.empty() != true && s.top() <= a[i]) 75 | { 76 | s.pop(); 77 | } 78 | if(s.empty() == true) 79 | v.push_back(-1); 80 | else if(s.top() > a[i]) 81 | v.push_back(s.top()); 82 | } 83 | s.push(a[i]); 84 | } 85 | for(int i = 0; i < n; i++) 86 | cout << v[i] << " "; 87 | } 88 | 89 | //Driver Function 90 | int main() 91 | { 92 | int n; 93 | cout << "Enter the number of elements: "; 94 | cin >> n; 95 | int a[n]; 96 | cout << "Enter the elements: "; 97 | for(int i = 0; i < n; i++) 98 | cin >> a[i]; 99 | cout << "The next greatest element to the left of each element: \n"; 100 | nextGreatestToLeft(a,n); 101 | } 102 | ``` 103 | 104 | 105 | 106 | ## Sample I/O 107 | 108 | #### Input 109 | 110 | ``` 111 | Enter the number of elements: 4 112 | Enter the elements: 5 2 4 6 113 | ``` 114 | #### Output 115 | 116 | ``` 117 | The next greatest element to the left of each element: 118 | -1 5 5 -1 119 | ``` 120 | 121 | ## Complexity Analysis 122 | 123 | - Time Complexity: O(n^2) 124 | - Space complexity: O(n) 125 | 126 | ## Credit 127 | 128 | - [Sayani Mallick](https://github.com/SAY-droid427) for the [C++ implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/stack/nextGreatestToLeft.cpp) 129 | -------------------------------------------------------------------------------- /docs/competitive-programming/next-smallest-left.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Next smallest element to the left 3 | slug: /competitive-programming/next-smallest-left 4 | --- 5 | 6 | ## Introduction 7 | 8 | Given an array, find the next smallest element to the left of each element in the array. An easy but less efficient method is to use two loops and find out the next smallest element to the right. But using stacks is an efficient way of solving the problem 9 | 10 | ## Algorithm 11 | 12 | - Initialise a stack and array. 13 | - Traverse the given array from the left. 14 | - If the stack is empty, then push -1 to array. 15 | - If the stack is not empty and topmost element is smaller than th element then push topmost element to array. 16 | - If not then pop elements from the stack till it is empty or topmost element is smaller. 17 | 18 | ## Examples 19 | 20 | #### Example 1 21 | 22 | ``` 23 | Let the array be 1, 3. 24 | Traverse the array from the left. 25 | The stack is empty, hence no smaller element to the right of 1. 26 | For 3, the topmost element 1 is compared to 3. 27 | 1 is less than 3, so the next smallest element to the left of 3 is 1. 28 | The resultant array is -1, 1. 29 | ``` 30 | 31 | #### Example 2 32 | 33 | ``` 34 | Let the array be 9, 4. 35 | The stack is initially empty, hence no smaller element to the right of 9. 36 | For 4, the topmost element 9 is compared to 4. 37 | It is greater than 4, so elements in stack are popped out till stack is empty or topmost element is smaller. 38 | Stack is empty on popping 9, so -1 is pushed to the array. 39 | The resultant array is -1, -1. 40 | ``` 41 | 42 | ## Code 43 | 44 | import Tabs from "@theme/Tabs"; 45 | import TabItem from "@theme/TabItem"; 46 | 47 | 54 | 55 | 56 | 57 | ```cpp 58 | #include 59 | using namespace std; 60 | 61 | void nextSmallestToLeft (int a[],int n) 62 | { 63 | stack s; 64 | vector v; 65 | 66 | for(int i = 0 ; i < n ; i++) 67 | { 68 | if (s.empty()) 69 | v.push_back(-1); 70 | else if (s.empty() != true && s.top() < a[i]) 71 | v.push_back(s.top()); 72 | else if (s.empty() != true && s.top() > a[i]) 73 | { 74 | while (s.empty() != true && s.top() > a[i]) 75 | { 76 | s.pop(); 77 | } 78 | if (s.empty()) 79 | v.push_back (-1); 80 | else if (s.top() < a[i]) 81 | v.push_back(s.top()); 82 | } 83 | s.push(a[i]); 84 | } 85 | 86 | for(int i = 0 ; i < n ; i++) 87 | cout << v[i] << " "; 88 | } 89 | 90 | //Driver function 91 | int main() 92 | { 93 | int n; 94 | cout << "Enter number of elements: "; 95 | cin >> n; 96 | int a[n]; 97 | cout << "Enter the elements:\n"; 98 | for(int i = 0 ; i < n ; i++) 99 | cin >> a[i]; 100 | nextSmallestToLeft(a,n); 101 | } 102 | ``` 103 | 104 | 105 | 106 | ## Sample I/O 107 | 108 | #### Input 109 | 110 | ``` 111 | Enter number of elements: 4 112 | Enter the elements: 113 | 1 2 4 5 114 | ``` 115 | 116 | #### Output 117 | 118 | ``` 119 | -1 1 2 4 120 | ``` 121 | 122 | ## Complexity Analysis 123 | 124 | - Time Complexity: `O(n^2)` 125 | - Space Complexity:`O(n)` 126 | 127 | ## Credits 128 | 129 | - [Sayani Mallick]() for the C++ implementation 130 | 131 | -------------------------------------------------------------------------------- /docs/competitive-programming/next-smallest-right.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Next Smallest Element to the Right 3 | slug: /competitive-programming/next-smallest-to-right 4 | --- 5 | 6 | ## Introduction 7 | 8 | Given an array, find out the next smallest element to its right. If the element does not have an element smaller than itself in the array, then `-1` is printed. 9 | 10 | ## Explanation 11 | 12 | Stack as a data structure has many applications, especially because of its 'Last In, First Out' principle. One of them is to find the smallest element to the right of each element in the array.Another simple method to do the problem would be using two loops. In the first loop we fix an element and then using the second loop, we try to find the next smaller element. However this approach is not the most efficient algorithm. Therefore, we use stacks to solve the problem more efficiently. 13 | 14 | ## Algorithm 15 | 16 | - Initialize a stack. 17 | - Start the scanning of the array from the right. 18 | - Declare an array and a stack. 19 | - If the stack is empty, then no element to the right is smaller than the present element. 20 | - If the stack is not empty but the element present at the top of the stack is not smaller than the current element then: 21 | - Pop the stack till the stack is not empty or the top element of stack is smaller than the current element. 22 | - If the stack is not empty and the element at the top of the stack is smaller than the current element then: 23 | - Push the topmost element to the stack. 24 | 25 | ## Examples 26 | 27 | #### Example 1 28 | 29 | ``` 30 | Let the array consist of 2,3. 31 | As the stack is initially empty, so the rightmost element has no smaller element. 32 | The last element 3 is pushed into the stack. 33 | Next 2 is compared to the top of the stack, 3 which is greater than `2`. 34 | The top of the stack is popped. 35 | The stack being empty, 2 has no greater element to its right. 36 | The output is -1 -1. 37 | ``` 38 | 39 | #### Example 2 40 | 41 | ``` 42 | Let the array consist of 3,4. 43 | Initially stack is empty, so 4 has no other smaller element to its right. 44 | 4 pushed into stack. 45 | Next, 3 is compared to the top of the stack,4 which is greater than 3. 46 | The output is -1 -1. 47 | ``` 48 | 49 | ## Code 50 | 51 | import Tabs from '@theme/Tabs'; 52 | import TabItem from '@theme/TabItem'; 53 | 54 | 61 | 62 | 63 | ```cpp 64 | #include 65 | using namespace std; 66 | void nextSmallestElement(int a[], int n) 67 | { 68 | stack s; 69 | vector v; 70 | for(int i=n-1;i>=0;i--) 71 | { 72 | if(s.empty()) 73 | v.push_back(-1); 74 | else if(s.empty()!=true && s.top()a[i]) 77 | { 78 | while(s.empty()!=true && s.top()>a[i]) 79 | s.pop(); 80 | 81 | if(s.empty()) 82 | v.push_back(-1); 83 | else if(s.top()>a[i]) 84 | v.push_back(s.top()); 85 | } 86 | s.push(a[i]); 87 | } 88 | reverse(v.begin(),v.end()); 89 | 90 | for(int i=0;i> n; 98 | int a[n]; 99 | cout<<"Enter the elements:"; 100 | for (int i = 0; i < n; i++) 101 | cin >> a[i]; 102 | cout<<"The next smallest element for each:"; 103 | nextSmallestElement(a, n); 104 | } 105 | ``` 106 | 107 | 108 | 109 | 110 | ## Sample I/O 111 | 112 | #### Input 113 | 114 | ``` 115 | Enter the number of elements: 4 116 | Enter the elements: 117 | 4 3 6 1 118 | ``` 119 | 120 | #### Output 121 | 122 | ``` 123 | The next smallest element for each: 124 | 3 1 1 -1 125 | ``` 126 | 127 | ## Complexity Analysis 128 | 129 | - Time Complexity : `O(n)` 130 | - Space Complexity: `O(n)` 131 | 132 | ## Credits 133 | 134 | * [Sayani Mallick](https://github.com/SAY-droid427) for the [C++ implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/stack/nextSmallestToRight.cpp) 135 | -------------------------------------------------------------------------------- /docs/competitive-programming/phone-keypad.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Phone Keypad Problem 3 | slug: /competitive-programming/phone-keypad 4 | --- 5 | 6 | ## Introduction 7 | 8 | Given an integer array containing digits from [0, 9], the task is to print all possible letter combinations that the numbers could represent. 9 | 10 | ## Explanation 11 | 12 | First we can input the number from the user, and take an empty output array. 13 | We will include the first digit of the number and make three sub-calls, likewise we will make sub-calls for each digit and generate the strings possible. 14 | 15 | ## Algorithm 16 | 17 | - Initialize an empty array(out) 18 | - If the input string reaches its end 19 | - Add a NULL character at the end 20 | - Print the string 21 | 22 | - digit=input[i]-'0' 23 | - make a for loop from 0 to keypad[digit][k] is not NULL 24 | - include the current character in the out array 25 | - Make a recursive call for furthur combinations 26 | 27 | 28 | Let's have few examples: 29 | ``` 30 | Input 1: 31 | 23 32 | Output 1: 33 | dg 34 | dh 35 | di 36 | eg 37 | eh 38 | ei 39 | fg 40 | fh 41 | fi 42 | Input 2: 43 | 67 44 | Output 2: 45 | pt 46 | pu 47 | pv 48 | qt 49 | qu 50 | qv 51 | rt 52 | ru 53 | rv 54 | st 55 | su 56 | sv 57 | ``` 58 | ## Code 59 | 60 | import Tabs from '@theme/Tabs'; 61 | import TabItem from '@theme/TabItem'; 62 | 63 | 70 | 71 | 72 | ```cpp 73 | #include 74 | using namespace std; 75 | 76 | char keypad[][10]={" ","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 77 | 78 | void generate_names(char *in,char *out,int i,int j) 79 | { 80 | //Base case 81 | if(in[i]=='\0') 82 | { 83 | out[j]='\0'; 84 | cout<>in; 100 | char out[100]; 101 | generate_names(in,out,0,0); 102 | return 0; 103 | } 104 | ``` 105 | 106 | 107 | 108 | 109 | ```python 110 | # Generate phone keypad strings 111 | def getString(d): 112 | if d==2: 113 | return "abc" 114 | if d==3: 115 | return "def" 116 | if d==4: 117 | return "ghi" 118 | if d==5: 119 | return "jkl" 120 | if d==6: 121 | return "mno" 122 | if d==7: 123 | return "pqrs" 124 | if d==8: 125 | return "tuv" 126 | if d==9: 127 | return "wxyz" 128 | return " " 129 | 130 | def printKeypad(n,outputSoFar): 131 | if n==0: 132 | print(outputSoFar) 133 | return 134 | smallNumber=n//10 135 | lastDigit=n%10 136 | optionsForLastDigit=getString(lastDigit) 137 | for c in optionsForLastDigit: 138 | newOutput=outputSoFar+c 139 | printKeypad(smallNumber,newOutput) 140 | 141 | d=eval(input("enter value: ")) 142 | printKeypad(d,"") 143 | ``` 144 | 145 | 146 | 147 | 148 | ## Sample Input and Output 149 | 150 | #### Input : 151 | 152 | ``` 153 | 23 154 | ``` 155 | 156 | #### Output : 157 | 158 | ``` 159 | dg 160 | dh 161 | di 162 | eg 163 | eh 164 | ei 165 | fg 166 | fh 167 | fi 168 | ``` 169 | 170 | ## Complexity Analysis 171 | 172 | - Time Complexity: `O(N)` 173 | - Space Complexity: `O(N)` 174 | -------------------------------------------------------------------------------- /docs/competitive-programming/postfix-to-prefix.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Postfix to Prefix Conversion 3 | slug: /data-structures/postfix-to-prefix 4 | --- 5 | 6 | ## Introduction 7 | 8 | A postfix expression is of the form operand1 operand2 operator, whereas a prefix expression is of the form operand operator1 operator2.Converting a postfix expression to prefix expression is one of the many applications of stacks due to its 'Last in First Out' policy. 9 | 10 | ## Algorithm 11 | 12 | - Scan the postfix expression from left to right. 13 | - If the symbol is an operand, push it to the stack. 14 | - If the symbol is an operator, pop two operands from the stack. 15 | - Create a string by concatenating the two operands and the operator before them. 16 | - Push the resultant string back to stack. 17 | 18 | ## Explanation 19 | 20 | Let the string be A+B. We aim to convert this string into a prefix string by scanning the string sequentially. Let us visualize how the stack works in this case. 21 | 22 |

23 | 24 | ## Examples 25 | 26 | #### Example 1 27 | 28 | ``` 29 | Let the string be AB+. 30 | A is pushes to the stack. 31 | B is pushed to the stack. 32 | + is an operator. 33 | A and B are popped back and expression +AB is printed. 34 | ``` 35 | 36 | #### Example 2 37 | 38 | ``` 39 | Let the string be AB+C+. 40 | A and B are pushed to stack. 41 | + is an operator, so A and B are popped out and the string +AB is pushed to stack. 42 | C is pushed to stack. 43 | + is operator, so the two elements of the stack are popped out and the string ++ABC is pushed to stack. 44 | ``` 45 | 46 | ## Code 47 | 48 | 49 | import Tabs from "@theme/Tabs"; 50 | import TabItem from "@theme/TabItem"; 51 | 52 | 58 | 59 | 60 | 61 | ```cpp 62 | #include 63 | using namespace std; 64 | 65 | void postfixToPrefix(string s) 66 | { 67 | stack str; 68 | for(int i=0;i>s; 98 | cout<<"Prefix expression:\n"; 99 | postfixToPrefix(s); 100 | } 101 | ``` 102 | 103 | 104 | 105 | ## Sample I/O 106 | 107 | #### Input 108 | 109 | ``` 110 | Enter the postfix expression: 111 | ABC/-A 112 | ``` 113 | 114 | #### Output 115 | 116 | ``` 117 | Prefix Expression: 118 | A-A/BC 119 | ``` 120 | 121 | ## Complexity Analysis 122 | 123 | - Space Complexity : `O(n)` 124 | - Time Comlexity : `O(n)` 125 | 126 | ## Credits 127 | 128 | - [Sayani Mallick](https://github.com/SAY-droid427) for the [C++ implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/stack/postfix_to_prefix.cpp) 129 | -------------------------------------------------------------------------------- /docs/competitive-programming/reverse-of-string.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Reverse of String 3 | slug: /competitive-programming/Reverse-of-String 4 | --- 5 | 6 | ## Introduction 7 | 8 | Given a string, we need to find its reverse. 9 | 10 | ## Explanation 11 | 12 | Reversing a string implies that the string given by the user in a specific sequence will get entirely reversed, 13 | when the reverse of a string algorithm is implemented. 14 | 15 | Let us have a few examples: 16 | 17 | ``` 18 | Reverse of "hello" will be "olleh" 19 | Reverse of "NeoAlgo" will be "oglAoeN" 20 | ``` 21 | 22 | ## Algorithm 23 | 24 | #### Using Stack 25 | 26 | ``` 27 | reverse(s): 28 | - creating an empty stack. 29 | - pushing each character of string in stack. 30 | - using for loop, storing the top character in result string 31 | and popping out every single character. 32 | ``` 33 | 34 | #### Iterative 35 | 36 | ``` 37 | reverse(s): 38 | - creating a variable to store result. 39 | - using for loop, extracting each element from the end of the string 40 | and storing in the variable. 41 | - printing the reversed string. 42 | ``` 43 | 44 | ## Code 45 | 46 | import Tabs from '@theme/Tabs'; 47 | import TabItem from '@theme/TabItem'; 48 | 49 | 56 | 57 | 58 | ```cpp 59 | #include 60 | using namespace std; 61 | 62 | //function to reverse the string 63 | void reverse(string &s) 64 | { 65 | int i; 66 | stack str; 67 | 68 | for(char ch:s){ 69 | str.push(ch); 70 | } 71 | for(i=0;i 91 | 92 | 93 | ```java 94 | import java.io.*; 95 | import java.util.*; 96 | 97 | // Main class 98 | 99 | class Program { 100 | public static void main(String[] args) 101 | { 102 | Scanner sc = new Scanner(System.in); 103 | 104 | // Accepting input from user 105 | 106 | System.out.println("Enter the string: "); 107 | String str = sc.nextLine(); 108 | 109 | // revoking the function reverse 110 | 111 | reverse(str); 112 | 113 | } 114 | 115 | // Method for reversing the string 116 | 117 | static void reverse(String s){ 118 | 119 | // Reversing the string by extracting each element from the end of the string 120 | // and storing in a variable result 121 | 122 | String result = ""; 123 | for (int i = s.length() - 1; i >= 0; i--) 124 | result += s.charAt(i); 125 | 126 | // Printing the reversed string 127 | System.out.println("String after Reverse: "); 128 | System.out.println(result); 129 | 130 | } 131 | 132 | } 133 | ``` 134 | 135 | 136 | 137 | 138 | ## Sample Input and Output 139 | 140 | #### Input: 141 | 142 | ``` 143 | Enter the string: Hello World 144 | ``` 145 | 146 | #### Output: 147 | 148 | ``` 149 | String after Reverse: dlroW olleH 150 | ``` 151 | 152 | ## Complexity Analysis 153 | 154 | - Time complexity - `O(n)` 155 | - Space complexity - `O(n)` 156 | 157 | ## Credits 158 | 159 | - [Harshit Pandey](https://github.com/HarshitPandey251) contributed the [C++ implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/cp/Reverse_string_using_stack.cpp) 160 | - [Amit Kumar Mishra](https://github.com/Amit366) contributed the [Java implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/Java/cp/ReverseString.java) 161 | -------------------------------------------------------------------------------- /docs/competitive-programming/wave-sort.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Wave Sort 3 | slug: /competitive-programming/wave-sort 4 | --- 5 | 6 | ## Introduction 7 | 8 | Given an unsorted array. Sort the array in such a way that the array looks like a wave array. 9 | For example, if the given sequence arr has n elements then the sorted wave array looks like - 10 | arr[0] >= arr[1] and arr[1] <= arr[2] 11 | arr[2] >= arr[3] and arr[3] <= arr[4] 12 | arr[4] >= arr[5] and arr[5] <= arr[6] And so on 13 | For example, the given array : arr = { 4, 3, 5, 2, 3, 1, 2 } 14 | The above figure is a visual representation of the given arr and you can see we can express ‘arr’ in a waveform array because 15 | 4>3 and 3<5 16 | 5>2 and 2<3 17 | 3>1 and 1<2 18 | And it follows the condition of wave array. 19 | 20 | ## Explanation 21 | 22 | First we take the input from the user. Then while traversing the array of elements, check for two conditions: 23 | - If the current element is lesser in value than the previous and is not the first, then the values will be swapped 24 | - If the current element is lesser in value than the next and is not the last, then the values will be swapped 25 | 26 | Let's have few examples: 27 | ``` 28 | Input 1: 29 | 7 30 | 20 80 40 35 10 15 70 31 | Output 1: 32 | 80 20 40 10 35 15 70 33 | Input 2: 34 | 5 35 | 12 20 45 60 5 36 | Output 2: 37 | 20 12 60 5 45 38 | ``` 39 | 40 | ## Algorithm 41 | 42 | - Take the input array from the user 43 | - For each element check for two conditions 44 | - If the current element is lesser in value than the previous and is not the first,then swap the values 45 | - If the current element is lesser in value than the next and is not the last, then swap the values 46 | - Finally, print the array 47 | 48 | ## Code 49 | 50 | import Tabs from '@theme/Tabs'; 51 | import TabItem from '@theme/TabItem'; 52 | 53 | 60 | 61 | 62 | ```cpp 63 | #include 64 | using namespace std; 65 | vector wave_sort(vector &v, int n) 66 | { 67 | for (int i = 0; i < n; i += 2) 68 | { 69 | if (v[i] < v[i - 1] and i != 0) 70 | { 71 | swap(v[i], v[i - 1]); 72 | } 73 | 74 | if (v[i] < v[i + 1] and i != n - 1) 75 | { 76 | swap(v[i], v[i + 1]); 77 | } 78 | } 79 | 80 | return v; 81 | } 82 | 83 | int main() 84 | { 85 | int n; 86 | vector v; 87 | cin >> n; 88 | 89 | for (int i = 0; i < n; i++) 90 | { 91 | int temp; 92 | cin >> temp; 93 | v.push_back(temp); 94 | } 95 | wave_sort(v, n); 96 | for (int i = 0; i < n; i++) 97 | { 98 | cout << v[i] << " "; 99 | } 100 | 101 | return 0; 102 | } 103 | ``` 104 | 105 | 106 | 107 | 108 | ```python 109 | # Wave Sort 110 | def wave( listA ): 111 | size=len(listA) 112 | 113 | for index in range(0,size,2): 114 | if((index > 0) and (listA[index-1] > listA[index])): 115 | listA[index-1] , listA[index] = listA[index] , listA[index-1] 116 | 117 | if((index < size-1) and (listA[index] < listA[index+1])): 118 | listA[index] , listA[index+1] = listA[index+1] , listA[index] 119 | 120 | return listA 121 | listA = [] 122 | 123 | n = int(input("Enter number of elements in the list : ")) 124 | 125 | for i in range(0, n): 126 | print("Enter element No-{}: ".format(i+1)) 127 | elm = int(input()) 128 | listA.append(elm) 129 | print(wave(listA)) 130 | ``` 131 | 132 | 133 | 134 | 135 | ## Sample Input and Output 136 | 137 | #### Input : 138 | 139 | ``` 140 | 7 141 | 20 80 40 35 10 15 70 142 | ``` 143 | 144 | #### Output : 145 | 146 | ``` 147 | 80 20 40 10 35 15 70 148 | ``` 149 | 150 | ## Complexity Analysis 151 | 152 | - Time Complexity: `O(N)` 153 | - Space Complexity: `O(N)` -------------------------------------------------------------------------------- /docs/competitive-programming/wine-selling.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Wave Selling Problem 3 | slug: /competitive-programming/wine-selling 4 | --- 5 | 6 | ## Introduction 7 | 8 | Given n wines in a row, with integers denoting the cost of each wine respectively. 9 | Each year you can sell the first or the last wine in the row. 10 | Let the initial profits from the wines be P1, P2, P3…Pn. 11 | In the Yth year, the profit from the ith wine will be Y*P[i]. 12 | The goal is to calculate the maximum profit that can be earned by selling all the wines. 13 | 14 | ## Explanation 15 | 16 | We can find the optimal solution by two ways: 17 | -We can pick either the first wine and multiply with the current year and recursively move to next year 18 | -We will select the last wine and multiply with the current year and move recursively to the next part 19 | At the end we will select the maximum of the two sub-cases for the optimal solution. 20 | 21 | Let's have few examples: 22 | ``` 23 | Input 1: 24 | 5 25 | 2 4 6 2 5 26 | Output 1: 27 | 64 28 | Input 2: 29 | 4 30 | 1 2 3 4 31 | Output 2: 32 | 30 33 | ``` 34 | 35 | ## Algorithm 36 | 37 | - If the length of the array is less than or equal to 1, then return 38 | - Take the first wine and multiply with the corresponding year 39 | - Recursively call further 40 | 41 | - Take the last wine and multiply with the corresponding year 42 | - Recursively call further 43 | - At the end add the maximum of the two options 44 | ## Code 45 | 46 | import Tabs from '@theme/Tabs'; 47 | import TabItem from '@theme/TabItem'; 48 | 49 | 56 | 57 | 58 | ```cpp 59 | #include 60 | using namespace std; 61 | 62 | int profit(int wines[],int i,int j,int year, int dp[][10]) 63 | { 64 | if(i>j) 65 | { 66 | return 0; 67 | } 68 | if(dp[i][j]!=0) 69 | { 70 | return dp[i][j]; 71 | } 72 | int op1=wines[i]*year+profit(wines,i+1,j,year+1,dp); 73 | int op2=wines[j]*year+profit(wines,i,j-1,year+1,dp); 74 | return max(op1,op2); 75 | } 76 | 77 | int main() 78 | { 79 | int n; 80 | cout<<"Enter total number of wines: "<>n; 82 | int wines[100],dp[10][10]={0}; 83 | cout<<"Enter wine prices: "<>wines[i]; 87 | } 88 | cout<<"The maximum profit is: "< 93 | 94 | 95 | 96 | ```python 97 | # Wine Selling Problem 98 | def max_profit(w,y,L,R): 99 | if L==R: 100 | return y*w[L] 101 | option1=y*w[L]+max_profit(w,y+1,L+1,R) 102 | option2=y*w[R]+max_profit(w,y+1,L,R-1) 103 | return max(option1,option2) 104 | 105 | print("Enter the weights: ") 106 | w=list(map(int,input().split(" "))) 107 | n=len(w) 108 | print(max_profit(w,1,0,n-1)) 109 | ``` 110 | 111 | 112 | 113 | 114 | ## Sample Input and Output 115 | 116 | #### Input : 117 | 118 | ``` 119 | 5 120 | 2 4 6 2 5 121 | ``` 122 | 123 | #### Output : 124 | 125 | ``` 126 | 64 127 | ``` 128 | 129 | ## Complexity Analysis 130 | 131 | - Time Complexity: `O(N)` 132 | - Space Complexity: `O(N)` -------------------------------------------------------------------------------- /docs/computational-geometry/computational-geometry.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Computational Geometry 3 | slug: /computational-geometry 4 | --- 5 | 6 | This page would serve our needs for documentation of Computational Geometry. -------------------------------------------------------------------------------- /docs/computational-geometry/jarvis-algorithm.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Jarvis Algorithm 3 | slug: /computational-geometry/jarvis-algorithm 4 | --- 5 | 6 | This page would serve our needs for documentation of the Jarvis Algorithm. -------------------------------------------------------------------------------- /docs/create-a-blog-post.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Create a Blog Post 3 | --- 4 | 5 | This page will help you on how to create blog posts in Docusaurus. 6 | 7 | ## Create a Blog Post 8 | 9 | Create a file at `blog/2021-02-28-greetings.md`: 10 | 11 | ```md title="blog/2021-02-28-greetings.md" 12 | --- 13 | title: Greetings! 14 | author: Steven Hansel 15 | author_title: Docusaurus Contributor 16 | author_url: https://github.com/ShinteiMai 17 | author_image_url: https://github.com/ShinteiMai.png 18 | --- 19 | 20 | Congratulations, you have made your first post! 21 | 22 | Feel free to play around and edit this post as much you like. 23 | ``` 24 | 25 | A new blog post is now available at `http://localhost:3000/blog/greetings`. -------------------------------------------------------------------------------- /docs/create-a-document.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Create a Document 3 | --- 4 | 5 | Documents are pages with a **sidebar**, a **previous/next navigation** and many other useful features. 6 | 7 | ## Create a Document 8 | 9 | Create a markdown file at `docs/my-doc.md`: 10 | 11 | ```mdx title="docs/hello.md" 12 | --- 13 | title: Hello, World! 14 | --- 15 | 16 | ## Hello, World! 17 | 18 | This is your first document in **Docusaurus**, Congratulations! 19 | ``` 20 | 21 | A new document is now available at `http://localhost:3000/docs/hello`. 22 | 23 | ## Add your document to the sidebar 24 | 25 | Add `hello` to the `sidebars.js` file: 26 | 27 | ```diff title="sidebars.js" 28 | module.exports = { 29 | docs: [ 30 | { 31 | type: 'category', 32 | label: 'Docusaurus Tutorial', 33 | - items: ['getting-started', 'create-a-doc', ...], 34 | + items: ['getting-started', 'create-a-doc', 'hello', ...], 35 | }, 36 | ], 37 | }; 38 | ``` 39 | -------------------------------------------------------------------------------- /docs/create-a-page.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Create a Page 3 | --- 4 | 5 | Any React or Markdown file created under `src/pages` directory is converted into a website page: 6 | 7 | - `src/pages/index.js` -> `localhost:3000/` 8 | - `src/pages/foo.md` -> `localhost:3000/foo` 9 | - `src/pages/foo/bar.js` -> `localhost:3000/foo/bar` 10 | 11 | ## Create a React Page 12 | 13 | Create a file at `src/pages/my-react-page.js`: 14 | 15 | ```jsx title="src/pages/my-react-page.js" 16 | import React from 'react'; 17 | import Layout from '@theme/Layout'; 18 | 19 | function HelloWorld() { 20 | return ( 21 | 22 |

My React page

23 |

This is a React page

24 |
25 | ); 26 | } 27 | ``` 28 | 29 | A new page is now available at `http://localhost:3000/my-react-page`. 30 | 31 | ## Create a Markdown Page 32 | 33 | Create a file at `src/pages/my-markdown-page.md`: 34 | 35 | ```mdx title="src/pages/my-markdown-page.md" 36 | --- 37 | title: My Markdown page 38 | --- 39 | 40 | # My Markdown page 41 | 42 | This is a Markdown page 43 | ``` 44 | 45 | A new page is now available at `http://localhost:3000/my-markdown-page`. 46 | -------------------------------------------------------------------------------- /docs/data-structures/data-structures.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: What are Data Structures? 3 | slug: /data-structures 4 | --- 5 | 6 | ## Introduction 7 | 8 | A program is a set of instructions that performs operations on data. The way of organizing this data in the main memory at the time of execution of the program is called as ***data structures*** . 9 | 10 | Depending upon the requirement of a program and the type of procedures it is performing, we have various data structures. Some of the common examples of data structures include arrays, linked lists, stacks, queues, trees and graphs. Data structures are widely applied in the following areas: 11 | * Compiler design 12 | * Operating system 13 | * DBMS 14 | * Simulation 15 | * Artificial intelligence 16 | * Graphics 17 | 18 | ## Classification of Data Structures 19 | 20 | Data structures are classified into two classes: 21 | 22 | ### ***Primitive and Non-primitive Data Structures*** 23 | 24 | Primitive data structures are the basic data types of any programming 25 | language that form the basic unit for the data structures. Some basic data types are integer, float, character and boolean. 26 | Non-primitive data structures are complex structures that are created using primitive data structures. Examples of such data structures include Arrays, Linked Lists, Stacks, Queues, Trees, and Graphs. 27 | 28 | ![Flowchart](https://i.imgur.com/0hLAz15.png) 29 |

Fig. 1: Classification of Data Structures

30 | 31 | Based on the above structure and arrangement of data, non-primitive data structures are further classified into linear and non-linear. 32 | 33 | ### ***Linear and Non-linear Structures*** 34 | Linear data structures are those where data can be processed in a linear fashion i.e one by one sequentially. It includes the following types of data structures: Arrays, Linked Lists, Stacks & Queues. 35 | Non-linear structures are those in which insertion and deletion are not possible in a linear fashion. It includes the following types of data structures: Trees & Graphs. 36 | 37 | ## Major Operations on Data Structures 38 | 39 | This section discusses the different operations that can be performed on various data structures. 40 | 41 | * ***Traversing : *** 42 | Accessing each record or element from a given file exactly once in order to process it is called traversing. For example, to print the marks of all the students in a class. 43 | 44 | * ***Searching : *** 45 | Finding the location of a given key value in a collection of various data items. 46 | It can be possible that the given key-value may or may not be present in that collection. For example, to find the names of all the people who live in a particular house. 47 | 48 | * ***Inserting : *** 49 | Adding a new element into existing files. For example, to add a particular data of a given student who has just enrolled in a school/college. 50 | 51 | * ***Deleting : *** 52 | Removing the elements from a collection of various data items. For example, to delete the data of a student who has dropped out of a school/college. 53 | 54 | * ***Sorting : *** 55 | Arranging the elements in the file or structure either in some logical order (alphabetically increasing order, decreasing order) or mathematical order. For example, arranging a deck of cards in ascending or descending order. 56 | 57 | * ***Merging : *** 58 | Combining the elements of two similar data structures to a new data structure of the same type. For example, when two lists `List A` and `List B` of size `P` and `Q` respectively, of similar type of elements, are joined to produce the third list, `List C` of size `(P+Q)`, then this process is called merging. 59 | 60 | ## Advantages of Data Structures 61 | 62 | Given below are some important ***advantages of data structures***: 63 | 64 | * Proper choice of data structures makes the program efficient in terms of space and time complexity. 65 | * It provides effective and efficient processing of small as well as a large amount of data. 66 | * They are re-usable. 67 | * They make the code cleaner and easier to understand. 68 | * Data structures are specified by an ADT (Abstract Data Type) which provides a level of abstraction. 69 | -------------------------------------------------------------------------------- /docs/data-structures/size-of-binary-tree.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Size of Binary Tree 3 | slug: /data-structures/size-of-binary-tree 4 | --- 5 | 6 | ## Introduction 7 | 8 | In this article, we will see how to find the size of a binary tree. In other words how many nodes are there in a tree. 9 | 10 | ## Explanation 11 | In this we are given an binary tree. We have to find the size of that binary tree means total number of nodes in binary tree. 12 | #### Example 1 13 | 14 | 15 | ``` 16 | In the above diagram the binary tree has 5 nodes 17 | So the size of above binary tree is 5 18 | 19 | ``` 20 | ## Algorithm 21 | 22 | For finding size of binary tree, we follow the following algorithm: 23 | 24 | * First, we will check that tree is empty or not. 25 | 26 | * If tree is empty then simply return 0 because it has zero size. 27 | 28 | * Otherwise find the size of left subtree and right subtree recursively. 29 | 30 | * Print the size of left subtree + right subtree + 1(for root). 31 | 32 | ## Code 33 | 34 | import Tabs from '@theme/Tabs'; 35 | import TabItem from '@theme/TabItem'; 36 | 37 | 44 | 45 | 46 | ```cpp 47 | #include 48 | using namespace std; 49 | 50 | // Making structure of node 51 | struct Node 52 | { 53 | int key; 54 | 55 | // Initialize left child as null 56 | struct Node* left=NULL; 57 | 58 | // Initialize right child as null 59 | struct Node* right=NULL; 60 | }; 61 | 62 | // createnode function for creating new node 63 | struct Node* createnode(int k) 64 | { 65 | struct Node* newnode; 66 | newnode=new Node; 67 | newnode->key=k; 68 | return newnode; 69 | } 70 | 71 | // getsize function for calculating size of binary tree 72 | int getsize(Node* root) 73 | { 74 | if(root==NULL) 75 | return 0; 76 | else 77 | return 1+getsize(root->left)+getsize(root->right); 78 | } 79 | 80 | // Main function 81 | int main() 82 | { 83 | struct Node *root=NULL; 84 | 85 | // creating binary tree 86 | root=createnode(44); 87 | root->left=createnode(22); 88 | root->right=createnode(66); 89 | root->left->left=createnode(11); 90 | root->left->right=createnode(33); 91 | cout<<"Size of binary tree: "<< getsize(root); 92 | } 93 | 94 | ``` 95 | 96 | 97 | 98 | 99 | ```python 100 | 101 | # A binary tree node 102 | class createnode: 103 | 104 | # for creating new node 105 | def __init__(self, data): 106 | self.data = data 107 | self.left = None 108 | self.right = None 109 | 110 | # finding size of binary tree 111 | def size(node): 112 | 113 | # if tree is empty return zero 114 | if node is None: 115 | return 0 116 | 117 | # else find the size of left subtree and right subtree 118 | else: 119 | return (1 + size(node.left) + size(node.right)) 120 | 121 | # creating binary tree 122 | root = createnode(44) 123 | root.left = createnode(22) 124 | root.right = createnode(66) 125 | root.left.left = createnode(11) 126 | root.left.right = createnode(33) 127 | print("Size of binary tree: ") 128 | 129 | # printing size of binary tree 130 | print(size(root)) 131 | 132 | ``` 133 | 134 | 135 | 136 | ## Sample Input and Output 137 | 138 | #### Input : 139 | 140 | 141 | 142 | 143 | #### Output : 144 | 145 | ``` 146 | 5 147 | ``` 148 | 149 | ## Complexity Analysis 150 | 151 | - **Time Complexity:** `O(n)` 152 | 153 | - **Space Complexity:** `O(h)` 154 | 155 | where `n` is the number of elements and `h` is the height of binary tree. 156 | -------------------------------------------------------------------------------- /docs/doc-guideline.md: -------------------------------------------------------------------------------- 1 | # DOC GUIDELINE 2 | 3 | ## How to write an article for the website 4 | 5 | 1. All the problems written should necessarily include 3 sections 6 | 1. Explanation of the article 7 | 2. Sample input 8 | 3. Sample output 9 | 10 | 2. All problems should be supplemented by examples of code. 11 | 12 | 3. Every problem should have two or more examples with at least one of them well-explained. 13 | 14 | 4. Time complexity and space complexity should be included, if applicable. 15 | 16 | 5. Formulae or any important point should be highlighted. 17 | 18 | ## GUIDELINES FOR THE CODE 19 | The guidelines for the code: 20 | 1. The width of text in each line should not exceed 60 characters 21 | 22 | 2. All documentations should be written using multi-line comments 23 | 24 | 3. Comments should be written above the code and not beside it. 25 | 26 | 4. Function and variable names should follow camelcasing. Example: uglyNumbers() 27 | 28 | 5. Indentation should be done using 4 spaces. 29 | 30 | 6. In case of the code being written in multiple languages, the output of all the codes should be the same 31 | 32 | 7. There should not be any spaces for function call or function declaration 33 | 34 | 8. Avoid the use of typedef 35 | 36 | 9. Avoid the use of static and global variables 37 | 38 | 10. When using cout, use a space between cout and "<<". 39 | 40 | 11. There should be space after comma in parameter passing and declaration list 41 | 42 | 12. In the beginning of each code, use multiline comments to explain the purpose of the program. Make the points bulleted and short. 43 | 44 | # Reviewing Process 45 | 46 | 1. Submit the article for review after writing it. 47 | 48 | 2. The team will review your article and give you feedback for the article 49 | 50 | 3. Work upon the feedback and improve your article. Submit it again for further review. 51 | 52 | 4. If all the required improvements have been made and the team approves your article, then your article will be published. 53 | -------------------------------------------------------------------------------- /docs/dynamic-programming/dynamic-programming.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: What is Dynamic Programming? 3 | slug: /dynamic-programming 4 | --- 5 | 6 | This page would serve our needs for documentation of Dynamic Programming. -------------------------------------------------------------------------------- /docs/dynamic-programming/egg-dropping-problem.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Egg Dropping Problem 3 | slug: /dynamic-programming/egg-dropping-problem 4 | --- 5 | 6 | This page would serve our needs for documentation of the Egg Dropping Problem. -------------------------------------------------------------------------------- /docs/dynamic-programming/golomb-sequence.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Golomb Sequence 3 | slug: /dynamic-programming/golomb-sequence 4 | --- 5 | 6 | ## Introduction 7 | 8 | Golomb sequence is a non-decreasing sequence of integers where the nth term of the sequence is equal to the number of times `n` appears in the sequence. 9 | 10 | ## Explanation 11 | 12 | - The Golomb sequence is given by, 13 | 14 | `Golomb(1) = 1 (Base case)` 15 | 16 | `Golomb(n) = 1 + Golomb(n - Golomb(Golomb(n - 1))) for n > 1`. 17 | 18 | - Let us see one example: 19 | 20 | ``` 21 | - The first few terms of the Golomb sequence are: `1, 2, 2, 3, 3, 4, 4, 4, . . .` 22 | - Here, the first term of the sequence is `1`, which means that `1` must appear only one time in 23 | the sequence. 24 | - Similarly, the second term is `2`, and we can see that `2` appears twice in the sequence. 25 | ``` 26 | 27 | ## Algorithm 28 | 29 | ``` 30 | - Given a number n. 31 | - Make an array to store the values of the Golomb sequence in a bottom-up manner. 32 | - Initialize array[1] = 1. 33 | - for i = 2 to n 34 | - array[i] = 1 + array[i - array[array[i - 1]]] 35 | - return array[n] 36 | ``` 37 | 38 | ## Code 39 | 40 | import Tabs from '@theme/Tabs'; 41 | import TabItem from '@theme/TabItem'; 42 | 43 | 50 | 51 | 52 | ```cpp 53 | #include 54 | using namespace std; 55 | 56 | int golomb_sequence(int n) 57 | { 58 | // Create a dp array, with value initialized as 0. 59 | int dp[n + 1]; 60 | 61 | dp[1] = 1; 62 | 63 | /* 64 | Identify the previous term 'prev' and go prev terms behind and find a number. 65 | Now assign the current element with an incremented value of that element. 66 | */ 67 | 68 | for (int i = 2; i <= n; i++) 69 | { 70 | int prev = dp[i - 1]; 71 | int back_index = i - dp[prev]; 72 | dp[i] = 1 + dp[back_index]; 73 | } 74 | return dp[n]; 75 | } 76 | 77 | int main() 78 | { 79 | int n; 80 | cout << "Enter the value of n: "; 81 | cin >> n; 82 | if (n <= 0) 83 | { 84 | cout << "\nThe given value of n is invalid." << endl; 85 | return 0; 86 | } 87 | int res = golomb_sequence(n); 88 | cout << "\nThe term at index " << n << " of the golomb sequence is " << res << "." << endl; 89 | return 0; 90 | } 91 | ``` 92 | 93 | 94 | 95 | 96 | ```py 97 | def golomb_sequence(n): 98 | 99 | # Create a dp array, with value initialized as 0. 100 | dp = [0 for i in range(n+1)] 101 | 102 | dp[1] = 1 103 | # Identify the previous term 'prev' and go prev terms behind and find a number. 104 | # Now assign the current element with an incremented value of that element. 105 | for i in range(2, n + 1): 106 | prev = dp[i - 1] 107 | back_index = i - dp[prev] 108 | dp[i] = 1 + dp[back_index] 109 | return dp[n] 110 | 111 | if __name__ == '__main__': 112 | print("Enter the value of n: ", end="") 113 | num = int(input()) 114 | if num <= 0: 115 | print("\nThe given value of n is invalid.") 116 | exit() 117 | res = golomb_sequence(num) 118 | print("\nThe term at index {} of the golomb sequence is {}.".format(num, res)) 119 | ``` 120 | 121 | 122 | 123 | 124 | ## Sample Input and Output 125 | 126 | #### Input: 127 | 128 | ``` 129 | Enter the value of n: 5 130 | ``` 131 | 132 | #### Output: 133 | 134 | ``` 135 | The term at index 5 of the golomb sequence is 3. 136 | ``` 137 | 138 | ## Complexity Analysis 139 | 140 | - Time complexity: `O(n)` 141 | - Space complexity: `O(n)` 142 | 143 | Here `n` is the given number. 144 | 145 | ## Credits 146 | 147 | - [Hari Krishnan U](https://github.com/Harikrishnan6336) for the [C++ Implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/dp/golomb_sequence.cpp) 148 | - [Hari Krishnan U](https://github.com/Harikrishnan6336) for the [Python Implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/Python/dp/golomb_sequence.py) 149 | -------------------------------------------------------------------------------- /docs/getting-started.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Getting Started 3 | slug: /remove-it-later 4 | --- 5 | 6 | ## Step 1: Generate a new Docusaurus site 7 | 8 | If you haven't already, generate a new Docusaurus site using the classic template: 9 | 10 | ```shell 11 | npx @docusaurus/init@latest init my-website classic 12 | ``` 13 | 14 | ## Step 2: Start your Docusaurus site 15 | 16 | Run the development server in the newly created `my-website` folder: 17 | 18 | ```shell 19 | cd my-website 20 | 21 | npx docusaurus start 22 | ``` 23 | 24 | Open `docs/getting-started.md` and edit some lines. The site reloads automatically and display your changes. 25 | 26 | ## That's it! 27 | 28 | Congratulations! You've successfully run and modified your Docusaurus project. 29 | -------------------------------------------------------------------------------- /docs/graph-algorithms/breadth-first-search.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Breadth First Search 3 | slug: /graph-algorithms/breadth-first-search 4 | --- 5 | 6 | This page would serve our needs for documentation of the Breadth First Search Algorithm. -------------------------------------------------------------------------------- /docs/graph-algorithms/graph-algorithms.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Graph Algorithms 3 | slug: /graph-algorithms 4 | --- 5 | 6 | This page would serve our needs for documentation of the Graph Algorithms. -------------------------------------------------------------------------------- /docs/introduction/About-NeoAlgo.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: About NeoAlgo 3 | slug: / 4 | --- 5 | 6 | Information about NeoAlgo 7 | -------------------------------------------------------------------------------- /docs/introduction/contributor-handbook.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Contributor Handbook 3 | slug: /contributor-handbook 4 | --- 5 | 6 | This page would serve our needs for a Contributor's Handbook. -------------------------------------------------------------------------------- /docs/introduction/development-setup.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Development Setup 3 | slug: /development-setup 4 | --- 5 | 6 | This page would serve our needs for documentation of a Development Setup. It would contain a small tutorial on cloning `NeoAlgo` and `NeoAlgo-Docs`, creating 7 | a branch, making a commit and sending a Pull Request. We would need to try to make it visually engaging through pictures. -------------------------------------------------------------------------------- /docs/machine-learning/linear-regression.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Linear Regression 3 | slug: /machine-learning/linear-regression 4 | --- 5 | 6 | This page would serve our needs for documentation of the Linear Regression algorithms. -------------------------------------------------------------------------------- /docs/machine-learning/machine-learning.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Machine Learning 3 | slug: /machine-learning 4 | --- 5 | 6 | This page would serve our needs for documentation of the Machine Learning algorithms. -------------------------------------------------------------------------------- /docs/markdown-features.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Markdown Features 3 | --- 4 | 5 | Docusaurus supports the [Markdown](https://daringfireball.net/projects/markdown/syntax) syntax and has some additional features. 6 | 7 | ## Front Matter 8 | 9 | Markdown documents can have associated metadata at the top called [Front Matter](https://jekyllrb.com/docs/front-matter/): 10 | 11 | ```md 12 | --- 13 | id: my-doc 14 | title: My document title 15 | description: My document description 16 | sidebar_label: My doc 17 | --- 18 | 19 | Markdown content 20 | ``` 21 | 22 | ## Markdown links 23 | 24 | Regular Markdown links are supported using url paths or relative file paths. 25 | 26 | ```md 27 | Let's see how to [Create a page](/create-a-page). 28 | ``` 29 | 30 | ```md 31 | Let's see how to [Create a page](./create-a-page.md). 32 | ``` 33 | 34 | Let's see how to [Create a page](./create-a-page.md). 35 | 36 | ## Markdown images 37 | 38 | Regular Markdown images are supported. 39 | 40 | ## Code Blocks 41 | 42 | Markdown code blocks are supported with Syntax highlighting. 43 | 44 | ```jsx title="src/components/HelloDocusaurus.js" 45 | function HelloDocusaurus() { 46 | return ( 47 |

Hello, Docusaurus!

48 | ) 49 | } 50 | ``` 51 | 52 | ```jsx title="src/components/HelloDocusaurus.js" 53 | function HelloDocusaurus() { 54 | return

Hello, Docusaurus!

; 55 | } 56 | ``` 57 | 58 | ## Admonitions 59 | 60 | Docusaurus has a special syntax to create admonitions and callouts: 61 | 62 | :::tip My tip 63 | 64 | Use this awesome feature option 65 | 66 | ::: 67 | 68 | :::danger Take care 69 | 70 | This action is dangerous 71 | 72 | ::: 73 | 74 | :::tip My tip 75 | 76 | Use this awesome feature option 77 | 78 | ::: 79 | 80 | :::danger Take care 81 | 82 | This action is dangerous 83 | 84 | ::: 85 | 86 | ## React components 87 | 88 | Thanks to [MDX](https://mdxjs.com/), you can make your doc more interactive and use React components inside Markdown: 89 | 90 | ```jsx 91 | export const Highlight = ({children, color}) => ( 92 | 99 | {children} 100 | 101 | ); 102 | 103 | Docusaurus green and Facebook blue are my favorite colors. 104 | ``` 105 | 106 | export const Highlight = ({children, color}) => ( 107 | 114 | {children} 115 | 116 | ); 117 | 118 | Docusaurus green and 119 | Facebook blue 120 | are my favorite colors. 121 | -------------------------------------------------------------------------------- /docs/mathematics/Kth-smallest.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: K-th smallest element in an array 3 | slug: /mathematics/Kth-smallest 4 | --- 5 | 6 | ## Introduction 7 | 8 | In this article we will be given a array and a number K we have to find the `Kth` smallest element in an array. Kth smallest means when we arrange the data in ascending order then the element which is at the `Kth` index is the kth smallest element. 9 | 10 | ## Explanation 11 | 12 | In this first we have to sort the array in ascending order. Then print `Kth` index(if `1` based indexing that means array index starts from `1`) or `(K-1)th` index(if `0` based indexing that means array index starts from `0`). 13 | 14 | #### Example 1 15 | 16 | ``` 17 | Given arr[8]= | 20 | 62 | 38 | 16 | 94 | 71 | 82 | 53 | 18 | Given K: 5 19 | So first we sort the array in ascending order 20 | After sorting: | 16 | 20 | 38 | 53 | 62 | 71 | 82 | 94 | 21 | Then print the value at K-1th index(0 based indexing) that is 4th index 22 | The value at 4th index: 62 23 | 24 | ``` 25 | 26 | ## Algorithm 27 | 28 | For printing Kth smallest element in an array, we follow the following algorithm: 29 | 30 | * First, we sort the array in ascending order. 31 | 32 | * Consider K index(if 1 based indexing) or K index(if 0 based indexing). 33 | 34 | * Print the element at K index(if 1 based indexing) or at K-1 index(if 0 based indexing). 35 | 36 | ## Code 37 | 38 | import Tabs from '@theme/Tabs'; 39 | import TabItem from '@theme/TabItem'; 40 | 41 | 48 | 49 | 50 | ```cpp 51 | #include 52 | using namespace std; 53 | 54 | // function for finding kth smallest element 55 | int kthsmallest(int k,int a[], int n) 56 | { 57 | //sort the array 58 | sort(a,a+n); 59 | 60 | //return element at a[k-1] index 61 | return a[k-1]; 62 | } 63 | //main function 64 | int main() 65 | { 66 | int n; 67 | 68 | //Taking size as input 69 | cout<<"Enter the size of array: "; 70 | cin>>n; 71 | int a[n]; 72 | cout<<"Enter the elements of array: "; 73 | 74 | //Taking elements of array 75 | for(int i=0;i>a[i]; 78 | } 79 | int x; 80 | cout<<"Enter the value of K: "; 81 | cin>>x; 82 | //Printing occurrence of given number 83 | cout< 89 | 90 | 91 | 92 | ```python 93 | def kthsmallest(arr, n, k): 94 | # Sort the array 95 | arr.sort() 96 | return arr[k-1] 97 | 98 | if __name__ == '__main__': 99 | # Taking size as input 100 | n = int(input("Enter the size of array: ")) 101 | data = [] 102 | # Taking array element as input 103 | print ("Enter the elements of array: ") 104 | for i in range(n): 105 | data.append(int(input())) 106 | x = int(input("Enter the value of K: ")) 107 | 108 | #Printing the occurrence of given number 109 | print(kthsmallest(data,n,x)) 110 | 111 | 112 | ``` 113 | 114 | 115 | 116 | ## Sample Input and Output 117 | 118 | #### Input : 119 | 120 | ``` 121 | Enter the size of array: 8 122 | Enter the elements of array: 20 62 38 16 94 71 82 53 123 | Enter the value of K: 5 124 | 125 | ``` 126 | #### Output : 127 | 128 | ``` 129 | 62 130 | ``` 131 | 132 | ## Complexity Analysis 133 | 134 | - Time Complexity: `O(nlogn)` 135 | 136 | - Space Complexity: `O(1)` 137 | 138 | where `n` is the number of elements. 139 | -------------------------------------------------------------------------------- /docs/mathematics/ackermann-function.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Ackermann Function 3 | slug: /mathematics/Ackermann-Function 4 | --- 5 | 6 | ## Introduction 7 | 8 | The Ackermann function is multi-variable function from the natural numbers to the natural numbers with very fast rate of growth. It is one of the classic example of a recursive function, that is not a primitive recursive function. All primitive recursive functions are total and computable, but the Ackermann function illustrates that not all total computable functions are primitive recursive. 9 | 10 | ## Explanation 11 | 12 | It is basically a function with two non-negative integers as arguments. 13 | Assuming `i` and `j` as the non-negative integers. 14 | Ackermann function can be declared as: 15 | ``` 16 | A(0, j)=j+1 for j ≥ 0 17 | A(i, 0)=A(i-1, 1) for i > 0 18 | A(i, j)=A(i-1, A(i, j-1)) for i, j > 0 19 | ``` 20 | Let's have an example to see how the Ackermann function grows so quickly: 21 | ``` 22 | A(1,2) = A(0, A(1, 1)) // applying third condition of Ackermann function 23 | = A(0, A(0, A(1, 0))) // applying third condition of Ackermann function 24 | = A(0, A(0, A(0, 1))) // applying second condition of Ackermann function 25 | = A(0, A(0, 2)) // applying first condition of Ackermann function: A(0, 1) = 2 26 | = A(0, 3) // applying first condition of Ackermann function: A(0, 2) = 3 27 | = 4. // applying first condition of Ackermann function: A(0, 3) = 4 28 | ``` 29 | 30 | ## Algorithm 31 | 32 | ``` 33 | Ackermann(i, j): 34 | - Checking the values of `i` and `j` 35 | - Applying the associated conditions 36 | - Recursively calling the function until the first condition is applied 37 | - Obtaining the final result 38 | - Returning the resultant value 39 | ``` 40 | 41 | ## Code 42 | 43 | import Tabs from '@theme/Tabs'; 44 | import TabItem from '@theme/TabItem'; 45 | 46 | 53 | 54 | 55 | 56 | ```cpp 57 | #include 58 | using namespace std; 59 | int Ackermann_Function(int m, int n) { 60 | if (m == 0) 61 | return n + 1; 62 | 63 | else if (m > 0 && n == 0) 64 | return Ackermann_Function(m - 1, 1); 65 | 66 | else if (m > 0 && n > 0) 67 | return Ackermann_Function(m - 1, Ackermann_Function(m, n - 1)); 68 | } 69 | 70 | int main() { 71 | int m, n; 72 | cout << "Input first Number\n"; 73 | cin >> m; 74 | cout << "Input second Number\n"; 75 | cin >> n; 76 | cout << "Result: " << Ackermann_Function(m, n); 77 | return 0; 78 | } 79 | ``` 80 | 81 | 82 | 83 | 84 | ```dart 85 | import 'dart:io'; 86 | 87 | int Ackermann_Function(int m, int n) { 88 | if (m == 0) 89 | return n + 1; 90 | else if (m > 0 && n == 0) 91 | return Ackermann_Function(m - 1, 1); 92 | else if (m > 0 && n > 0) return Ackermann_Function(m - 1, Ackermann_Function(m, n - 1)); 93 | 94 | return 0; 95 | } 96 | 97 | void main() { 98 | print("Input first Number"); 99 | int m = int.parse(stdin.readLineSync()!); 100 | print("Input second Number"); 101 | int n = int.parse(stdin.readLineSync()!); 102 | int result = Ackermann_Function(m, n); 103 | print("Result: $result"); 104 | } 105 | ``` 106 | 107 | 108 | 109 | 110 | ## Sample Input and Output 111 | 112 | #### Input: 113 | 114 | ``` 115 | Input first Number 116 | 1 117 | Input second Number 118 | 2 119 | ``` 120 | 121 | #### Output: 122 | 123 | ``` 124 | Result: 4 125 | ``` 126 | 127 | ## Complexity Analysis 128 | 129 | - Time complexity - `O(mA(m, n))` to calculate `A(m,n)` 130 | - Space complexity - `O(m)` to calculate `A(m, n)` 131 | Here, `m` and `n` are the two integers that we take from user 132 | 133 | ## Credits 134 | 135 | - [Ritvij Kumar Sharma](https://github.com/ritvij14) contributed the [Dart implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/Dart/maths/Ackermann_function.dart) 136 | - [Yash Thakare](https://github.com/YashThakare) contributed the [C++ implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/math/Ackermann_function.cpp) 137 | -------------------------------------------------------------------------------- /docs/mathematics/automorphic-number.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Automorphic Number 3 | slug: /mathematics/automorphic-number 4 | --- 5 | 6 | ## Introduction 7 | 8 | An automorphic number is a number whose square ends with the given original integer. 9 | 10 | ## Explanation 11 | 12 | First, calculate the square of the given number and check if the last digits of the squared number are the same as the original number. 13 | 14 | Let's have one example: 15 | 16 | ``` 17 | Input : 76 18 | Output : Yes 19 | 20 | (76)^2 = 57`76` 21 | 22 | Input : 3 23 | Output : No 24 | 25 | (3)^2 = 9 26 | ``` 27 | 28 | ## Algorithm 29 | 30 | - Compute the square of the given number. 31 | - Check if the last digits of the squared number are the same as the original number. 32 | - If found same then we can say it is an automorphic number else it is not an automorphic number. 33 | 34 | ## Code 35 | 36 | import Tabs from '@theme/Tabs'; 37 | import TabItem from '@theme/TabItem'; 38 | 39 | 46 | 47 | 48 | ```cpp 49 | #include 50 | 51 | using namespace std; 52 | 53 | int Check_Automorphic(int n){ 54 | 55 | int square, temp, remainder, no_digits = 0; 56 | temp = n; 57 | square = n * n; 58 | int flag = 10; 59 | 60 | while (n != 0) 61 | { 62 | n = n / 10; 63 | no_digits++; 64 | } 65 | 66 | flag = pow(10, no_digits); 67 | remainder = square % flag; 68 | 69 | if (remainder == temp) 70 | return 1; 71 | else 72 | return 0; 73 | } 74 | 75 | int main(){ 76 | 77 | long long int num; 78 | cout << "Enter the number you want to check :"; 79 | cin >> num; 80 | 81 | int result = Check_Automorphic(num); 82 | 83 | if (result == 1) 84 | cout<<"The given number is Automorphic number!"<< endl; 85 | 86 | else 87 | cout<<"The given number is not Automorphic number!"<< endl; 88 | } 89 | ``` 90 | 91 | 92 | 93 | 94 | ```go 95 | package main 96 | 97 | import ( 98 | 99 | "fmt" 100 | 101 | ) 102 | 103 | // This is a global variable 104 | var n int 105 | 106 | // This function tells us if the number is automorphic number or not 107 | func automorphicnumber() { 108 | 109 | var number int 110 | var b int 111 | b = n 112 | number = n*n 113 | i := 1 114 | 115 | //to construct the last digits 116 | for b != 0 { 117 | i = i*10 118 | b = b/10 119 | } 120 | 121 | //checking if the last digits form the orginal number 122 | if((number%i) == n) { 123 | 124 | fmt.Print("The given number is Automorphic number!") 125 | 126 | }else{ 127 | 128 | fmt.Print("The given number is not Automorphic number!") 129 | } 130 | 131 | } 132 | 133 | // driver function 134 | func main() { 135 | 136 | fmt.Print("Enter the number you want to check :") 137 | fmt.Scan(&n) 138 | 139 | // calling automorphic function 140 | automorphicnumber() 141 | } 142 | ``` 143 | 144 | 145 | 146 | 147 | ## Sample Input and Output 148 | 149 | #### Input: 150 | 151 | ``` 152 | Enter the number you want to check :76 153 | ``` 154 | 155 | #### Output: 156 | 157 | ``` 158 | The given number is Automorphic number! 159 | 160 | ``` 161 | 162 | #### Input: 163 | 164 | ``` 165 | Enter the number you want to check :7 166 | ``` 167 | 168 | #### Output: 169 | 170 | ``` 171 | The given number is not Automorphic number! 172 | 173 | ``` 174 | 175 | ## Complexity Analysis 176 | 177 | - Time complexity: `O(n)` 178 | - Space complexity : `O(1)` 179 | 180 | ## Credits 181 | 182 | - [Ayush Jha](https://github.com/ayushjha952) contributed the [C++ implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/math/automorphic_number.cpp) 183 | - [Naga Srihith Penjarla](https://github.com/nagasrihith608) contributed the [Go implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/Go/math/Automorphic_Number/automorphicnumber.go) 184 | -------------------------------------------------------------------------------- /docs/mathematics/binary-exponentiation.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Binary Exponentiation 3 | slug: /mathematics/binary-exponentiation 4 | --- 5 | 6 | ## Introduction 7 | 8 | Binary Exponentiation is a trick that allows us to calculate `a` raise to the power of `b` in logarithmic time complexity. It is also called exponentiation by squaring. It can also be extended to Modular Exponentiation. Both `C++` and `Python` provide a built-in power function that works in `O(log N)` time complexity. 9 | 10 | ## Explanation 11 | 12 | The Power of two numbers is calculated by multiplying the base by itself, exponent times. `a` raise to the power `b` is denoted by `pow(a,b)`. The Power of an even number is always even and odd is always odd. Any number raised to power `0` is always `1`. 13 | 14 | Here is the formula of the same: 15 | 16 | ``` 17 | pow(a,b) = a*a*a*a*a....b times 18 | ``` 19 | 20 | Here are the properties of the power: 21 | 22 | ``` 23 | pow(a,b) = pow(|a|,b), if a is negative and b is even 24 | pow(a,b) = -pow(|a|,b), if a is negative and b is odd 25 | pow(a,0) = 1 26 | pow(a,b) * pow(a,c) = pow(a,b+c) 27 | pow(a,b) / pow(a,c) = pow(a,b-c) 28 | ``` 29 | 30 | Let's have one example: 31 | 32 | ``` 33 | pow(2,5) 34 | a = 2 35 | b = 5 36 | res = 1 37 | 38 | Iteration 1: 39 | If ( b % 2 != 0) res = res * a = 2 40 | b = b / 2 = 2 41 | a = a * a = 4 42 | 43 | Iteration 2: 44 | If (b % 2 != 0) res = res * a 45 | b = b / 2 = 1 46 | a = a * a = 16 47 | 48 | Iteration 3: 49 | If (b % 2 != 0) res = res * a = 32 50 | b = b / 2 = 0 51 | a = a * a = 256 52 | ``` 53 | 54 | ## Algorithm 55 | 56 | - Declare a variable `res` and initialize it to `1`. 57 | 58 | - If `b` is odd then multiply `res` with `a` and reduce `b` by `1`. 59 | 60 | - If `b` is even then multiply `a` with `a` and reduce `b` to `b/2`. 61 | 62 | - Apply the previous two steps until `b` becomes `0`. 63 | 64 | ## Code 65 | 66 | import Tabs from '@theme/Tabs'; 67 | import TabItem from '@theme/TabItem'; 68 | 69 | 76 | 77 | 78 | ```cpp 79 | #include 80 | using namespace std; 81 | // Function to get pow(a,b) in logarithmic time 82 | 83 | int power(int a, int b) 84 | { 85 | if (b == 0) return 1; 86 | int res = 1; 87 | do 88 | { 89 | if (b % 2 != 0) 90 | { 91 | res = res * a; 92 | b = b - 1; 93 | } 94 | b = b / 2; 95 | a = a * a; 96 | } while (b > 0); 97 | 98 | return res; 99 | } 100 | 101 | int main() 102 | { 103 | cout << "Enter the Base: "; 104 | int a; 105 | cin >> a; 106 | cout << "Enter the Exponent: "; 107 | int b; 108 | cin >> b; 109 | 110 | cout << "Power is: " << power(a, b); 111 | return 0; 112 | } 113 | ``` 114 | 115 | 116 | 117 | 118 | ```python 119 | # Function to get power(a^b) in logarithmic time 120 | 121 | def power(a, b): 122 | res = 1 123 | # If exponent is 0 124 | 125 | if b == 0: 126 | return 1 127 | if b == 1: 128 | return a 129 | while b > 0: 130 | if b % 2 != 0: 131 | res *= a 132 | b -= 1 133 | a = a * a 134 | b = b // 2 135 | return res 136 | 137 | if __name__ == "__main__": 138 | 139 | a = int(input("Enter the Base: ")) 140 | b = int(input("Enter the Exponent: ")) 141 | 142 | print("Power is:", power(a, b)) 143 | ``` 144 | 145 | 146 | 147 | 148 | ## Sample Input and Output 149 | 150 | #### Input : 151 | 152 | ``` 153 | Enter the Base: 2 154 | Enter the Exponent: 3 155 | ``` 156 | 157 | #### Output : 158 | 159 | ``` 160 | Power is: 8 161 | ``` 162 | 163 | ## Complexity Analysis 164 | 165 | - Time Complexity: `O(log b)`, where`b` is the exponent 166 | 167 | - Space Complexity: `O(1)` 168 | -------------------------------------------------------------------------------- /docs/mathematics/count-bits.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Count no. of bits in a number 3 | slug: /mathematics/count-bits 4 | --- 5 | 6 | ## Introduction 7 | 8 | In this article, we will see how to count number of bits in a number. We are given a number and we have to count the number of bits in its binary representation. 9 | 10 | ## Explanation 11 | 12 | We are given a number and we have to print the number of bits in binary representation of that number. 13 | 14 | #### Example 1 15 | 16 | ``` 17 | Given number: 6 18 | Binary representation of given number(6)=110 19 | So number of bits in 6 is 3 20 | Print 3 21 | ``` 22 | ## Algorithm 23 | 24 | For count number of bits in a number, we follow the following algorithm: 25 | 26 | - First, we convert the number into its binary representation. 27 | - Count number of bits in binary representation. 28 | - Print the value of count. 29 | 30 | ## Code 31 | 32 | import Tabs from '@theme/Tabs'; 33 | import TabItem from '@theme/TabItem'; 34 | 35 | 42 | 43 | 44 | ```cpp 45 | #include 46 | using namespace std; 47 | 48 | //function for counting number of bits 49 | int count_bits(int n) 50 | { 51 | //initialize count with 0 52 | int count=0; 53 | 54 | // counting number of bits in binary representation of number 55 | while(n!=0) 56 | { 57 | count++; 58 | n=n/2; 59 | } 60 | return count; 61 | } 62 | 63 | //main function 64 | int main() 65 | { 66 | int n; 67 | 68 | //Taking number as input 69 | cout<<"Enter the number: "; 70 | cin>>n; 71 | 72 | //Printing count of bits of given number 73 | cout< 79 | 80 | 81 | 82 | ```python 83 | # function count_bits for counting number of bits in binary representation 84 | def count_bits(n): 85 | 86 | # initialize count with 0 87 | count=0 88 | while(n!=0): 89 | count+=1 90 | n=n//2 91 | 92 | return count 93 | 94 | # Taking number as input 95 | n = int(input("Enter the number: ")) 96 | #Printing count of bits of given number 97 | print(count_bits(n)) 98 | 99 | 100 | ``` 101 | 102 | 103 | 104 | ## Sample Input and Output 105 | 106 | #### Input : 107 | 108 | ``` 109 | Enter the number: 10 110 | 111 | ``` 112 | #### Output : 113 | 114 | ``` 115 | 4 116 | ``` 117 | 118 | ## Complexity Analysis 119 | 120 | - Time Complexity: `O(logn)` 121 | 122 | - Space Complexity: `O(1)` 123 | 124 | where `n` is the number of elements. 125 | -------------------------------------------------------------------------------- /docs/mathematics/count-of-digits.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Count of Digits 3 | slug: /mathematics/count-of-digits 4 | --- 5 | 6 | ## Introduction 7 | 8 | Count of digits refers to the sum of the frequency of all distinct digits in a number. The number having a higher count of digits will be greater than the number having a lower count of digits. In `C++` we can have a number having at max 20 count of digits. In `Python` there is no limits on the count of digits in a number. 9 | 10 | ## Explanation 11 | 12 | We need to keep on removing the least significant digit of a number and increase the count till the number becomes zero. All numbers in the range `[0,9]` have the count of digits as `1`. All numbers in the range `[10,99]` have the count of digits as `2`. All numbers in the range `[100,999]` have the count of digits as `3`. 13 | 14 | Let's have one example: 15 | ``` 16 | num = 4568 17 | cnt = 0 18 | 19 | Iteration 1: 20 | num = 4568/10 = 456 21 | cnt = cnt + 1 = 1 22 | 23 | Iteration 2: 24 | num = 456/10 = 45 25 | cnt = cnt + 1 = 2 26 | 27 | Iteration 3: 28 | num = 45/10 = 4 29 | cnt = cnt + 1 = 3 30 | 31 | Iteration 4: 32 | num = 4/10 = 0 33 | cnt = cnt + 1 = 4 34 | ``` 35 | 36 | ## Algorithm 37 | 38 | * Make a `cnt` variable and initialize it to `0`. 39 | 40 | * Keep on dividing the number by `10` and increase the `cnt` variable by `1` until the number becomes `0`. 41 | 42 | ## Code 43 | 44 | import Tabs from '@theme/Tabs'; 45 | import TabItem from '@theme/TabItem'; 46 | 47 | 54 | 55 | 56 | ```cpp 57 | #include 58 | using namespace std; 59 | 60 | //Function to count digits in the number 61 | 62 | int count_of_digits(int num) 63 | { 64 | if(num==0)return 1; 65 | int cnt = 0; 66 | while (num != 0) 67 | { 68 | //Incrementing cnt by 1 69 | 70 | cnt++; 71 | 72 | // Removing the least significant digit 73 | 74 | num = num / 10; 75 | } 76 | return cnt; 77 | } 78 | 79 | int main() 80 | { 81 | int num, cnt; 82 | 83 | //Taking Input 84 | 85 | cout << "Enter the number: "; 86 | cin >> num; 87 | 88 | // If the number is negative, convert it into positive 89 | 90 | if (num < 0) 91 | { 92 | num = num * -1; 93 | } 94 | 95 | // Call the function 96 | 97 | cnt = count_of_digits(num); 98 | 99 | // Print the obtained count 100 | 101 | cout << "The count of digits in the given number is: " << cnt; 102 | return 0; 103 | } 104 | ``` 105 | 106 | 107 | 108 | 109 | ```python 110 | #Function to count digits in the number 111 | 112 | def count_of_digits(n): 113 | if(n==0): 114 | return 1 115 | 116 | #Initializing cnt variable to zero 117 | 118 | cnt = 0 119 | while True: 120 | if(n==0): 121 | break 122 | 123 | #Increasing the cnt 124 | 125 | cnt+=1 126 | 127 | #Removing the least significant digit 128 | 129 | n = n//10 130 | return cnt 131 | 132 | #Taking Input 133 | 134 | n = int(input("Enter the number :")) 135 | 136 | #Printing Output 137 | 138 | print("The count of digits in the given number is: {} ".format(count_of_digits(n))) 139 | ``` 140 | 141 | 142 | 143 | 144 | ## Sample Input and Output 145 | 146 | #### Input : 147 | 148 | ``` 149 | Enter the number: 8965 150 | ``` 151 | #### Output : 152 | ``` 153 | The count of digits in the given number is: 4 154 | ``` 155 | 156 | ## Complexity Analysis 157 | 158 | `n` is the count of digits in the number. 159 | 160 | - Time Complexity: 161 | 162 | - **Best Case**: `O(n)` 163 | - **Average Case**: `O(n)` 164 | - **Worst Case**: `O(n)` 165 | 166 | - Space Complexity: `O(1)` 167 | 168 | ## Credits 169 | * [Hari Krishnan U](https://github.com/Harikrishnan6336) for the [C++ implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/math/number_of_digits.cpp) -------------------------------------------------------------------------------- /docs/mathematics/decimal-to-binary.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Decimal to Binary Conversion 3 | slug: /mathematics/decimal-to-binary 4 | --- 5 | 6 | ## Introduction 7 | 8 | Decimal numbers are numbers having base 10 and binary numbers are numbers having base 2. 9 | It is possible to convert the numbers from one number system into another. 10 | In this article, we will see how to convert a positive decimal number into its binary equivalent. 11 | 12 | ## Explanation 13 | 14 | We need to keep storing the remainder in a vector (list in case of Python) while dividing the number by 2 and print the stored values in reverse order. 15 | This method is known as `double dabble method`. 16 | 17 | Let's have one example: 18 | ``` 19 | Let 8 be our decimal number. 20 | Using the double dabble method, 21 | 22 | Division Remainder List 23 | 8 / 2 0 0 24 | 4 / 2 0 0, 0 25 | 2 / 2 0 0, 0, 0 26 | 1 / 2 1 0, 0, 0, 1 27 | 28 | Binary number : 1000 29 | ``` 30 | 31 | ## Algorithm 32 | 33 | - Check if the given decimal is 0. If it is, then its binary equivalent is also 0, hence print it. 34 | - Create a vector of integers named _binary_. 35 | - While the given decimal is not equal to 0, 36 | - Obtain the remainder i.e. `remainder = decimal % 2` 37 | - Add remainder to the vector. 38 | - Divide the number by 2 i.e. `decimal = decimal / 2` 39 | - Reverse the vector and print it. 40 | 41 | ## Code 42 | 43 | import Tabs from '@theme/Tabs'; 44 | import TabItem from '@theme/TabItem'; 45 | 46 | 53 | 54 | 55 | ```cpp 56 | #include 57 | using namespace std; 58 | 59 | //function to convert a positive decimal number into its binary equivalent 60 | long long DecimalToBinary(int decimal) { 61 | long long binaryNumber = 0; 62 | int remainder, i = 1; 63 | 64 | while (decimal != 0) { 65 | remainder = decimal % 2; 66 | decimal /= 2; 67 | binaryNumber += remainder * i; 68 | i *= 10; 69 | } 70 | return binaryNumber; 71 | } 72 | 73 | int main(){ 74 | int decimal; 75 | cout << "Enter a decimal number : "; 76 | cin >> decimal; 77 | cout << "Binary equivalent : "<< DecimalToBinary(decimal); 78 | } 79 | ``` 80 | 81 | 82 | 83 | 84 | ```py 85 | #Function to convert a positive decimal number into its binary equivalent 86 | def DecimalToBinary(decimal): 87 | if decimal == 0: 88 | print('0000') 89 | return 90 | else: 91 | binary = [] 92 | while decimal != 0: 93 | rem = decimal % 2 94 | binary.append(rem) 95 | decimal = decimal // 2 96 | 97 | binary.reverse() 98 | for bit in binary: 99 | print(bit, end="") 100 | 101 | #executable code 102 | decimal = int(input("Enter a decimal number to be converted to binary : ")) 103 | print("Binary number : ") 104 | DecimalToBinary(decimal) 105 | ``` 106 | 107 | 108 | 109 | 110 | ## Sample Input and Output 111 | 112 | ### Input: 113 | 114 | ``` 115 | Enter a decimal number to be converted into binary: 13 116 | ``` 117 | 118 | ### Output: 119 | 120 | ``` 121 | Binary number: 122 | 1101 123 | ``` 124 | 125 | ## Complexity Analysis 126 | 127 | - Time complexity : `O(n)` 128 | - Space complexity : `O(1)` 129 | 130 | ## Credits 131 | 132 | - [Srishti](https://github.com/SrishtiAray07) for the [C++ implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/math/Convert_decimal_to_binary.cpp) 133 | - [Tanvi Bugdani](https://github.com/tanvi355) for the [Python implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/Python/math/positive_decimal_to_binary.py) 134 | -------------------------------------------------------------------------------- /docs/mathematics/double-factorial.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Double Factorial 3 | slug: /mathematics/double-factorial 4 | --- 5 | 6 | ## Introduction 7 | 8 | Double Factorial of a number `n` is defined as the product of all positive integers less than or equal to `n` which are having the same parity as of `n`. Parity can be even or odd. Double Factorial is defined for all non-negative integers. It is also called semifactorial. It is denoted by `!!` symbol. The value of `0!!` is `1`. 9 | 10 | ## Explanation 11 | 12 | For a non-negative integer say `n`, Double factorial of `n` is defined as follows: 13 | 14 | If `n` is even: 15 | ``` 16 | DoubleFactorial(n) = n * (n - 2) * . . . . . 4 * 2 17 | ``` 18 | 19 | If `n` is odd: 20 | ``` 21 | DoubleFactorial(n) = n * (n - 2) * . . . . . 3 * 1 22 | ``` 23 | 24 | Let's have few examples: 25 | ``` 26 | num = 6 27 | res = 2 * 4 * 6 , as all of them are even 28 | res = 48 29 | 30 | num = 3 31 | res = 1 * 3 , as all of them are odd 32 | res = 3 33 | ``` 34 | 35 | ## Algorithm 36 | 37 | - Declare a variable `res` and initialize it to `1`. 38 | 39 | - Multiply all the numbers in the range `1 to n` having the same parity as of `n` to `res`. 40 | 41 | - Return `res`. 42 | 43 | ## Code 44 | 45 | import Tabs from '@theme/Tabs'; 46 | import TabItem from '@theme/TabItem'; 47 | 48 | 55 | 56 | 57 | ```cpp 58 | #include 59 | using namespace std; 60 | // Function to determine the double factorial of a number 61 | 62 | int Double_factorial(int n) 63 | { 64 | int ans=1; 65 | // If Number is even 66 | 67 | if(n % 2 == 0) 68 | { 69 | int temp1 = 2; 70 | while (temp1 <= n) 71 | { 72 | ans *= temp1; 73 | temp1 += 2; 74 | } 75 | } 76 | // If Number is Odd 77 | 78 | else 79 | { 80 | int temp2 = 1; 81 | while (temp2 <= n) 82 | { 83 | ans *= temp2; 84 | temp2 += 2; 85 | } 86 | } 87 | return ans; 88 | } 89 | int main() 90 | { 91 | cout << "Enter the Number: "; 92 | int n; 93 | cin >> n; 94 | 95 | cout<<"Double Factorial is: "< 100 | 101 | 102 | 103 | ```python 104 | # Function to determine the double factorial of a number 105 | 106 | def Double_factorial(n): 107 | ans=1 108 | # If number is even 109 | 110 | if(n % 2 == 0): 111 | temp1 = 2 112 | while (temp1 <= n): 113 | ans *= temp1 114 | temp1 += 2 115 | # If number is odd 116 | 117 | else: 118 | temp2 = 1 119 | while (temp2 <= n): 120 | ans *= temp2 121 | temp2 += 2 122 | return ans 123 | 124 | if __name__ == '__main__': 125 | 126 | n = int(input("Enter the Number: ")) 127 | 128 | print("Double Factorial is: ",Double_factorial(n)) 129 | ``` 130 | 131 | 132 | 133 | 134 | ## Sample Input and Output 135 | 136 | #### Input : 137 | 138 | ``` 139 | Enter the Number: 5 140 | ``` 141 | 142 | #### Output : 143 | 144 | ``` 145 | Double Factorial is: 15 146 | ``` 147 | 148 | ## Complexity Analysis 149 | 150 | - Time Complexity: `O(n)` 151 | 152 | - Space Complexity: `O(1)` -------------------------------------------------------------------------------- /docs/mathematics/euler-totient-function.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Euler Totient Function 3 | slug: /mathematics/euler-totient-function 4 | --- 5 | 6 | ## Introduction 7 | 8 | Euler Totient Function gives the count of numbers from `1 to n` which are coprime with `n`. Two numbers are coprime if their highest common factor is `1`. `1` is coprime to every number. It is also called phi-function and represented as `ϕ(n)`. 9 | 10 | ## Explanation 11 | 12 | We can calculate the value of Euler function by iterating from `1 to n` and checking if the gcd of the current number with `n` is `1` or not. 13 | 14 | Here are values of ϕ(n) for first 10 integers: 15 | ``` 16 | n | 1 | 2 | 3 | 4 | 5 | 7 | 9 | 10 17 | ϕ(n)| 1 | 1 | 2 | 2 | 4 | 2 | 6 | 4 18 | ``` 19 | 20 | Properties: 21 | ``` 22 | ϕ(ab) = ϕ(a)⋅ϕ(b), where a and b are relatively prime 23 | ϕ(ab) = ϕ(a)⋅ϕ(b)⋅(d/ϕ(d)), where a and b are not coprime and d = gcd(a,b) 24 | ``` 25 | 26 | Let's have one example: 27 | ``` 28 | num = 5 29 | cnt = 0 , to store the count of numbers which are coprime with `n` 30 | 31 | Iteration 1: 32 | i = 1 33 | if (gcd(1,num) == 1) increment cnt: 34 | cnt = 1 35 | 36 | Iteration 2: 37 | i = 2 38 | if (gcd(2,num) == 1) increment cnt: 39 | cnt = 2 40 | 41 | Iteration 3: 42 | i = 3 43 | if (gcd(3,num) == 1) increment cnt: 44 | cnt = 3 45 | 46 | Iteration 4: 47 | i = 4 48 | if (gcd(4,num) == 1) increment cnt: 49 | cnt = 4 50 | 51 | Iteration 5: 52 | i = 5 53 | if (gcd(5,num) == 1) increment cnt: 54 | cnt = 4 55 | ``` 56 | 57 | ## Algorithm 58 | 59 | - Declare a variable `cnt` and initialize it to `0`. 60 | - Now iterate from `1 to n` and check if the current number is coprime with `n` or not and if it is coprime then increase the `cnt` by `1` . 61 | - Return `cnt`. 62 | 63 | ## Code 64 | 65 | import Tabs from '@theme/Tabs'; 66 | import TabItem from '@theme/TabItem'; 67 | 68 | 75 | 76 | 77 | ```cpp 78 | #include 79 | using namespace std; 80 | // Function to get count of numbers from 1 to n which are coprime with n 81 | 82 | int euler_totient(int n) 83 | { 84 | if (n == 1) return 1; 85 | int tmp = 1; 86 | int cnt = 0; 87 | do 88 | { 89 | if (__gcd(tmp, n) == 1) 90 | { 91 | cnt++; 92 | } 93 | tmp++; 94 | } while (tmp < n); 95 | 96 | return cnt; 97 | } 98 | 99 | int main() 100 | { 101 | cout << "Enter the Number: "; 102 | int n; 103 | cin >> n; 104 | 105 | cout << "Count of Numbers from 1 to n which are coprime to n is: " << euler_totient(n); 106 | return 0; 107 | } 108 | ``` 109 | 110 | 111 | 112 | 113 | ```python 114 | import math 115 | # Function to get count of numbers from 1 to n which are coprime with n 116 | 117 | def euler_totient(n): 118 | if n == 1: 119 | return 1 120 | tmp = 1 121 | cnt = 0 122 | 123 | while tmp < n: 124 | if math.gcd(tmp, n) == 1: 125 | cnt = 1 126 | tmp = 1 127 | 128 | return cnt 129 | 130 | if __name__ == "__main__": 131 | 132 | n = int(input("Enter the Number: ")) 133 | 134 | print("Count of Numbers from 1 to n which are coprime to n is:", euler_totient(n)) 135 | ``` 136 | 137 | 138 | 139 | 140 | ## Sample Input and Output 141 | 142 | #### Input : 143 | 144 | ``` 145 | Enter the Number: 21 146 | ``` 147 | #### Output : 148 | 149 | ``` 150 | Count of Numbers from 1 to n which are coprime to n is: 12 151 | ``` 152 | 153 | ## Complexity Analysis 154 | 155 | - Time Complexity: `O(n)` 156 | - Space Complexity: `O(1)` 157 | -------------------------------------------------------------------------------- /docs/mathematics/extended-euclidean-Algorithm.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Extended Euclidean Algorithm 3 | slug: /mathematics/extended-euclidean-algorithm 4 | --- 5 | 6 | ## Introduction 7 | 8 | This is an extension of the already existing euclidean algorithm. Here also we find the GCD of the given two numbers. But here we also find additionally two numbers say `x`,`y`. The computation of these modular multiplicative inverse can come in handy in RSA public-key encryption method. 9 | 10 | ## Explanation 11 | 12 | We find the `GCD` of two numbers same as in the euclidean algorithm but additionally we compute two numbers say `a`,`b` which can be uses to exprecess the GCD computed till then as `ax + by`. 13 | 14 | Let's have one example: 15 | ``` 16 | Input : a = 30, b = 20 17 | Output: gcd = 10 18 | x = 1, y = -1 19 | 20 | Sequential steps: 21 | 30*1 + 20*(-1) = 10 22 | 23 | Input : a = 35, b = 15 24 | Output: gcd = 5 25 | x = 1, y = -2 26 | 27 | Sequential steps: 28 | 35*1 + 15*(-2) = 5 29 | ``` 30 | 31 | ## Algorithm 32 | 33 | - `x` and `y` are with respective to inputs `a` and `b`. 34 | - `a.x + b.y = gcd` 35 | - `x1` and `y1` are with respective to inputs `b%a` and `a`. 36 | - `(b%a).x1 + a.y1 = gcd` 37 | - We calculate the above values of `x1` and `y1` at every iteration. 38 | - Then we put `b%a = (b - (⌊b/a⌋).a)` in the equation to get : 39 | - `(b - (⌊b/a⌋).a).x1 + a.y1 = gcd` 40 | - This equation can also be written as `b.x1 + a.(y1 - (⌊b/a⌋).x1) = gcd` 41 | - So, the coeffitients `a` and `b` : 42 | - `x = y1 - ⌊b/a⌋ * x1` `y = x1` 43 | 44 | ## Code 45 | 46 | import Tabs from '@theme/Tabs'; 47 | import TabItem from '@theme/TabItem'; 48 | 49 | 56 | 57 | 58 | ```cpp 59 | #include 60 | #include 61 | 62 | using namespace std; 63 | 64 | int gcd (int a, int b, int &x, int &y) { 65 | //base case 66 | if (a == 0) { 67 | x = 0; y = 1; 68 | return b; 69 | } 70 | int x1, y1; 71 | int d = gcd (b % a, a, x1, y1); 72 | x = y1 - (b / a) * x1; 73 | y = x1; 74 | return d; 75 | } 76 | 77 | int main() { 78 | int x = 0, y = 0, a, b; 79 | cout<<"Enter the numbers whose GCD is to be found:"<>a>>b; 81 | cout<<"GCD of numbers "< 87 | 88 | 89 | ```py 90 | def Extended_gcd(a, b, x, y): 91 | #Base Case 92 | if a == 0: 93 | x = 0 94 | y = 1 95 | return b 96 | 97 | x1, y1 = 0, 0 98 | gcd = Extended_gcd(b % a, a, x1, y1) 99 | 100 | x = y1 - int(b / a) * x1 101 | y = x1 102 | 103 | return gcd 104 | 105 | if __name__ == '__main__' : 106 | 107 | print("Enter the numbers whose GCD is to be found: ") 108 | a = int(input()) 109 | b = int(input()) 110 | x, y = 0, 0 111 | print("GCD of numbers " + str(a) + " and " + str(b) + " is " + str(Extended_gcd(a, b, x, y))) 112 | ``` 113 | 114 | 115 | 116 | 117 | ## Sample Input and Output 118 | 119 | ### Input: 120 | 121 | ``` 122 | Enter the numbers whose GCD is to be found: 123 | 36 124 | 60 125 | ``` 126 | 127 | ### Output: 128 | 129 | ``` 130 | GCD of numbers 60 and 36 is 12 131 | ``` 132 | 133 | ## Complexity Analysis 134 | 135 | ``` 136 | Time complexity -O(Log min(a, b)) 137 | Space complexity -O(1) 138 | ``` 139 | 140 | ## Credits 141 | 142 | - [Supritha R S](https://github.com/suprithars111) contributed the [C++ implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/math/Extended_Euclidean_Algorithm.cpp) 143 | - [Abhinav Anand](https://github.com/atarax665) contributed the [Python implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/Python/math/Extended_Euclidean_Algorithm.py) 144 | -------------------------------------------------------------------------------- /docs/mathematics/factorial-of-number.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Factorial of a number 3 | slug: /mathematics/factorial-of-number 4 | --- 5 | 6 | ## Introduction 7 | 8 | Factorial of a number `n` is defined as the product of all positive integers less than or equal to `n`. Factorial function is defined for all non-negative integers. The value of `0!` is `1`. 9 | 10 | ## Explanation 11 | 12 | For a non-negative integer say `n`, factorial of `n` is defined as follows: 13 | 14 | ``` 15 | Factorial(n) = n * (n - 1) * (n - 2) * . . . . . 3 * 2 * 1 16 | ``` 17 | 18 | It is also defined as: 19 | 20 | ``` 21 | Factorial(n) = n * Factorial(n - 1) 22 | ``` 23 | 24 | Let us have a few examples: 25 | 26 | ``` 27 | Factorial(5) = 5 * 4 * 3 * 2 * 1 = 120 28 | Factorial(6) = 6 * 5 * 4 * 3 * 2 * 1 = 720 = 6 * Factorial(5) 29 | ``` 30 | 31 | ## Algorithm 32 | 33 | ### Recursive 34 | 35 | For a given number `n`, 36 | 37 | - If `n` == `1`, return `1`. 38 | - Else recursively return `n` * `factorial(n - 1)` 39 | 40 | ``` 41 | factorial(n): 42 | if(n == 1) 43 | return 1 44 | else 45 | return n * factorial(n - 1) 46 | ``` 47 | 48 | ### Iterative 49 | 50 | For a given number `n`, 51 | 52 | - Declare a variable factorial and initialize it to `1`. 53 | - For `num` starting from `1` to `n`. 54 | - Compute `factorial` = `factorial` * `num` 55 | - Add the end of the for loop, return the `factorial`. 56 | 57 | ``` 58 | factorial = 1 59 | for i = 1 to n 60 | factorial = factorial * i 61 | return factorial 62 | ``` 63 | 64 | ## Code 65 | 66 | import Tabs from '@theme/Tabs'; 67 | import TabItem from '@theme/TabItem'; 68 | 69 | 76 | 77 | 78 | 79 | ```cpp 80 | #include 81 | using namespace std; 82 | 83 | //This function calculates the factorial iteratively 84 | void factorial(int val) { 85 | int f = 1; 86 | if (val>0) { 87 | for(int i=1;i<=val;i++){ 88 | f = f*i; 89 | } 90 | cout << "The factorial of " << val << " is: "<< f << endl; 91 | } 92 | } 93 | 94 | // driver function 95 | int main(void) { 96 | int num; 97 | cout << "Enter the number: "; 98 | cin>>num; 99 | factorial(num); 100 | return 0; 101 | } 102 | ``` 103 | 104 | 105 | 106 | 107 | ```python 108 | # Iterative implementation for factorial 109 | def fact(x): 110 | result = 1 111 | for i in range(1,x): 112 | result = result * (i+1) 113 | return result 114 | 115 | # Calculate factorial using recursion 116 | def fact_rec(x): 117 | if x == 0 or x == 1: 118 | return 1 119 | else: 120 | return x * fact_rec(x-1) 121 | 122 | 123 | if __name__ == "__main__": 124 | n = int(input("Enter the number: ")) 125 | print("The factorial of {} is: {} ".format(n, fact(n))) 126 | ``` 127 | 128 | 129 | 130 | 131 | ## Sample Input and Output 132 | 133 | ### Input 134 | 135 | ``` 136 | Enter the number: 6 137 | ``` 138 | 139 | ### Output 140 | 141 | ``` 142 | The factorial of 6 is: 720 143 | ``` 144 | 145 | ## Complexity Analysis 146 | 147 | ``` 148 | Time complexity - O(n) 149 | Space complexity - O(1) 150 | ``` 151 | 152 | ## Credits 153 | 154 | - [Harsh Ghodkar](https://github.com/Saviour1001) for the [C++ implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/cp/long_factorials.cpp) 155 | - [Ricardo Prins](https://github.com/ricardoprins) for the [Python implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/Python/math/factorial.py) 156 | -------------------------------------------------------------------------------- /docs/mathematics/fibonacci-recursion.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Nth term in the Fibonacci sequence 3 | slug: /mathematics/fibonacci-recursion 4 | --- 5 | 6 | ## Introduction 7 | 8 | Fibonacci numbers form a sequence of numbers known as the Fibonacci sequence, such that each number is the sum of its two preceding numbers in the sequence. The series starts with `0` and `1`. 9 | 10 | ## Explanation 11 | 12 | For a non-negative number `n`, the `nth` fibonacci number is given by, 13 | 14 | Base case: 15 | 16 | ``` 17 | Fibonacci(0) = 0 18 | Fibonacci(1) = 1 19 | ``` 20 | 21 | General case: 22 | 23 | ``` 24 | Fibonacci(n) = Fibonacci(n - 1) + Fibonacci(n - 2), for n > 1 25 | ``` 26 | 27 | Let us have a look at a few examples: 28 | 29 | ``` 30 | Fibonacci(5) = 5 31 | Fibonacci(10) = 55 32 | ``` 33 | 34 | The first few terms of the fibonacci sequence are: `0, 1, 1, 2, 3, 5, 8, 13, . . . ` 35 | 36 | ## Algorithm 37 | 38 | - Given a number `n`. 39 | - Handle the base cases, i.e., for `n = 0` and `n = 1`. 40 | - For other cases, call the function recursively for `n - 1` and `n - 2`. 41 | 42 | ``` 43 | Pseudo-Code: 44 | 45 | fibonacci(n) 46 | If n = 0 47 | return 0 48 | If n = 1 49 | return 1 50 | Else 51 | return fibonacci(n-1) + fibonacci(n-2) 52 | ``` 53 | 54 | ## Code 55 | 56 | import Tabs from '@theme/Tabs'; 57 | import TabItem from '@theme/TabItem'; 58 | 59 | 66 | 67 | 68 | 69 | ```cpp 70 | #include 71 | using namespace std; 72 | 73 | // This function returns the nth terms in fibonacci sequence 74 | int fibonacci(int number) { 75 | // Base case for n = 0 and n = 1 76 | if(number == 0) 77 | return 0; 78 | else if(number == 1) 79 | return 1; 80 | // Recursively call the function for n-1 and n-2 81 | return fibonacci(number - 1) + fibonacci(number - 2); 82 | } 83 | 84 | int main() { 85 | 86 | // Take number as input from the user 87 | int number; 88 | cout << "Enter a number: "; 89 | cin >> number; 90 | 91 | // If number is less than 0, exit 92 | if(number < 0) { 93 | cout << "\nPlease enter a non-negative number." << endl; 94 | exit(0); 95 | } 96 | 97 | // Else call the function and print the nth term 98 | cout << "\nThe term at index " << number << " of the fibonacci sequence is "; 99 | cout << fibonacci(number) << endl; 100 | return 0; 101 | } 102 | ``` 103 | 104 | 105 | 106 | 107 | ```python 108 | def fibo_rec(x): 109 | 110 | if x == 0: 111 | return 0 112 | elif x == 1: 113 | return 1 114 | else: 115 | return fibo_rec(x-1) + fibo_rec(x-2) 116 | 117 | if __name__ == "__main__": 118 | 119 | n = int(input("Enter a number: ")) 120 | print("\nThe term at index " + str(n) + " of the fibonacci sequence is " + str(fibo_rec(n))) 121 | ``` 122 | 123 | 124 | 125 | 126 | ## Sample Input and Output 127 | 128 | #### Input 129 | 130 | ``` 131 | Enter a number: 7 132 | ``` 133 | 134 | #### Output 135 | 136 | ``` 137 | The term at index 7 of the fibonacci sequence is 13 138 | ``` 139 | 140 | ## Complexity Analysis 141 | 142 | - Time complexity: `O(2^n)` 143 | - Space complexity: `O(n)` 144 | 145 | ## Credits 146 | 147 | - [Nidhish Bhimrajka](https://github.com/nidh-ish) for the [CPP Implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/math/fibonacci.cpp) 148 | - [Prakash-poka](https://github.com/Prakash-poka) for the [Python Implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/Python/math/Fibonacci.py) 149 | -------------------------------------------------------------------------------- /docs/mathematics/gcd-of-two-numbers.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: GCD of two Numbers 3 | slug: /mathematics/gcd-of-two-numbers 4 | --- 5 | 6 | ## Introduction 7 | 8 | Greatest Common Divisor(GCD) is the highest number which is the factor of both the numbers. It is also called as Highest Common Factor(HCF). Two numbers are coprime if their GCD is `1`. GCD of two even numbers is always even and odd numbers is always odd. 9 | 10 | ## Explanation 11 | 12 | GCD of two numbers `a` and `b` is denoted by `gcd(a,b)`. GCD of any number with `1` is `1`. GCD of any number with `0` is the same number. 13 | 14 | GCD has following properties: 15 | 16 | ``` 17 | gcd(m⋅a, m⋅b) = m⋅gcd(a, b) 18 | gcd(a + m⋅b, b) = gcd(a, b) 19 | 20 | where m is a non-negative integer 21 | ``` 22 | 23 | Let's have one example: 24 | 25 | ``` 26 | num1 = 6 27 | num2 = 9 28 | mini = 6, it contains minimum of num1 and num2 29 | 30 | Iteration 1: 31 | mini = 6 32 | Both numbers are not divisible by mini, so reduce mini by 1 33 | mini = mini-1 34 | 35 | Iteration 2: 36 | mini = 5 37 | Both numbers are not divisible by mini, so reduce mini by 1 38 | mini = mini-1 39 | 40 | Iteration 3: 41 | mini = 4 42 | Both numbers are not divisible by mini, so reduce mini by 1 43 | mini = mini-1 44 | 45 | Iteration 4: 46 | mini = 3 47 | Both the numbers are divisible by mini, so return mini 48 | ``` 49 | 50 | ## Algorithm 51 | 52 | - Declare a variable `mini` and initialize it to minimum of two numbers. 53 | 54 | - Decrease `mini` by `1` until both the numbers become divisible by it. 55 | 56 | - Return `mini`. 57 | 58 | ## Code 59 | 60 | import Tabs from '@theme/Tabs'; 61 | import TabItem from '@theme/TabItem'; 62 | 63 | 70 | 71 | 72 | ```cpp 73 | #include 74 | using namespace std; 75 | // Function to determine the gcd of two numbers 76 | 77 | int gcd(int a, int b) 78 | { 79 | // Assigning minimum element to mini 80 | 81 | int mini; 82 | if (a <= b) mini = a; 83 | else mini = b; 84 | 85 | while (mini > 1) 86 | { 87 | if (a % mini == 0 && b % mini == 0) 88 | { 89 | break; 90 | } 91 | mini--; 92 | } 93 | return mini; 94 | } 95 | int main() 96 | { 97 | cout << "Enter the First Number: "; 98 | int a; 99 | cin >> a; 100 | 101 | cout << "Enter the Second Number: "; 102 | int b; 103 | cin >> b; 104 | 105 | cout << "GCD of two Numbers is: " << gcd(a, b); 106 | return 0; 107 | } 108 | ``` 109 | 110 | 111 | 112 | 113 | ```python 114 | # Function to determine the gcd of two numbers 115 | 116 | def gcd(a,b): 117 | # Assigning minimum element to mini 118 | 119 | mini = b; 120 | if (a < b): 121 | mini = a 122 | 123 | while (mini > 1): 124 | if (a % mini == 0 and b % mini == 0): 125 | break 126 | mini -= 1 127 | 128 | return mini; 129 | 130 | if __name__ == '__main__': 131 | 132 | a = int(input("Enter the First Number: ")) 133 | b = int(input("Enter the Second Number: ")) 134 | 135 | print("GCD of two Numbers is:",gcd(a,b)) 136 | ``` 137 | 138 | 139 | 140 | 141 | ## Sample Input and Output 142 | 143 | #### Input : 144 | 145 | ``` 146 | Enter the First Number: 5 147 | Enter the Second Number: 15 148 | ``` 149 | 150 | #### Output : 151 | 152 | ``` 153 | GCD of two Numbers is: 5 154 | ``` 155 | 156 | ## Complexity Analysis 157 | 158 | - Time Complexity: `O(n)` 159 | - Space Complexity: `O(1)` 160 | -------------------------------------------------------------------------------- /docs/mathematics/hamming-distance.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Hamming Distance 3 | slug: /mathematics/hamming-distance 4 | --- 5 | 6 | ## Introduction 7 | 8 | The hamming distance is the value difference between the two binary representations of the 32-bit integer. 9 | 10 | ## Explanation 11 | 12 | If we are given two numbers then the hamming distance is the number of positions at which the corresponding symbols differ. 13 | 14 | Let's have one example: 15 | ``` 16 | Input : 17 | num1 = 7(0111) 18 | num2 = 8(1000) 19 | 20 | Output : 4 21 | ``` 22 | 23 | ## Algorithm 24 | 25 | - Take the given two digits as input from the user. 26 | - Compute the binary equivalent of the two decimal numbers. 27 | - Compute the number of positions at which the corresponding binary equivalent numbers differ. 28 | 29 | ## Code 30 | 31 | import Tabs from '@theme/Tabs'; 32 | import TabItem from '@theme/TabItem'; 33 | 34 | 41 | 42 | 43 | ```cpp 44 | #include 45 | using namespace std; 46 | 47 | int solve1(int x, int y) { 48 | 49 | int ans = x^y; 50 | return __builtin_popcount(ans); 51 | } 52 | 53 | int solve2(int x, int y) { 54 | 55 | int count = 0; 56 | for (int i = 0; i < 32; i++) 57 | if ( (x & (1 << i)) != (y & (1 << i)) ) 58 | count++; 59 | return count; 60 | } 61 | 62 | int main(){ 63 | 64 | int x,y; 65 | cout<<"Enter 1st number: "; 66 | cin>>x; 67 | cout<<"Enter 2nd number: "; 68 | cin>>y; 69 | cout<<"Hamming distance between these two numbers is: "< 74 | 75 | 76 | ```py 77 | def hamming_distance(num1, num2): 78 | 79 | #To store value of the differnce 80 | bitdiff = 0 81 | 82 | for i in range(31, -1, -1): 83 | 84 | #right shift for both the numbers for i AND 1 times 85 | binary_num1 = num1>>i&1 86 | binary_num2 = num2>>i&1 87 | 88 | #checking if binary of both are not equal 89 | if binary_num1 != binary_num2: 90 | bitdiff += 1 91 | #i it is equal bitdiff will be same and loop will continue 92 | 93 | return bitdiff 94 | 95 | def main(): 96 | 97 | #User input for a both numbers 98 | num1 = int(input("Enter 1st number: ")) 99 | num2 = int(input("Enter 2nd number: ")) 100 | 101 | #function call for getting hamming distance for the given two numbers. 102 | print("Hamming distance between these two numbers is: ", hamming_distance(num1, num2)) 103 | 104 | if __name__ == "__main__": 105 | main() 106 | ``` 107 | 108 | 109 | 110 | 111 | ## Sample Input and Output 112 | 113 | #### Input: 114 | 115 | ``` 116 | Enter 1st number: 7 117 | Enter 2nd number: 8 118 | ``` 119 | 120 | #### Output: 121 | 122 | ``` 123 | Hamming distance between these two numbers is: 4 124 | ``` 125 | 126 | ## Complexity Analysis 127 | 128 | - Time complexity: `O(n)` 129 | - Space complexity : `O(1)` 130 | 131 | ## Credits 132 | 133 | - [Aakriti Aggarwal](https://github.com/aakriti1318) contributed the [C++ implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/math/Hamming_Distance.cpp) 134 | - [Batul Makada](https://github.com/batul02) contributed the [Python implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/Python/math/Hamming_distance.py) 135 | -------------------------------------------------------------------------------- /docs/mathematics/hexagonal-number.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Hexagonal Number 3 | slug: /mathematics/hexagonal-number 4 | --- 5 | 6 | ## Introduction 7 | 8 | A Hexagonal number is a figurate number. A Figurate number is a number that can be represented by a regular geometrical arrangement of equally spaced points. The `nth` hexagonal number `Hn` refers to the count of distinct dots which can be used to draw the outlines of regular hexagonal pattern such that hexagons are overlaid to share one vertex. We are given a number `n` and we need to print the `nth` hexagonal number. 9 | 10 | ## Explanation 11 | 12 | Every hexagonal number is a triangular number and every odd triangular number is a hexagonal number. For calculating the `nth` hexagonal number just apply the formula given below. The first few hexagonal few hexagonal numbers are `1`, `6`, `15`, `28`, `45`, `66`, `91`, `120`, `153`, `190`. 13 | 14 |

15 | 16 | Formula: 17 | 18 | ``` 19 | nth Hexagonal Number: n * (2 * n - 1) 20 | ``` 21 | 22 | We can test whether a positive integer `x` is a hexagonal number or not by calculating below expression: 23 | 24 | ``` 25 | n = (sqrt(8*x + 1) + 1) / 4 26 | 27 | If n is an integer then x is a hexagonal number 28 | Else x is not a hexagonal number 29 | ``` 30 | 31 | Let's have few examples: 32 | 33 | ``` 34 | n = 1 35 | 1st hexagonal number = 1 36 | 37 | n = 3 38 | 3rd hexagonal number = 15 39 | 40 | n = 6 41 | 6th hexagonal number = 66 42 | ``` 43 | 44 | ## Code 45 | 46 | import Tabs from '@theme/Tabs'; 47 | import TabItem from '@theme/TabItem'; 48 | 49 | 56 | 57 | 58 | ```cpp 59 | #include 60 | using namespace std; 61 | // Function to return nth hexagonal number 62 | 63 | int hexagonal_number(int n) 64 | { 65 | int res = n; 66 | res = res * (2 * n - 1); 67 | return res; 68 | } 69 | 70 | int main() 71 | { 72 | int n; 73 | cout << "Enter the Number: "; 74 | cin >> n; 75 | 76 | cout<<"Hexagonal Number is: "< 82 | 83 | 84 | 85 | ```python 86 | # Function to return nth hexagonal number 87 | 88 | def hexagonal_number(n): 89 | res = n 90 | res = res * (2 * n - 1); 91 | return res 92 | 93 | if __name__ == "__main__": 94 | 95 | n = int(input("Enter the Number: ")) 96 | 97 | print("Hexagonal Number is: ",hexagonal_number(n)) 98 | ``` 99 | 100 | 101 | 102 | 103 | ## Sample Input and Output 104 | 105 | #### Input : 106 | 107 | ``` 108 | Enter the Number: 5 109 | ``` 110 | 111 | #### Output : 112 | 113 | ``` 114 | Hexagonal Number is: 45 115 | ``` 116 | 117 | ## Complexity Analysis 118 | 119 | - Time Complexity: `O(1)` 120 | 121 | - Space Complexity: `O(1)` 122 | -------------------------------------------------------------------------------- /docs/mathematics/lcm-of-two-numbers.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: LCM of two Numbers 3 | slug: /mathematics/lcm-of-two-numbers 4 | --- 5 | 6 | ## Introduction 7 | 8 | Lowest Common Multiple (LCM) is the lowest number which is divisible by both the numbers. It is also called as Least Common Divisor (LCD). LCM of two numbers cannot be less than the greater of them. If smaller number is the factor of greater number then the greater number will be the LCM. 9 | 10 | ## Explanation 11 | 12 | LCM of two numbers `a` and `b` is denoted by `lcm(a,b)`. LCM of any number with `1` will be the number itself. LCM of two coprime numbers is the product of numbers. LCM can be found by Listing Multiples, Prime Factorization, Ladder Method, and Divison Method. 13 | 14 | LCM has the following properties: 15 | ``` 16 | lcm(a,b) = lcm(b,a) 17 | lcm(da, db, dc) = d * lcm(a, b, c), where d is any positive integer 18 | lcm(a, b, c) = lcm(lcm(a, b), c) = lcm(a, lcm(b, c)) 19 | ``` 20 | 21 | Let's have one example: 22 | ``` 23 | num1 = 4 24 | num2 = 6 25 | maxx = 6, it contains maximum of num1 and num2 26 | 27 | Iteration 1: 28 | maxx = 6 29 | maxx is not divisible by both numbers, so increase maxx by 1 30 | maxx = maxx + 1 31 | 32 | Iteration 2: 33 | maxx = 7 34 | maxx is not divisible by both numbers, so increase maxx by 1 35 | maxx = maxx + 1 36 | 37 | Iteration 3: 38 | maxx = 8 39 | maxx is not divisible by both numbers, so increase maxx by 1 40 | maxx = maxx + 1 41 | 42 | Iteration 4: 43 | maxx = 9 44 | maxx is not divisible by both numbers, so increase maxx by 1 45 | maxx = maxx + 1 46 | 47 | Iteration 5: 48 | maxx = 10 49 | maxx is not divisible by both numbers, so increase maxx by 1 50 | maxx = maxx + 1 51 | 52 | Iteration 6: 53 | maxx = 11 54 | maxx is not divisible by both numbers, so increase maxx by 1 55 | maxx = maxx + 1 56 | 57 | Iteration 7: 58 | maxx = 12 59 | maxx is divisible by both the numbers, so this is our LCM 60 | ``` 61 | 62 | ## Algorithm 63 | 64 | - Declare a variable `maxx` and initialize it to maximum of two numbers. 65 | - Increase `maxx` by `1` until it becomes divisible by both the numbers. 66 | - Return `maxx`. 67 | 68 | ## Code 69 | 70 | import Tabs from '@theme/Tabs'; 71 | import TabItem from '@theme/TabItem'; 72 | 73 | 80 | 81 | 82 | ```cpp 83 | #include 84 | using namespace std; 85 | // Function to determine the lcm of two numbers 86 | 87 | int lcm(int a, int b) 88 | { 89 | // Assigning maximum element to maxx 90 | 91 | int maxx; 92 | if (a <= b) maxx = b; 93 | else maxx = a; 94 | 95 | while (true) 96 | { 97 | if (maxx % a == 0 && maxx % b == 0) 98 | { 99 | break; 100 | } 101 | maxx++; 102 | } 103 | return maxx; 104 | } 105 | 106 | int main() 107 | { 108 | cout << "Enter the First Number: "; 109 | int a; 110 | cin >> a; 111 | cout << "Enter the Second Number: "; 112 | int b; 113 | cin >> b; 114 | 115 | cout << "LCM of two Numbers is: " << lcm(a, b); 116 | return 0; 117 | } 118 | ``` 119 | 120 | 121 | 122 | 123 | ```python 124 | # Function to determine the lcm of two numbers 125 | 126 | def lcm(a, b): 127 | # Assigning maximum element to maxx 128 | 129 | if a <= b: 130 | maxx = b 131 | else: 132 | maxx = a 133 | while True: 134 | if maxx % a == 0 and maxx % b == 0: 135 | break 136 | maxx += 1 137 | return maxx 138 | 139 | 140 | if __name__ == "__main__": 141 | 142 | a = int(input("Enter the First Number: ")) 143 | b = int(input("Enter the Second Number: ")) 144 | 145 | print("LCM of two Numbers is:", lcm(a, b)) 146 | ``` 147 | 148 | 149 | 150 | 151 | ## Sample Input and Output 152 | 153 | #### Input : 154 | 155 | ``` 156 | Enter the First Number: 5 157 | Enter the Second Number: 15 158 | ``` 159 | #### Output : 160 | 161 | ``` 162 | LCM of two Numbers is: 15 163 | ``` 164 | 165 | ## Complexity Analysis 166 | 167 | - Time Complexity: `O(n)` 168 | - Space Complexity: `O(1)` 169 | -------------------------------------------------------------------------------- /docs/mathematics/mathematics.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Mathematics 3 | slug: /mathematics 4 | --- 5 | 6 | This page would serve our needs for documentation of Mathematical Algorithms. 7 | -------------------------------------------------------------------------------- /docs/mathematics/next-permutation.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Next Permutation 3 | slug: /mathematics/next-permutation 4 | --- 5 | 6 | ## Introduction 7 | 8 | Implementation of next permutation, it rearranges numbers into the lexicographically next greater permutation of numbers.If such an arrangement is not possible, it must rearrange it as the lowest possible order (sorted in ascending order). 9 | 10 | ## Explanation 11 | We need to find the next lexicographic permutation of the given list of numbers than the number formed by the given array and Our approach would be inplace. 12 | 13 | 14 | 15 | Let's have few examples: 16 | ``` 17 | Input: nums = [1,2,3] 18 | Output: [1,3,2] 19 | 20 | 21 | Input: nums = [3,2,1] 22 | Output: [1,2,3] 23 | 24 | 25 | Input: nums = [1] 26 | Output: [1] 27 | 28 | ``` 29 | 30 | ## Algorithm 31 | 32 | * We will find length of array and store it in `length` variable. 33 | * We will check a base condition if the `length` is less than or equal to 2 simply return `reverse` of array ( as that's the next permutation). 34 | * Now, Let's keep a pointer at `length - 2` position of array and call it `pointer`. 35 | * Now, we will iterate with conditions `pointer >=0` and Element at that index must be graeter than or equal to Element at next index simply `array[pointer] >= array[pointer + 1]` , Here we will be decrementing pointer as `pointer = pointer -1` (ensures us that we are moving backwards over the array) 36 | * Now, Over that process once the `pointer` is equal to `-1` then it simply means we have to return `array.reverse()` 37 | * If it is not yet equal to `-1' then we iterate over the range of `length - 1, pointer` with incrementer as `-1` and variable as `number`. 38 | * Inside the loop we check condition if `array[pointer] < array[number]` is `True` then swap `array[pointer]` with `array[number]` and `break` after that is done. 39 | * Finally we index over our array from `pointer + 1` till `end` of array and simply reverse is using `reversed` function. 40 | * Now, we'd simply return the modified array as our answer. 41 | 42 | ## Code 43 | 44 | import Tabs from '@theme/Tabs'; 45 | import TabItem from '@theme/TabItem'; 46 | 47 | 53 | 54 | 55 | 56 | ```python 57 | 58 | 59 | # Function for next Permutation 60 | def nextPermutation(array): 61 | 62 | 63 | length = len(array) 64 | 65 | if length <= 2: 66 | return array.reverse() 67 | pointer = length - 2 68 | 69 | while pointer >= 0 and array[pointer] >= array[pointer + 1]: 70 | pointer -= 1 71 | 72 | if pointer == -1: 73 | return array.reverse() 74 | 75 | for number in range(length - 1, pointer, -1): 76 | if array[pointer] < array[number]: 77 | array[pointer], array[number] = array[number], array[pointer] 78 | break 79 | 80 | array[pointer + 1:] = reversed(array[pointer + 1:]) 81 | 82 | return array 83 | 84 | 85 | if __name__ == "__main__": 86 | #User input for both the strings 87 | print('Enter values of the array') 88 | array = list(map(int, input().rstrip().split())) 89 | print('Next Permutation is: ',nextPermutation(array)) 90 | 91 | ``` 92 | 93 | 94 | 95 | 96 | ## Sample Input and Output 97 | 98 | #### Input : 99 | ``` 100 | Enter values into array: 1 1 5 101 | ``` 102 | #### Output : 103 | ``` 104 | Next Permutation is : [1,5,1] 105 | ``` 106 | 107 | ## Complexity Analysis 108 | 109 | `n` is the given number. 110 | 111 | - Time Complexity: 112 | 113 | - **Best Case**: `O(n)` 114 | - **Average Case**: `O(n)` 115 | - **Worst Case**: `O(n)` 116 | 117 | - Space Complexity: `O(1)` 118 | -------------------------------------------------------------------------------- /docs/mathematics/next-prime-number.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Next Prime Number 3 | slug: /mathematics/next-prime-number 4 | --- 5 | 6 | ## Introduction 7 | 8 | The next prime number _p_ of a number _n_ is a number such that 9 | - _p_ is greater than _n_. 10 | - _p_ is a prime number. 11 | - There are no prime numbers between _n_ and _p_. 12 | 13 | ## Explanation 14 | 15 | Let's have one example: 16 | ``` 17 | Let n = 13, then the numbers after 13 are 14, 15, 16, 17 and so on. 18 | Here 14, 15 and 16 are composite numbers. Hence, the next prime number is 17 which is 19 | - Greater than 13. 20 | - Is a prime number. 21 | - And there are no prime numbers between 13 and 17. 22 | 23 | ``` 24 | 25 | ## Algorithm 26 | 27 | - Start with a number greater than _n_ i.e. `p = n+1`. 28 | - Take `flag == false` initially and consider that _p_ is not a composite number. 29 | - Now, in each iteration check if _p_ is composite or not. 30 | - If it is, i.e. we found a factor for _p_ other than _1_ and _p_, then just set `flag == true`, increment p by 1 and break the loop. 31 | - If `flag == false`, it means that _p_ has only two factors _1_ and _p_, i.e. _p_ is prime hence return it. 32 | 33 | 34 | ## Code 35 | 36 | import Tabs from '@theme/Tabs'; 37 | import TabItem from '@theme/TabItem'; 38 | 39 | 46 | 47 | 48 | ```cpp 49 | #include 50 | using namespace std; 51 | 52 | int next_prime(int n){ 53 | int p = n + 1; 54 | if(p<=1){ 55 | return 2; 56 | } 57 | while(true){ 58 | //consider that p is not a composite number 59 | bool flag = false; 60 | for(int i=2; i<=floor(n/2)+1; i++){ 61 | //found a factor other than 1 or p 62 | if(p%i==0){ 63 | p = p + 1; 64 | //p is composite 65 | flag = true; 66 | break; 67 | } 68 | } 69 | //p is prime 70 | if(flag==false){ 71 | return p; 72 | } 73 | } 74 | } 75 | 76 | int main(){ 77 | int n; 78 | cout<<"Enter a number : "; 79 | cin>>n; 80 | cout<<"Next prime number is "< 85 | 86 | 87 | ```py 88 | def next_prime(n): 89 | # looping from next number to find if it prime or not 90 | p = n+1 91 | while True: 92 | flag = False 93 | # checking whether p is divisible by numbers from 2 to it's half 94 | for y in range(2,p//2+1): 95 | if p%y==0: 96 | p+=1 97 | flag = True 98 | break 99 | if flag==False: 100 | return(p) 101 | 102 | n = int(input("Enter a number : ")) 103 | print('Next prime number is ', next_prime(n)) 104 | ``` 105 | 106 | 107 | 108 | 109 | ## Sample Input and Output 110 | 111 | #### Input 112 | 113 | ``` 114 | Enter a number : 23 115 | ``` 116 | 117 | #### Output 118 | 119 | ``` 120 | Next prime number is 29 121 | ``` 122 | 123 | ## Complexity Analysis 124 | 125 | - Time complexity : `O(n^2)` 126 | - Space complexity : `O(1)` 127 | 128 | ## Credits 129 | 130 | - [Tanvi Bugdani](https://github.com/tanvi355) contributed the [C++ implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/math/next_prime_number.cpp) 131 | - [Tarun Kamboj](https://github.com/Tarun-Kamboj) contributed the [Python implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/Python/math/Next_Prime_Number.py) 132 | -------------------------------------------------------------------------------- /docs/mathematics/occurrence-of-no.-in-array.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Occurence of a number in array 3 | slug: /mathematics/occurrence-of-no.-in-array 4 | --- 5 | 6 | ## Introduction 7 | 8 | In this article, we will see how to count the occurrence of a number in a given set of data. Occurrence or frequency means how many times a number is present in a given set of data. 9 | 10 | ## Explanation 11 | 12 | In this, we have to count the number of times a given element is present in an array that means if an element is present 4 times in the array then we have to print 4. If element is not present then it prints zero. 13 | 14 | #### Example 1 15 | 16 | 17 | 18 | ``` 19 | Given arr[8]= | 2 | 4 | 3 | 2 | 4 | 5 | 2 | 3 | 20 | Given number: 3 21 | So we iterate on whole array 22 | And increase the count if current number is equal to 3 23 | So after traversing the whole array it prints the count=2 24 | That means 3 is present 2 times 25 | If number is not present then it returns zero. 26 | ``` 27 | ## Algorithm 28 | 29 | For counting occurrence of an element in array, we follow the following algorithm: 30 | 31 | * First, we initialize a count variable with 0. 32 | 33 | * Iterate on whole array and increase the count by 1 when our current element is equal to given element. 34 | 35 | * If element is not present print Invalid. 36 | 37 | * Otherwise display the value of count. 38 | 39 | ## Code 40 | 41 | import Tabs from '@theme/Tabs'; 42 | import TabItem from '@theme/TabItem'; 43 | 44 | 51 | 52 | 53 | ```cpp 54 | #include 55 | using namespace std; 56 | 57 | //function for counting occurrence 58 | int count_occurrence(int x,int a[],int n) 59 | { 60 | //initialize count with 0 61 | int count=0; 62 | 63 | //iterating on whole array 64 | for(int i=0;i>n; 82 | int a[n]; 83 | cout<<"Enter the elements of array: "; 84 | 85 | //Taking elements of array 86 | for(int i=0;i>a[i]; 89 | } 90 | int x; 91 | cout<<"Enter the no. of which you want to count the occurrence: "; 92 | cin>>x; 93 | //Printing occurrence of given number 94 | cout< 100 | 101 | 102 | 103 | ```python 104 | def countOccurrences(arr, n, x): 105 | res = 0 106 | for i in range(n-1): 107 | if x == arr[i]: 108 | res += 1 109 | return res 110 | 111 | # Taking size as input 112 | n = int(input("Enter the size of array: ")) 113 | data = [] 114 | 115 | # Taking array element as input 116 | d = int(input("Enter the elements of array: ")) 117 | for i in range(n-1): 118 | data.append(int(input())) 119 | x = int(input("Enter the no. of which you want to print the occurrence: ")) 120 | 121 | #Printing the occurrence of given number 122 | print(countOccurrences(data,n,x)) 123 | 124 | 125 | ``` 126 | 127 | 128 | 129 | ## Sample Input and Output 130 | 131 | #### Input : 132 | 133 | ``` 134 | Enter the size of array: 8 135 | Enter the elements of array: 2 4 3 2 4 5 2 3 136 | Enter the no. of which you want to print the occurrence: 3 137 | 138 | ``` 139 | #### Output : 140 | 141 | ``` 142 | 2 143 | ``` 144 | 145 | ## Complexity Analysis 146 | 147 | - Time Complexity: `O(n)` 148 | 149 | where `n` is the number of elements. 150 | 151 | - Space Complexity: `O(1)` 152 | 153 | 154 | -------------------------------------------------------------------------------- /docs/mathematics/palindrome-number.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Palindrome Number 3 | slug: /mathematics/palindrome-number 4 | --- 5 | 6 | ## Introduction 7 | 8 | A number whose digits when reversed form the same original number then such a number is said to be a palindromic number. The term palindromic is derived from palindrome, which refers to a word (such as rotor or racecar) whose spelling is unchanged when its letters are reversed. 9 | 10 | ## Explanation 11 | 12 | A number `pqr` is said to be palindrome, if and only if it's reverse is also `pqr`. This means the reverse of `pqr` is `rqp` which must be equal to it's original number `pqr`. 13 | 14 | ### Quick Example : 15 | 16 | * Consider a number `17371`. If this is reversed then again we get `17371` which is same as the original number. Hence `17371` is a palindrome number. 17 | 18 | * Consider a number `1243`. If this is reversed then we get `3421` which is not same as the original number. Hence `1243` is not a palindrome number. 19 | 20 | **Note:** All **single digit** integers are palindrome numbers. 21 | 22 | Some palindrome numbers are: ```0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, .....``` 23 | 24 | ## Algorithm 25 | 26 | - Input the number `num`. 27 | - Store the number in a temporary variable. 28 | - Reverse the number `num`. 29 | - Check if the reversed number is equal to original number `num`. 30 | 31 | ## Code 32 | import Tabs from '@theme/Tabs'; 33 | import TabItem from '@theme/TabItem'; 34 | 35 | 42 | 43 | 44 | ```c 45 | // C++ program to check if a number is a palindrome or not 46 | #include 47 | using namespace std; 48 | 49 | int main() 50 | { 51 | int num, temp, rev = 0; 52 | cout << "Enter the number: "; 53 | cin >> num; 54 | temp = num; 55 | /*To check if a number is palindrome, we reverse the number 56 | and then compare it with the given number */ 57 | while (temp) 58 | { 59 | int rem = temp % 10; 60 | rev = rev * 10 + rem; 61 | temp = temp / 10; 62 | } 63 | if (rev == num) 64 | { 65 | cout << num << " is a Palindrome number."; 66 | } 67 | else 68 | { 69 | cout << num << " is not a Palindrome number."; 70 | } 71 | return 0; 72 | } 73 | ``` 74 | 75 | 76 | 77 | 78 | ```java 79 | // Checking Palindrome number with Recursion 80 | import java.io.*; 81 | import java.util.*; 82 | class PalindromeRecursion { 83 | //stored reversed number 84 | static long revNum = 0; 85 | public static long palindrome(long i) { 86 | if (i > 0) //base class 87 | { 88 | revNum = (revNum * 10) + (i % 10); 89 | palindrome(i / 10); 90 | } else 91 | return revNum; 92 | return revNum; 93 | } 94 | public static void main(String args[]) { 95 | Scanner sc = new Scanner(System.in); 96 | System.out.print("Enter the number: "); 97 | long n = sc.nextLong(); 98 | if (n == palindrome(n)) 99 | System.out.println(n + " is a Palindrome number."); 100 | else 101 | System.out.println(n + " is not a Palindrome number."); 102 | } 103 | } 104 | ``` 105 | 106 | 107 | 108 | ## Sample Input and Output 109 | #### Input : 110 | ``` 111 | Enter the number: 121 112 | ``` 113 | 114 | #### Output : 115 | ``` 116 | 121 is a Palindrome Number. 117 | ``` 118 | #### Input : 119 | ``` 120 | Enter a number: 14 121 | ``` 122 | #### Output : 123 | ``` 124 | 14 is not a Palindrome Number. 125 | ``` 126 | ## Complexity Analysis 127 | - Time Complexity: `O(n)` 128 | - Space Complexity: `O(1)` 129 | 130 | ## Credits 131 | 132 | - [Hari Krishnan U](https://github.com/Harikrishnan6336) for the [C++ implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/math/check_palindrome.cpp) 133 | - [Rajiv Singh](https://github.com/iamrajiv) for the [Java implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/Java/math/PalindromeRecursion.java) 134 | -------------------------------------------------------------------------------- /docs/mathematics/pascal-triangle.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Pascal Triangle 3 | slug: /mathematics/pascal-triangle 4 | --- 5 | 6 | ## Introduction 7 | 8 | Pascal Triangle refers to the triangle which consists of binomial coefficients. It was named after the French mathematician Blaise Pascal. The first line of the pascal triangle has only one element, the second has two elements, and this keeps on increasing by `1` as we proceed to the nth line. We need to take an integer `n` as input and print the first `n` lines of the pascal triangle. 9 | 10 | ## Explanation 11 | 12 | Starting and Ending element of every line of the pascal triangle is `1`. We just need to run two loops and print every element using the formula given below. 13 | 14 |

15 | 16 | The value of `jth` entry in `ith` line is: 17 | ``` 18 | C(i, j) = i! / ( (i-j)! * j! ), ways to select j objects from the set of i objects 19 | ``` 20 | 21 | Let's have one example: 22 | ``` 23 | n = 3 24 | 25 | 1st row 26 | C(0 ,0) = 1, first element 27 | 28 | 2nd row 29 | C(1 ,0) = 1, first element 30 | C(1 ,1) = 1, second element 31 | 32 | 3rd row 33 | C(2 ,0) = 1, first element 34 | C(2 ,1) = 2, second element 35 | C(2 ,2) = 1, third element 36 | ``` 37 | 38 | ## Algorithm 39 | 40 | - Iterate `i` from `0 to n-1`. 41 | 42 | - For each iteration of `i`, iterate `j` from `0 to i` and print `C(i,j)`. 43 | 44 | ## Code 45 | 46 | import Tabs from '@theme/Tabs'; 47 | import TabItem from '@theme/TabItem'; 48 | 49 | 56 | 57 | 58 | ```cpp 59 | #include 60 | using namespace std; 61 | // Function to print pascal triangle 62 | 63 | int pascal(int n) 64 | { 65 | int i = 0; 66 | while (i < n) 67 | { 68 | int j = 0; 69 | while (j <= i) 70 | { 71 | // Calculating C(i,j) = i!/((i-j)!*j!) 72 | 73 | int res = 1; 74 | int k = 1; 75 | while (k <= i) 76 | { 77 | res = res * k; 78 | k++; 79 | } 80 | k = 1; 81 | while (k <= (i - j)) 82 | { 83 | res = res / k; 84 | k++; 85 | } 86 | k = 1; 87 | while (k <= j) 88 | { 89 | res = res / k; 90 | k++; 91 | } 92 | if (res != 0) cout << res << " "; 93 | j++; 94 | } 95 | cout << endl; 96 | i++; 97 | } 98 | } 99 | 100 | int main() 101 | { 102 | int n; 103 | cout << "Enter the Number of rows: "; 104 | cin >> n; 105 | 106 | pascal(n); 107 | return 0; 108 | } 109 | ``` 110 | 111 | 112 | 113 | 114 | ```python 115 | # Function to print pascal triangle 116 | 117 | def pascal(n): 118 | i = 0 119 | while i < n: 120 | j = 0 121 | while j <= i: 122 | # Calculating C(i,j) = i!/((i-j)!*j!) 123 | 124 | res = 1 125 | k = 1 126 | while k <= i: 127 | res = res * k 128 | k += 1 129 | 130 | k = 1 131 | while k <= (i - j): 132 | res = res // k 133 | k += 1 134 | 135 | k = 1 136 | while k <= j: 137 | res = res // k 138 | k += 1 139 | 140 | if res != 0: 141 | print(res, end=" ") 142 | j += 1 143 | 144 | print("") 145 | i += 1 146 | 147 | if __name__ == "__main__": 148 | n = int(input("Enter the Number of rows: ")) 149 | 150 | pascal(n) 151 | ``` 152 | 153 | 154 | 155 | 156 | ## Sample Input and Output 157 | 158 | #### Input : 159 | 160 | ``` 161 | Enter the Number of rows: 3 162 | ``` 163 | 164 | #### Output : 165 | 166 | ``` 167 | 1 168 | 1 1 169 | 1 2 1 170 | ``` 171 | 172 | ## Complexity Analysis 173 | 174 | - Time Complexity: `O(n^3)` 175 | 176 | - Space Complexity: `O(1)` 177 | -------------------------------------------------------------------------------- /docs/mathematics/power-linear.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Power in Linear Time 3 | slug: /mathematics/power-linear 4 | --- 5 | 6 | ## Introduction 7 | 8 | Power Function calculates `a` raise to the power of `b`. Here `a` is called a Base and `b` is called an exponent. Both `C++` and `Python` provides built-in power function. In this article, we will see the implementation of power function in linear time complexity. 9 | 10 | ## Explanation 11 | 12 | Power of two numbers is calculated by multiplying the base by itself, exponent times. `a` raise to the power `b` is denoted by `pow(a,b)`. The Power of an even number is always even and odd is always odd. Any number raised to power `0` is always `1`. 13 | 14 | Formula: 15 | ``` 16 | pow(a,b) = a*a*a*a*a....b times 17 | ``` 18 | 19 | Properties of Power: 20 | ``` 21 | pow(a,b) = pow(|a|,b), if a is negative and b is even 22 | pow(a,b) = -pow(|a|,b), if a is negative and b is odd 23 | pow(a,0) = 1 24 | pow(a,b) * pow(a,c) = pow(a,b+c) 25 | pow(a,b) / pow(a,c) = pow(a,b-c) 26 | ``` 27 | 28 | Let's have few examples: 29 | ``` 30 | pow(2,3) 31 | res = 2 * 2 * 2 = 8 32 | 33 | pow(3,2) 34 | res = 3 * 3 = 9 35 | ``` 36 | 37 | ## Algorithm 38 | 39 | - Declare a variable `res` and initialize it to `1`. 40 | 41 | - Multiply `res` with base, exponent times. 42 | 43 | - Return `res`. 44 | 45 | ## Code 46 | 47 | import Tabs from '@theme/Tabs'; 48 | import TabItem from '@theme/TabItem'; 49 | 50 | 57 | 58 | 59 | ```cpp 60 | #include 61 | using namespace std; 62 | // Function to get power(a^b) in linear time 63 | 64 | int power(int a, int b) 65 | { 66 | int res = 1; 67 | // if exponent is 0 68 | 69 | if (b == 0) return 1; 70 | do 71 | { 72 | res = res * a; 73 | b--; 74 | } while (b > 0); 75 | return res; 76 | } 77 | 78 | int main() 79 | { 80 | cout << "Enter the Base: "; 81 | int a; 82 | cin >> a; 83 | 84 | cout << "Enter the Exponent: "; 85 | int b; 86 | cin >> b; 87 | 88 | cout << "Power is: " << power(a, b); 89 | return 0; 90 | } 91 | ``` 92 | 93 | 94 | 95 | 96 | ```python 97 | # Function to get power(a^b) in linear time 98 | 99 | def power(a, b): 100 | res = 1 101 | # if exponent is 0 102 | 103 | if b == 0: 104 | return 1 105 | while b > 0: 106 | res *= a 107 | b -= 1 108 | return res 109 | 110 | if __name__ == '__main__': 111 | 112 | a = int(input('Enter the Base: ')) 113 | b = int(input('Enter the Exponent: ')) 114 | 115 | print ('Power is:', power(a, b)) 116 | ``` 117 | 118 | 119 | 120 | 121 | ## Sample Input and Output 122 | 123 | #### Input : 124 | 125 | ``` 126 | Enter the Base: 2 127 | Enter the Exponent: 3 128 | ``` 129 | 130 | #### Output : 131 | 132 | ``` 133 | Power is: 8 134 | ``` 135 | 136 | ## Complexity Analysis 137 | 138 | - Time Complexity: `O(b)`, where`b` is the exponent 139 | 140 | - Space Complexity: `O(1)` -------------------------------------------------------------------------------- /docs/mathematics/prime-number.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Prime Number 3 | slug: /mathematics/prime-number 4 | --- 5 | 6 | ## Introduction 7 | 8 | Prime numbers are the positive integers having only two factors, 1 and the integer itself. 9 | 10 | If `p` is a prime, then it’s only factors are necessarily `1` and `p` itself. A number which does not follow this and have more than two factors or which can be factored by other numbers are called composite numbers. 11 | 12 | ### Quick Example : 13 | 14 | The first ten primes are: `2`, `3`, `5`, `7`, `11`, `13`, `17`, `19`, `23`, `29`. 15 | 16 | Here `2` is prime as it's factors are `1` and `2` itself. Similarly `3` and `5` are prime as their factors are `1` and `3` and `1` and `5` respectively. 17 | It should be noted that `1` is a non-prime number. 18 | 19 | ## Algorithm 20 | 21 | - Input the number `num`. 22 | - Initialize `Flag` to 1. 23 | - Check the number of factors of `num`. If factor is found then `Flag` is 0. 24 | - Check the condition: if `Flag` is 1 then `num` is `prime` else `num` is `not prime`. 25 | 26 | ## Code 27 | import Tabs from '@theme/Tabs'; 28 | import TabItem from '@theme/TabItem'; 29 | 30 | 37 | 38 | 39 | ```c 40 | #include 41 | #include 42 | // Function to check whether the Number is Prime Number or Not. 43 | int is_prime(int num) { 44 | int Flag = 1; 45 | for (int i = 2; i <= sqrt(num); i++) { 46 | if (num % i == 0) { 47 | Flag = 0; 48 | break; 49 | } 50 | } 51 | if (Flag == 1) 52 | return 1; 53 | else 54 | return 0; 55 | } 56 | int main() { 57 | printf("Enter the number: "); 58 | int num; 59 | scanf("%d", & num); 60 | if (is_prime(num) == 1) 61 | printf("%d is a Prime Number.", num); 62 | else 63 | printf("%d is not a Prime Number.", num);; 64 | return 0; 65 | } 66 | ``` 67 | 68 | 69 | 70 | 71 | ```java 72 | import java.io.*; 73 | import java.util.*; 74 | public class Primenumber { 75 | static boolean isPrime(int num) { 76 | int Flag = 1; 77 | for (int i = 2; i < Math.sqrt(num); i++) { 78 | if (num % i == 0) { 79 | Flag = 0; 80 | break; 81 | } 82 | } 83 | if (Flag == 1) 84 | return true; 85 | else 86 | return false; 87 | } 88 | public static void main(String[] args) { 89 | Scanner sc = new Scanner(System.in); 90 | System.out.print("Enter the number: "); 91 | int num = sc.nextInt(); 92 | if (isPrime(num)) 93 | System.out.println(num + " is a Prime Number."); 94 | else 95 | System.out.println(num + " is not a Prime Number."); 96 | } 97 | } 98 | ``` 99 | 100 | 101 | 102 | ## Sample Input and Output 103 | #### Input : 104 | ``` 105 | Enter the number: 23 106 | ``` 107 | 108 | #### Output : 109 | ``` 110 | 23 is a Prime Number. 111 | ``` 112 | #### Input : 113 | ``` 114 | Enter a number: 14 115 | ``` 116 | #### Output : 117 | ``` 118 | 14 is not a Prime Number. 119 | ``` 120 | ## Complexity Analysis 121 | - Time Complexity: `O(n)` 122 | - Space Complexity: `O(1)` 123 | 124 | -------------------------------------------------------------------------------- /docs/mathematics/product-of-count-of-bits-of-each-elements.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Product of count of bits of each element in array 3 | slug: /mathematics/product-of-count-of-bits-of-each-elements 4 | --- 5 | 6 | ## Introduction 7 | 8 | In this article, we will see how to calculate the product of the count of bits of each element present in the array. 9 | 10 | ## Explanation 11 | 12 | In this, we are given an array. We have to calculate the product of bits of each element present in the array so first, we have to calculate the number of bits in each element then simply multiply them. 13 | 14 | #### Example : 15 | 16 | ``` 17 | Given array a[5]: { 3, 2, 4, 1, 5 } 18 | Binary representation of 3 : 11 19 | So no. of bits in 3 : 2 20 | 21 | Binary representation of 2 : 10 22 | So no. of bits in 2 : 2 23 | 24 | Binary representation of 4 : 100 25 | So no. of bits in 4 : 3 26 | 27 | Binary representation of 1 : 1 28 | So no. of bits in 1 : 1 29 | 30 | Binary representation of 5 : 101 31 | So no. of bits in 5 : 3 32 | 33 | Product of all bits of each element : 2*2*3*1*3=36 34 | 35 | ``` 36 | ## Algorithm 37 | 38 | For calculating product of count of bits of each element in array, we follow the following algorithm: 39 | 40 | * First, we will calculate the number of bits in binary representation of each element. 41 | 42 | * Initialize product variable with 1 and keep multiply count of bits of each element. 43 | 44 | * Print the value of product. 45 | 46 | ## Code 47 | 48 | import Tabs from '@theme/Tabs'; 49 | import TabItem from '@theme/TabItem'; 50 | 51 | 58 | 59 | 60 | ```cpp 61 | #include 62 | using namespace std; 63 | 64 | //function countbits for calculating no. of bits in a number 65 | int countbits(int n) 66 | { 67 | int count=0; 68 | 69 | //for counting bits count++ until n is equal to zero 70 | while(n!=0) 71 | { 72 | count++; 73 | n=n/2; 74 | } 75 | 76 | //after calculating count return 77 | return count; 78 | } 79 | 80 | // main function 81 | int main() 82 | { 83 | int n; 84 | cout<<"Enter the size of array: "; 85 | cin>>n; 86 | int a[n]; 87 | cout<<"Enter the elements of array: "; 88 | 89 | //input array 90 | for(int i=0;i>a[i]; 93 | } 94 | 95 | //initialize product with 1 96 | int product=1; 97 | 98 | //for loop for calculating bits of all elements in array 99 | for(int i=0;i 114 | 115 | 116 | 117 | ```python 118 | # function count_bits for counting number of bits in binary representation 119 | def count_bits(n): 120 | 121 | # initialize count with 0 122 | count=0 123 | while(n!=0): 124 | count+=1 125 | n=n//2 126 | 127 | return count 128 | 129 | # Taking size as input 130 | n = int(input("Enter the size of array: ")) 131 | 132 | # Taking elements of array as input 133 | print("Enter the elements of array: ") 134 | data=[] 135 | for i in range(n): 136 | data.append(int(input())) 137 | 138 | # Initializing product variable with 1 139 | product=1 140 | 141 | # loop for calculating bits of each element present in array 142 | for i in range(n): 143 | bits=0 144 | # calling count_bits function 145 | bits=count_bits(data[i]); 146 | product*=bits; 147 | 148 | # Printing the value of product 149 | print(product) 150 | 151 | ``` 152 | 153 | 154 | 155 | ## Sample Input and Output 156 | 157 | #### Input : 158 | 159 | ``` 160 | Enter the size of array: 5 161 | Enter the elements of array: 3 2 4 1 5 162 | 163 | ``` 164 | #### Output : 165 | 166 | ``` 167 | 36 168 | ``` 169 | 170 | ## Complexity Analysis 171 | 172 | - **Time Complexity:** `O(nlogn)` 173 | 174 | - **Space Complexity:** `O(1)` 175 | 176 | where `n` is the number of elements. 177 | -------------------------------------------------------------------------------- /docs/mathematics/reverse-a-number.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Reverse a Number 3 | slug: /mathematics/reverse-a-number 4 | --- 5 | 6 | ## Introduction 7 | 8 | The reverse of a number is a number that is obtained when a number is traversed from right to left. The reverse of a number can be greater, smaller, or equal to the number. A number that is equal to its reverse is called a Palindrome. The algorithm for finding reverse can be extended to check whether the given number is palindrome or not. 9 | 10 | ## Explanation 11 | 12 | We will make a `reverse` variable. Then we will keep on extracting the least significant digit from the number and push it to the reverse variable till the number becomes `0`. The reverse of the number `pqr` will be `rqp`. The reverse of single digit number `p` will be equal same number `p`. Single-digit numbers are always palindromes. 13 | 14 | Let's have one example: 15 | ``` 16 | num=4568 17 | rev=0 18 | 19 | Iteration 1: 20 | rev = rev*10 + num%10 = 8 21 | num = num/10 = 456 22 | 23 | Iteration 2: 24 | rev = rev*10 + num%10 = 86 25 | num = num/10 = 45 26 | 27 | Iteration 3: 28 | rev = rev*10 + num%10 = 865 29 | num = num/10 = 4 30 | 31 | Iteration 4: 32 | rev = rev*10 + num%10 = 8654 33 | num = num/10 = 0 34 | ``` 35 | 36 | ## Algorithm 37 | 38 | * Make a `rev` variable and initialize it to `0`. 39 | 40 | * Divide the number by `10` and store it into `temp`. 41 | 42 | * Multiply the `rev` variable by `10` and add `temp` to it. 43 | 44 | * Apply the previous two steps until the number becomes `0`. 45 | 46 | ## Code 47 | 48 | import Tabs from '@theme/Tabs'; 49 | import TabItem from '@theme/TabItem'; 50 | 51 | 58 | 59 | 60 | ```cpp 61 | #include 62 | using namespace std; 63 | 64 | //Function to do reverse 65 | 66 | int reverse(int num) { 67 | 68 | //Initializing rev as 0 69 | 70 | int rev = 0; 71 | do { 72 | 73 | //Adding the last digit 74 | 75 | rev = rev * 10 + num % 10; 76 | 77 | //Removing the last digit 78 | 79 | num = num / 10; 80 | } while (num > 0); 81 | 82 | return rev; 83 | } 84 | 85 | int main() { 86 | int num; 87 | 88 | //Taking Input 89 | 90 | cout << "Enter the number: "; 91 | cin >> num; 92 | 93 | //Printing Output 94 | 95 | cout << "The reverse of the given number is: " << reverse(num); 96 | return 0; 97 | } 98 | ``` 99 | 100 | 101 | 102 | 103 | ```python 104 | #Function to do reverse 105 | 106 | def reverse(n): 107 | 108 | #Initializing rev as 0 109 | 110 | rev = 0 111 | while True: 112 | if n == 0: 113 | break 114 | 115 | #Adding the last digit 116 | 117 | rev = rev * 10 + n % 10 118 | 119 | #Removing the last digit 120 | 121 | n = n // 10 122 | return rev 123 | 124 | #Taking input from user 125 | 126 | n = int(input('Enter the number :')) 127 | 128 | #Printing the output 129 | 130 | print ("The reverse of the given number is: {} ".format(reverse(n))) 131 | ``` 132 | 133 | 134 | 135 | 136 | ## Sample Input and Output 137 | 138 | #### Input : 139 | 140 | ``` 141 | Enter the number: 1234 142 | ``` 143 | #### Output : 144 | ``` 145 | The reverse of the given number is: 4321 146 | ``` 147 | 148 | ## Complexity Analysis 149 | 150 | `n` is the number of digits in the number. 151 | 152 | - Time Complexity: 153 | 154 | - **Best Case**: `O(n)` 155 | - **Average Case**: `O(n)` 156 | - **Worst Case**: `O(n)` 157 | 158 | - Space Complexity: `O(1)` 159 | 160 | ## Credits -------------------------------------------------------------------------------- /docs/mathematics/row-with-max-one.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Row with Max 1's 3 | slug: /mathematics/row-with-max-one 4 | --- 5 | 6 | ## Introduction 7 | 8 | We are given a matrix of size `N*M` which only contains `0` and `1`. Each row of the matrix is sorted. We have to find the row with the highest number of `1`. If two rows are having the same number of `1` then return the row which is having a minimum index. 9 | 10 | ## Explanation 11 | 12 | We can do it by traversing each row of the matrix and keeping the count of maximum `1`, but this method is time-consuming. Its time complexity is `O(Row*Column)`. We will see another approach to find the row with maximum `1` in time complexity `O(Row+Column)`. 13 | 14 | Let's have few examples: 15 | ``` 16 | Input 1: 17 | 1 1 18 | 1 1 19 | 20 | Output 1: 21 | Row with max 1's: 0 22 | 23 | Input 2: 24 | 0 0 0 25 | 1 1 1 26 | 27 | Output 2: 28 | Row with max 1's: 1 29 | ``` 30 | 31 | ## Algorithm 32 | 33 | - Initialize `i to 0`, `j to M-1`, `row_no to -1`. 34 | - While `i` is less than `n` and `j` is greater than equal to `0` 35 | - If `matrix[i][j]` is equal to `1` 36 | - Change `row_no` to `i` 37 | - Decrease `j` by 1. 38 | - Else 39 | - Increase `i` by 1. 40 | - Return `row_no`. 41 | 42 | ## Code 43 | 44 | import Tabs from '@theme/Tabs'; 45 | import TabItem from '@theme/TabItem'; 46 | 47 | 54 | 55 | 56 | ```cpp 57 | #include 58 | using namespace std; 59 | // Function to find row with max 1's 60 | 61 | int row_with_max1s(int * arr, int n, int m) 62 | { 63 | int i = 0; 64 | int j = m - 1; 65 | int row = -1; 66 | while (i < n && j >= 0) 67 | { 68 | if ( * (arr + i * m + j) == 1) 69 | { 70 | row = i; 71 | j--; 72 | } 73 | else 74 | { 75 | i++; 76 | } 77 | } 78 | return row; 79 | } 80 | 81 | int main() 82 | { 83 | int row, col; 84 | cout << "Enter the number of rows: "; 85 | cin >> row; 86 | 87 | cout << "Enter the number of columns: "; 88 | cin >> col; 89 | 90 | int arr[row][col]; 91 | 92 | cout << "Enter the elements of Matrix: " << endl; 93 | 94 | for (int i = 0; i < row; i++) 95 | { 96 | for (int j = 0; j < col; j++) 97 | { 98 | cin >> arr[i][j]; 99 | } 100 | } 101 | 102 | cout << "Row with max 1's: " << row_with_max1s((int * ) arr, row, col) << endl; 103 | return 0; 104 | } 105 | ``` 106 | 107 | 108 | 109 | 110 | ```python 111 | # Function to find row with max 1's 112 | 113 | def row_with_max1s(matrix, n, m): 114 | i = 0 115 | j = m - 1 116 | row = -1 117 | while i < n and j >= 0: 118 | if matrix[i][j] == 1: 119 | row = i 120 | j -= 1 121 | else: 122 | i += 1 123 | return row 124 | 125 | if __name__ == "__main__": 126 | row = int(input("Enter the number of rows: ")) 127 | col = int(input("Enter the number of columns: ")) 128 | 129 | matrix = [] 130 | print("Enter the elements of Matrix row-wise: ") 131 | 132 | for i in range(row): 133 | a = [] 134 | for j in range(col): 135 | a.append(int(input())) 136 | matrix.append(a) 137 | 138 | print("Row with max 1's:", row_with_max1s(matrix, row, col)) 139 | ``` 140 | 141 | 142 | 143 | 144 | ## Sample Input and Output 145 | 146 | #### Input : 147 | 148 | ``` 149 | Enter the number of rows: 3 150 | Enter the number of columns: 3 151 | Enter the elements of Matrix row-wise: 152 | 0 153 | 0 154 | 0 155 | 0 156 | 0 157 | 1 158 | 0 159 | 1 160 | 1 161 | ``` 162 | 163 | #### Output : 164 | 165 | ``` 166 | Row with max 1's: 2 167 | ``` 168 | 169 | ## Complexity Analysis 170 | 171 | - Time Complexity: `O(Row+Column)` 172 | - Space Complexity: `O(1)` -------------------------------------------------------------------------------- /docs/mathematics/sum-of-digits.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Sum of Digits 3 | slug: /mathematics/sum-of-digits 4 | --- 5 | 6 | ## Introduction 7 | 8 | In the Sum of Digits problem, we have to find the sum of the digits of the given number. 9 | 10 | ## Explanation 11 | 12 | Consider a number `n` = `pqr` (where `p`, `q`, and `r` are its individual digits). Then the sum of its digits say `Sum` would be 13 | 14 | ``` 15 | Sum = p + q + r 16 | ``` 17 | 18 | For Example, consider `n` = 4382 19 | 20 | ``` 21 | Sum = 4 + 3 + 8 + 2 = 17 22 | ``` 23 | 24 | Hence 17 is the sum of digits of the given number 4382. 25 | 26 | ## Algorithm 27 | 28 | Let us assume that the given number be `num`, 29 | 30 | - Declare a variable `sum` and set its value to 0. 31 | - Begin a While loop till `num != 0` 32 | - Set `rem = num % 10` 33 | - Set `sum = sum + rem` 34 | - Set `num = num / 10`. 35 | - Return the sum value. 36 | 37 | ## Code 38 | 39 | import Tabs from "@theme/Tabs"; 40 | import TabItem from "@theme/TabItem"; 41 | 42 | 49 | 50 | 51 | 52 | ```cpp 53 | // C++ PROGRAM TO COMPUTE THE SUM OF DIGITS OF A NUMBER 54 | #include 55 | using namespace std; 56 | // Function to calculate the sum of digits 57 | int sum_of_digits(int N) 58 | { 59 | int sum = 0; 60 | while(N != 0) 61 | { 62 | // Adding the last digit of the number to the sum 63 | int rem = N % 10; 64 | sum += rem; 65 | // Removing the last digit 66 | N = N / 10; 67 | } 68 | return sum; 69 | } 70 | int main() 71 | { 72 | int N; 73 | cout << "Enter the number: "; 74 | cin >> N; 75 | cout << "The sum of digits of the given number is " << sum_of_digits(N) << endl; 76 | return 0; 77 | } 78 | ``` 79 | 80 | 81 | 82 | 83 | ```python 84 | # Python program to Find the Sum of Digits of a Number 85 | def sum_of_digits(num): 86 | # Extracting Each digits 87 | # and compute thier sum in 's' 88 | s = 0 89 | while num != 0: 90 | s = s + (num % 10) 91 | num = num // 10 92 | return s 93 | if __name__ == '__main__': 94 | # Input the number And 95 | # Call the function 96 | print("Enter the number: ", end="") 97 | n = int(input()) 98 | S = sum_of_digits(abs(n)) 99 | print("The sum of digits of the given number is {}".format(S)) 100 | ``` 101 | 102 | 103 | 104 | 105 | ## Sample Input and Output 106 | 107 | #### Input 108 | 109 | ``` 110 | Enter the number: 1234 111 | ``` 112 | 113 | #### Output 114 | 115 | ``` 116 | The sum of digits of the given number is 10 117 | ``` 118 | 119 | ## Complexity Analysis 120 | 121 | - Time complexity - `O(log(n))`, where `n` is the given number 122 | - Space complexity - `O(1)` 123 | 124 | ## Credits 125 | 126 | - [Drishika Chauhan](https://github.com/drishika2002) for the [C++ Implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/math/Sum_of_digits.cpp) 127 | - [Hari Krishnan U](https://github.com/Harikrishnan6336) for the [Python Implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/Python/math/sum_of_digits.py) 128 | -------------------------------------------------------------------------------- /docs/mathematics/tetrahedral-number.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Tetrahedral Number 3 | slug: /mathematics/tetrahedral-number 4 | --- 5 | 6 | ## Introduction 7 | 8 | A Tetrahedral number is a figurate number. A Figurate number is a number that can be represented by a regular geometrical arrangement of equally spaced points. The Tetrahedral number represents a pyramid with a triangular base and three sides. We are given a number `n` and we need to print the `nth` tetrahedral number. 9 | 10 | ## Explanation 11 | 12 | The `nth` Tetrahedral number is the sum of first `n` triangular numbers. For calculating the `nth` tetrahedral number just apply the formula given below. First few tetrahedral numbers are `1`, `4`, `10`, `20`, `35`, `56`, `84`, `120`, `165`, `220`. 13 | 14 |

15 | 16 | Formula: 17 | ``` 18 | nth Tetrahedral Number: (n * (n + 1) * (n + 2)) / 6 19 | ``` 20 | 21 | Let's have few examples: 22 | ``` 23 | n = 3 24 | 3rd tetrahedral number = 10 25 | 26 | n = 5 27 | 5th tetrahedral number = 35 28 | 29 | n = 7 30 | 7th tetrahedral number = 84 31 | ``` 32 | 33 | ## Code 34 | 35 | import Tabs from '@theme/Tabs'; 36 | import TabItem from '@theme/TabItem'; 37 | 38 | 45 | 46 | 47 | ```cpp 48 | #include 49 | using namespace std; 50 | // Function to return nth tetrahedral number 51 | 52 | int tetrahedral_number(int n) 53 | { 54 | int res = n * (n+1) * (n+2); 55 | res = res / 6; 56 | return res; 57 | } 58 | 59 | int main() 60 | { 61 | int n; 62 | cout << "Enter the Number: "; 63 | cin >> n; 64 | 65 | cout<<"Tetrahedral Number is: "< 71 | 72 | 73 | 74 | ```python 75 | # Function to return nth tetrahedral number 76 | 77 | def tetrahedral_number(n): 78 | res = n * (n+1) * (n+2) 79 | res = res // 6 80 | return res 81 | 82 | if __name__ == "__main__": 83 | 84 | n = int(input("Enter the Number: ")) 85 | 86 | print("Tetrahedral Number is: ",tetrahedral_number(n)) 87 | ``` 88 | 89 | 90 | 91 | 92 | ## Sample Input and Output 93 | 94 | #### Input : 95 | 96 | ``` 97 | Enter the Number: 10 98 | ``` 99 | 100 | #### Output : 101 | 102 | ``` 103 | Tetrahedral Number is: 220 104 | ``` 105 | 106 | ## Complexity Analysis 107 | 108 | - Time Complexity: `O(1)` 109 | - Space Complexity: `O(1)` 110 | -------------------------------------------------------------------------------- /docs/mathematics/triangular-numbers.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Triangular Numbers 3 | slug: /mathematics/triangular-numbers 4 | --- 5 | 6 | ## Introduction 7 | 8 | A triangular number is a number that can be represented in the form of a triangular grid of points. This triangular grid should be an equilateral triangle. We need to check whether the number given by the user is a triangular number or not. 9 | 10 | ## Explanation 11 | 12 | Each row in a triangular grid formed by a triangular number contains the same number of points as the row number. The first row will contain `1` points, the second row will contain `2` points, the third row will contain `3` points, and so on. First few triangular numbers `1`, `3`, `6`, `10`. 13 | 14 |

15 | 16 | Let's have one example: 17 | ``` 18 | n = 6 19 | total_points = 1 , total points in the triangle till now 20 | row_point = 2 , point in the next row 21 | 22 | Iteration 1: 23 | total_points = total_points + row_point = 3 24 | row_point = row_point + 1 = 3 25 | 26 | Iteration 2: 27 | total_points = total_points + row_point = 6 28 | row_point = row_point + 1 = 4 29 | 30 | n is a triangular number because total_points became equal to n 31 | ``` 32 | 33 | ## Algorithm 34 | 35 | - Initialize `total_points` to `1` and `row_point` to `2`. 36 | 37 | - Keep on increasing the `total_points` by `row_point` and `row_point` by `1` until `total_points` becomes equal or greater than given number. 38 | 39 | - If `total_points` becomes equal to `n` then it is triangular number. 40 | 41 | ## Code 42 | 43 | import Tabs from '@theme/Tabs'; 44 | import TabItem from '@theme/TabItem'; 45 | 46 | 53 | 54 | 55 | ```cpp 56 | #include 57 | using namespace std; 58 | // Function to check whether a number is triangular or not 59 | 60 | int triangular_number(int n) 61 | { 62 | if(n == 1)return 1; 63 | int total_points = 1; 64 | int row_point = 2; 65 | while (total_points < n) 66 | { 67 | total_points += row_point++; 68 | } 69 | 70 | if (total_points == n) return 1; 71 | else return 0; 72 | } 73 | 74 | int main() 75 | { 76 | int n; 77 | cout << "Enter the Number: "; 78 | cin >> n; 79 | 80 | if (triangular_number(n)) 81 | cout << "Triangular Number" << endl; 82 | else 83 | cout << "Not a Triangular Number" << endl; 84 | 85 | return 0; 86 | } 87 | ``` 88 | 89 | 90 | 91 | 92 | ```python 93 | # Function to check whether a number is triangular or not 94 | 95 | def triangular_number(n): 96 | if(n == 1): 97 | return 1 98 | 99 | total_points = 1 100 | row_point = 2 101 | while (total_points < n): 102 | total_points += row_point 103 | row_point += 1 104 | 105 | if (total_points == n): 106 | return 1 107 | else: 108 | return 0 109 | 110 | if __name__ == "__main__": 111 | n = int(input("Enter the Number: ")) 112 | 113 | if (triangular_number(n)): 114 | print("Triangular Number") 115 | else: 116 | print("Not a Triangular Number") 117 | ``` 118 | 119 | 120 | 121 | 122 | ## Sample Input and Output 123 | 124 | #### Input : 125 | 126 | ``` 127 | Enter the Number: 6 128 | ``` 129 | 130 | #### Output : 131 | 132 | ``` 133 | Triangular Number 134 | ``` 135 | 136 | ## Complexity Analysis 137 | 138 | - Time Complexity: `O(n)` 139 | 140 | - Space Complexity: `O(1)` -------------------------------------------------------------------------------- /docs/miscellaneous/miscellaneous.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Miscellaneous 3 | slug: /miscellaneous 4 | --- 5 | 6 | This page would serve our needs for documentation of miscellaneous algorithms. -------------------------------------------------------------------------------- /docs/miscellaneous/sudoku-solver.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Sudoku Solver 3 | slug: /miscellaneous/sudoku-solver 4 | --- 5 | 6 | This page would serve our needs for documentation of the Sudoku Solver algorithm. -------------------------------------------------------------------------------- /docs/operating-systems/banker-algorithm.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Banker Algorithm 3 | slug: /operating-systems/banker-algorithm 4 | --- 5 | 6 | This page would serve our needs for documentation of the Banker Algorithm. -------------------------------------------------------------------------------- /docs/operating-systems/operating-systems.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Operating Systems 3 | slug: /operating-systems 4 | --- 5 | 6 | This page would serve our needs for documentation of the Operating Systems algorithms. -------------------------------------------------------------------------------- /docs/sorting-algorithms/bubble-sort.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Bubble Sort 3 | slug: /sorting-algorithms/bubble-sort 4 | --- 5 | 6 | ## Introduction 7 | 8 | The bubble sort is a simple sorting algorithm which compares two adjacent elements and swaps them if they are not in the correct order. 9 | 10 | ## Explanation 11 | 12 | Let's have an array arr[] where we have the following elements: ```5 4 3 2 1``` 13 | 14 | ![Imgur](https://i.imgur.com/mrC2YZn.png) 15 | 16 | ![Imgur](https://i.imgur.com/snYKCMG.png) 17 | 18 | ![Imgur](https://i.imgur.com/blbuUB2.png) 19 | 20 | ![Imgur](https://i.imgur.com/XLxdlis.png) 21 | 22 | ## Algorithm 23 | 24 | * Starting with the first element, compare the current element with the next element of the array. 25 | * If the current element is greater than the next element of the array, swap them. 26 | * If the current element is less than the next element, move to the next element. 27 | * Repeat Step 1. 28 | 29 | 30 | ## Code 31 | 32 | import Tabs from '@theme/Tabs'; 33 | import TabItem from '@theme/TabItem'; 34 | 35 | 42 | 43 | 44 | ```cpp 45 | #include 46 | using namespace std; //For cin and cout 47 | void bubblesort(int[], int); 48 | int main() 49 | { 50 | //Declarartion of required variables 51 | int n, arr[100], num; 52 | cout << "Enter the number of elements of the array: "; 53 | //Getting the number of elements of the array from the user 54 | cin >> n; 55 | cout << endl << "Enter the elements of the array to be sorted: " << "\n"; 56 | for (int i = 0; i < n; i++) 57 | { 58 | //For loop for taking elements of the array from the user, can be space-seperated as well 59 | cin >> num; 60 | arr[i] = num; 61 | } 62 | bubblesort(arr, n); 63 | cout << "Array after sorting is:" << endl; 64 | for (int i = 0; i < n; i++) 65 | { 66 | //For loop for printing out the array after sorting 67 | cout << arr[i] << " "; 68 | } 69 | } 70 | void bubblesort(int arr[], int n) 71 | { 72 | int temp; 73 | for (int i = 0; i < n - 1; i++) 74 | { 75 | // declaring a sorted variable which will check if array is already sorted or not 76 | bool sorted = true; 77 | for (int j = 0; j < n - 1 - i; j++) 78 | { 79 | //Inner for loop 80 | if (arr[j] > arr[j + 1]) 81 | { 82 | //Swapping the elements, temp is used to store the temporary variable 83 | temp = arr[j + 1]; 84 | arr[j + 1] = arr[j]; 85 | arr[j] = temp; 86 | // sorted value will be updated to false if there is swapping of elements occured 87 | sorted = false; 88 | } 89 | } 90 | if (sorted) 91 | { 92 | break; 93 | } 94 | } 95 | } 96 | ``` 97 | 98 | 99 | 100 | 101 | ```py 102 | def bubble_sort(Array): 103 | 104 | n = len(Array) 105 | for i in range(n-1): 106 | flag = True 107 | for j in range(n-i-1): 108 | if Array[j] > Array[j+1]: 109 | flag = False 110 | Array[j], Array[j+1] = Array[j+1], Array[j] 111 | if flag: 112 | break 113 | 114 | 115 | if __name__ == "__main__": 116 | 117 | print("Enter the elements of the list to be sorted: ") 118 | Array = [int(x) for x in input().split(" ")] 119 | bubble_sort(Array) 120 | print("List after sorting: ") 121 | for i in Array: 122 | print(i, end=" ") 123 | 124 | ``` 125 | 126 | 127 | 128 | 129 | ## Sample Input and Output 130 | 131 | #### Input: 132 | ``` 133 | 2 5 1 6 3 9 10 8 134 | ``` 135 | 136 | #### Output: 137 | ``` 138 | 1 2 3 5 6 8 9 10 139 | ``` 140 | 141 | ## Complexity Analysis 142 | 143 | - Time complexity - ```O(n^2)``` 144 | - Space complexity - ```O(1)``` 145 | 146 | ## Credits 147 | 148 | - [Rohan Babbar](https://github.com/rohanbabbar04) contributed the [C++ implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/C-Plus-Plus/sort/Bubble_Sort.cpp) 149 | - [Saloni Swagata](https://github.com/SaloniSwagata) contributed the [Python implementation](https://github.com/TesseractCoding/NeoAlgo/blob/master/Python/sort/Bubble_Sort.py) -------------------------------------------------------------------------------- /docs/sorting-algorithms/sorting-algorithms.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: What are Sorting Algorithms? 3 | slug: /sorting-algorithms 4 | --- 5 | 6 | This page would serve our needs for documentation of Sorting Algorithms. -------------------------------------------------------------------------------- /docs/thank-you.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Thank you! 3 | --- 4 | 5 | Congratulations on making it this far! 6 | 7 | You have learned the **basics of Docusaurus** and made some changes to the **initial template**. 8 | 9 | But Docusaurus has **much more to offer**! 10 | 11 | ## What's next? 12 | 13 | - [Read the official documentation](https://v2.docusaurus.io/). 14 | - [Design and Layout your Docusaurus site](https://v2.docusaurus.io/docs/styling-layout) 15 | - [Integrate a search bar into your site](https://v2.docusaurus.io/docs/search) 16 | - [Find inspirations in Docusaurus showcase](https://v2.docusaurus.io/showcase) 17 | - [Get involved in the Docusaurus Community](https://v2.docusaurus.io/community/support) 18 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "neoalgo-docs", 3 | "version": "0.0.0", 4 | "private": true, 5 | "workspaces": { 6 | "packages": [ 7 | "src/*", 8 | "plugins/*", 9 | "./docs" 10 | ], 11 | "nohoist": [ 12 | "**/html-minifier-terser" 13 | ] 14 | }, 15 | "scripts": { 16 | "docusaurus": "docusaurus", 17 | "start": "docusaurus start", 18 | "build": "docusaurus build", 19 | "swizzle": "docusaurus swizzle", 20 | "deploy": "docusaurus deploy", 21 | "clear": "docusaurus clear", 22 | "serve": "docusaurus serve", 23 | "write-translations": "docusaurus write-translations", 24 | "write-heading-ids": "docusaurus write-heading-ids" 25 | }, 26 | "dependencies": { 27 | "@docusaurus/core": "^2.0.0-alpha.73", 28 | "@docusaurus/plugin-google-analytics": "^2.0.0-alpha.73", 29 | "@docusaurus/plugin-pwa": "^2.0.0-alpha.73", 30 | "@docusaurus/preset-classic": "^2.0.0-alpha.73", 31 | "@docusaurus/theme-live-codeblock": "^2.0.0-alpha.73", 32 | "@mdx-js/react": "^1.6.21", 33 | "clsx": "^1.1.1", 34 | "react": "^17.0.1", 35 | "react-dom": "^17.0.1" 36 | }, 37 | "browserslist": { 38 | "production": [ 39 | ">0.5%", 40 | "not dead", 41 | "not op_mini all" 42 | ], 43 | "development": [ 44 | "last 1 chrome version", 45 | "last 1 firefox version", 46 | "last 1 safari version" 47 | ] 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/components/comments/index.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from 'react'; 2 | import useThemeContext from '@theme/hooks/useThemeContext'; 3 | import styles from "./styles.module.css"; 4 | import "./styles.css"; 5 | 6 | function Comments(props) { 7 | const { isDarkTheme } = useThemeContext(); 8 | const theme = isDarkTheme ? "github-dark" : "github-light"; 9 | 10 | useEffect(() => { 11 | const script = document.createElement('script'); 12 | 13 | script.src = "https://utteranc.es/client.js"; 14 | script.setAttribute('repo', "TesseractCoding/NeoAlgo-Docs"); 15 | script.setAttribute('issue-term', "pathname"); 16 | script.setAttribute('label', "comment"); 17 | script.setAttribute('theme', theme); 18 | script.crossOrigin = "anonymous"; 19 | script.async = true; 20 | 21 | document.getElementById("comment-container").appendChild(script); 22 | }, []); 23 | 24 | 25 | return ( 26 |
27 | ); 28 | } 29 | 30 | export default Comments; 31 | -------------------------------------------------------------------------------- /src/components/comments/styles.css: -------------------------------------------------------------------------------- 1 | .utterances { 2 | margin: 0; 3 | } 4 | 5 | @media only screen and (min-width: 997px) { 6 | .utterances { 7 | max-width: 75% !important; 8 | } 9 | } 10 | 11 | @media only screen and (max-width: 996px) { 12 | .utterances { 13 | margin-left: auto; 14 | margin-right: auto; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/components/comments/styles.module.css: -------------------------------------------------------------------------------- 1 | @media (min-width: 997px) and (max-width: 1320px) { 2 | .commentWrapper { 3 | max-width: calc( 4 | var(--ifm-container-width) - 300px - var(--ifm-spacing-horizontal) * 2 5 | ); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/css/custom.css: -------------------------------------------------------------------------------- 1 | /* stylelint-disable docusaurus/copyright-header */ 2 | /** 3 | * Any CSS included here will be global. The classic template 4 | * bundles Infima by default. Infima is a CSS framework designed to 5 | * work well for content-centric websites. 6 | */ 7 | 8 | /* You can override the default Infima variables here. */ 9 | :root { 10 | --ifm-color-primary: #3556e6; 11 | --ifm-color-primary-dark: rgb(33, 175, 144); 12 | --ifm-color-primary-darker: rgb(31, 165, 136); 13 | --ifm-color-primary-darkest: rgb(26, 136, 112); 14 | --ifm-color-primary-light: rgb(70, 203, 174); 15 | --ifm-color-primary-lighter: rgb(102, 212, 189); 16 | --ifm-color-primary-lightest: rgb(146, 224, 208); 17 | --ifm-code-font-size: 95%; 18 | } 19 | 20 | .docusaurus-highlight-code-line { 21 | background-color: rgb(72, 77, 91); 22 | display: block; 23 | margin: 0 calc(-1 * var(--ifm-pre-padding)); 24 | padding: 0 var(--ifm-pre-padding); 25 | } 26 | 27 | .navbar-sidebar--show .navbar-sidebar { 28 | width: 39%; 29 | } -------------------------------------------------------------------------------- /src/pages/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import clsx from 'clsx'; 3 | import Layout from '@theme/Layout'; 4 | import Link from '@docusaurus/Link'; 5 | import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; 6 | import useBaseUrl from '@docusaurus/useBaseUrl'; 7 | import styles from './styles.module.css'; 8 | 9 | const features = [ 10 | { 11 | title: 'Centralized & Unified', 12 | imageUrl: 'img/tesseract-coding-trees.svg', 13 | description: ( 14 | <> 15 | NeoAlgo aims to bring all Data Structures and Algorithms under one roof. Get started with high quality learning and resources 16 | to level up your understanding about Data Structures and Algorithms. 17 | 18 | ), 19 | }, 20 | { 21 | title: 'Free & Open Source', 22 | imageUrl: 'img/tesseract-coding-algorithms.svg', 23 | description: ( 24 | <> 25 | NeoAlgo strives forward for an Open-Source Community development. Come and conribute to NeoAlgo and NeoAlgo docs and be a 26 | part of our expanding Open-Source project. 27 | 28 | ), 29 | }, 30 | { 31 | title: 'Collaboration & Contribution', 32 | imageUrl: 'img/tesseract-coding-programming.svg', 33 | description: ( 34 | <> 35 | Collaborate with Developers and Writers to produce high-quality content in and around Data Structures & Algorithms. Plug in your 36 | contributions in an active feedback loop with maintainers and learn from the community. 37 | 38 | ), 39 | }, 40 | ]; 41 | 42 | function Feature({imageUrl, title, description}) { 43 | const imgUrl = useBaseUrl(imageUrl); 44 | return ( 45 |
46 | {imgUrl && ( 47 |
48 | {title} 49 |
50 | )} 51 |

{title}

52 |

{description}

53 |
54 | ); 55 | } 56 | 57 | export default function Home() { 58 | const context = useDocusaurusContext(); 59 | const {siteConfig = {}} = context; 60 | return ( 61 | 65 |
66 |
67 |

{siteConfig.title}

68 |

{siteConfig.tagline}

69 |
70 | 76 | Get Started 77 | 78 |
79 |
80 |
81 |
82 | {features && features.length > 0 && ( 83 |
84 |
85 |
86 | {features.map((props, idx) => ( 87 | 88 | ))} 89 |
90 |
91 |
92 | )} 93 |
94 |
95 | ); 96 | } 97 | -------------------------------------------------------------------------------- /src/pages/markdown-page.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Markdown page example 3 | --- 4 | 5 | # Markdown page example 6 | 7 | You don't need React to write simple standalone pages. 8 | -------------------------------------------------------------------------------- /src/pages/styles.module.css: -------------------------------------------------------------------------------- 1 | /* stylelint-disable docusaurus/copyright-header */ 2 | 3 | /** 4 | * CSS files with the .module.css suffix will be treated as CSS modules 5 | * and scoped locally. 6 | */ 7 | 8 | .heroBanner { 9 | padding: 4rem 0; 10 | text-align: center; 11 | position: relative; 12 | overflow: hidden; 13 | } 14 | 15 | @media screen and (max-width: 966px) { 16 | .heroBanner { 17 | padding: 2rem; 18 | } 19 | } 20 | 21 | .buttons { 22 | display: flex; 23 | align-items: center; 24 | justify-content: center; 25 | } 26 | 27 | .features { 28 | display: flex; 29 | align-items: center; 30 | padding: 2rem 0; 31 | width: 100%; 32 | } 33 | 34 | .featureImage { 35 | height: 200px; 36 | width: 200px; 37 | } 38 | 39 | .getStarted { 40 | color: white !important; 41 | } 42 | 43 | .getStarted:hover { 44 | color: black !important; 45 | background-color: white; 46 | } -------------------------------------------------------------------------------- /src/theme/DocItem/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import OriginalDocItem from "@theme-original/DocItem"; 3 | import Comment from "../../components/comments" 4 | 5 | export default function CustomDocItem(props) { 6 | return ( 7 | <> 8 | 9 | 10 | 11 | ); 12 | } 13 | -------------------------------------------------------------------------------- /static/.nojekyll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HarshCasper/NeoAlgo-Docs/fc22f8361e7bf59f5b2c76c55fe2e56699989336/static/.nojekyll -------------------------------------------------------------------------------- /static/img/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HarshCasper/NeoAlgo-Docs/fc22f8361e7bf59f5b2c76c55fe2e56699989336/static/img/favicon.ico -------------------------------------------------------------------------------- /static/img/main-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HarshCasper/NeoAlgo-Docs/fc22f8361e7bf59f5b2c76c55fe2e56699989336/static/img/main-logo.png -------------------------------------------------------------------------------- /static/img/pwa/android/android-launchericon-144-144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HarshCasper/NeoAlgo-Docs/fc22f8361e7bf59f5b2c76c55fe2e56699989336/static/img/pwa/android/android-launchericon-144-144.png -------------------------------------------------------------------------------- /static/img/pwa/android/android-launchericon-192-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HarshCasper/NeoAlgo-Docs/fc22f8361e7bf59f5b2c76c55fe2e56699989336/static/img/pwa/android/android-launchericon-192-192.png -------------------------------------------------------------------------------- /static/img/pwa/android/android-launchericon-48-48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HarshCasper/NeoAlgo-Docs/fc22f8361e7bf59f5b2c76c55fe2e56699989336/static/img/pwa/android/android-launchericon-48-48.png -------------------------------------------------------------------------------- /static/img/pwa/android/android-launchericon-512-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HarshCasper/NeoAlgo-Docs/fc22f8361e7bf59f5b2c76c55fe2e56699989336/static/img/pwa/android/android-launchericon-512-512.png -------------------------------------------------------------------------------- /static/img/pwa/chrome/chrome-estension-48-48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HarshCasper/NeoAlgo-Docs/fc22f8361e7bf59f5b2c76c55fe2e56699989336/static/img/pwa/chrome/chrome-estension-48-48.png -------------------------------------------------------------------------------- /static/img/pwa/chrome/chrome-favicon-16-16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HarshCasper/NeoAlgo-Docs/fc22f8361e7bf59f5b2c76c55fe2e56699989336/static/img/pwa/chrome/chrome-favicon-16-16.png -------------------------------------------------------------------------------- /static/img/pwa/chrome/chrome-installicon-128-128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HarshCasper/NeoAlgo-Docs/fc22f8361e7bf59f5b2c76c55fe2e56699989336/static/img/pwa/chrome/chrome-installicon-128-128.png -------------------------------------------------------------------------------- /static/img/pwa/firefox/firefox-general-128-128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HarshCasper/NeoAlgo-Docs/fc22f8361e7bf59f5b2c76c55fe2e56699989336/static/img/pwa/firefox/firefox-general-128-128.png -------------------------------------------------------------------------------- /static/img/pwa/firefox/firefox-general-16-16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HarshCasper/NeoAlgo-Docs/fc22f8361e7bf59f5b2c76c55fe2e56699989336/static/img/pwa/firefox/firefox-general-16-16.png -------------------------------------------------------------------------------- /static/img/pwa/firefox/firefox-general-48-48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HarshCasper/NeoAlgo-Docs/fc22f8361e7bf59f5b2c76c55fe2e56699989336/static/img/pwa/firefox/firefox-general-48-48.png -------------------------------------------------------------------------------- /static/img/pwa/firefox/firefox-marketplace-512-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HarshCasper/NeoAlgo-Docs/fc22f8361e7bf59f5b2c76c55fe2e56699989336/static/img/pwa/firefox/firefox-marketplace-512-512.png -------------------------------------------------------------------------------- /static/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "NeoAlgo", 3 | "Name": "NeoAlgo:", 4 | "description": "Bringing all Data Structures and Algorithms under one Roof ⚡", 5 | "display": "standalone", 6 | "scope": "/", 7 | "theme_color": "#fafbfc", 8 | "icons": [ 9 | { 10 | "src": "img/pwa/android/android-launchericon-512-512.png", 11 | "sizes": "512x512" 12 | }, 13 | { 14 | "src": "img/pwa/android/android-launchericon-192-192.png", 15 | "sizes": "192x192" 16 | }, 17 | { 18 | "src": "img/pwa/android/android-launchericon-144-144.png", 19 | "sizes": "144x144" 20 | }, 21 | { 22 | "src": "img/pwa/android/android-launchericon-48-48.png", 23 | "sizes": "48x48" 24 | }, 25 | { 26 | "src": "img/pwa/chrome/chrome-installicon-128-128.png", 27 | "sizes": "128x128" 28 | }, 29 | { 30 | "src": "img/pwa/chrome/chrome-estension-48-48.png", 31 | "sizes": "48x48" 32 | }, 33 | { 34 | "src": "img/pwa/chrome/chrome-favicon-16-16.png", 35 | "sizes": "16x16" 36 | }, 37 | { 38 | "src": "img/pwa/firefox/firefox-marketplace-512-512.png", 39 | "sizes": "512x512" 40 | }, 41 | { 42 | "src": "img/pwa/firefox/firefox-general-128-128.png", 43 | "sizes": "128x128" 44 | }, 45 | { 46 | "src": "img/pwa/firefox/firefox-general-48-48.png", 47 | "sizes": "48x48" 48 | }, 49 | { 50 | "src": "img/pwa/firefox/firefox-general-16-16.png", 51 | "sizes": "16x16" 52 | } 53 | ], 54 | "lang": "en", 55 | "start_url": "/" 56 | } 57 | --------------------------------------------------------------------------------