├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── documentation_improvement.md │ ├── feature_request.md │ ├── question.md │ └── support_request.md └── pull_request_template.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md └── solutions ├── day01 ├── solution_cpp.cpp ├── solution_java.java └── solution_python.py ├── day02 ├── solution_cpp.cpp ├── solution_java.java └── solution_python.py ├── day03 ├── solution_cpp.cpp ├── solution_elisp.el ├── solution_java.java ├── solution_javascript.js └── solution_python.py ├── day04 ├── solution_cpp.cpp ├── solution_java.java ├── solution_javascript.js └── solution_python.py ├── day05 ├── solution_cpp.cpp ├── solution_java.java └── solution_javascript.js ├── day06 ├── .gitkeep ├── Readme.md ├── solution_cpp.cpp ├── solution_java.java └── solution_python.py ├── day07 ├── .gitkeep ├── KrounositySolution.java ├── Readme.md ├── solutionInConstantSpace.cpp ├── solution_cpp.cpp ├── solution_java.java └── solution_python.py ├── day08 ├── .gitkeep ├── README ├── Solution.java ├── solution.cpp ├── solution.go ├── solution_java.java └── solution_python.py ├── day09 ├── .gitkeep ├── Readme.md ├── krounosity_solution.java ├── solution.cpp ├── solution_java.java └── solution_python.py ├── day10 ├── .gitkeep ├── maxWidthRamp.cpp ├── solution_java.java └── solution_python.py ├── day11 ├── .gitkeep ├── solution_java.java └── soultion_cpp.cpp ├── day12 ├── .gitkeep ├── Readme.md ├── solution_cpp.cpp ├── solution_java.java └── solution_python.py ├── day13 ├── .gitkeep ├── solution_java.java └── uniqueEmailAddress │ ├── Readme.md │ └── Solution.java ├── day14 ├── .gitkeep ├── Readme.md ├── solution_cpp.cpp ├── solution_java.java └── solution_py.py ├── day15 ├── .gitkeep ├── Separate Black and White Balls.java ├── Solution.java ├── Solution_cpp.cpp ├── shortEncodingofWords.py ├── solution_java.java ├── solution_javascript.js └── uniqueEmail.py ├── day16 ├── .gitkeep ├── Solution_cpp.cpp └── solution_java.java ├── day17 ├── .gitkeep ├── Day17.py ├── Readme.md ├── day17.cpp └── day17.java ├── day18 ├── .gitkeep ├── solution_cpp.cpp └── solution_java.java ├── day19 ├── .gitkeep ├── README.md ├── solution_cpp.cpp └── solutions │ └── day19 │ └── solution_java.java ├── day20 ├── .gitkeep ├── README.md ├── Solution.java ├── leetcode_daily_20.py └── solutions.cpp ├── day21 ├── .gitkeep ├── Solution.java ├── solution.cpp └── solution.js ├── day22 └── .gitkeep ├── day23 ├── .gitkeep ├── solution_cpp.cpp ├── solution_java.java └── solution_python.py ├── day24 ├── .gitkeep ├── solution.java ├── solution_cpp.cpp └── solution_java.java ├── day25 ├── .gitkeep ├── solution.java └── solution_java.java ├── day26 ├── .gitkeep └── solution_java.java ├── day27 ├── .gitkeep ├── README.md └── solution_java.java ├── day28 ├── .gitkeep └── solution_java.java ├── day29 ├── .gitkeep ├── README.md ├── solution_cpp.cpp ├── solution_java.java └── solution_python.py ├── day30 ├── .gitkeep └── solution_java.java ├── day31 └── .gitkeep └── solutions.iml /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug Report 3 | about: Report a bug to help us improve 4 | title: "[BUG] " 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '...' 17 | 3. Scroll down to '...' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Environment (please complete the following information):** 27 | - OS: [e.g., Windows, macOS] 28 | - Browser [e.g., Chrome, Firefox] 29 | - Version [e.g., 22] 30 | 31 | **Additional context** 32 | Add any other context about the problem here. 33 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/documentation_improvement.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Documentation Improvement 3 | about: Suggest improvements or additions to the documentation 4 | title: "[DOCS] " 5 | labels: documentation 6 | assignees: '' 7 | 8 | --- 9 | 10 | **What part of the documentation needs improvement?** 11 | Please specify the section or page of the documentation that needs improvement. 12 | 13 | **Describe the improvement** 14 | A clear and concise description of what you would like to see improved. 15 | 16 | **Additional context** 17 | Add any other context or screenshots related to the documentation improvement. 18 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature Request 3 | about: Suggest an idea for this project 4 | title: "[FEATURE] " 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Question 3 | about: Ask a question about the project 4 | title: "[QUESTION] " 5 | labels: question 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Your Question** 11 | Please provide your question in detail. 12 | 13 | **Additional context** 14 | If applicable, add any other context or screenshots related to your question. 15 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/support_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Support Request 3 | about: Get help with using the project 4 | title: "[SUPPORT] " 5 | labels: support 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe your issue** 11 | A clear and concise description of your issue. 12 | 13 | **Steps Taken So Far** 14 | What steps have you taken so far to try and resolve the issue? 15 | 16 | **Environment (please complete the following information):** 17 | - OS: [e.g., Windows, macOS] 18 | - Version [e.g., v1.2.3] 19 | 20 | **Additional context** 21 | Add any other context or screenshots related to your support request. 22 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ### 🚀 What does this PR do? 4 | 5 | - Adds solution for LeetCode Daily Challenge on (Day and Date) in (Programming Language). 6 | - Briefly explain the approach taken to solve the problem. 7 | 8 | ### 📝 Issue Reference: 9 | 10 | Fixes issue: # (Mention the issue number this PR solves) 11 | 12 | ### 🔍 Checklist: 13 | Please ensure the following before submitting your PR: 14 | - [ ] I have placed my solution in the correct folder (`solutions/dayXX/`). 15 | - [ ] My code follows clean coding practices and is efficient. 16 | - [ ] I have added comments in my code to explain the approach. 17 | - [ ] I have updated the `README.md` for the specific day with a brief explanation of my solution. 18 | - [ ] I have tested the solution on LeetCode and it works correctly. 19 | 20 | ### 🔧 Solution Details: 21 | - **Language Used**: (e.g., Python, Java, C++, etc.) 22 | - **Time Complexity**: (e.g., O(n log n), O(n), etc.) 23 | - **Space Complexity**: (e.g., O(1), O(n), etc.) 24 | 25 | ### 🌟 Additional Notes (if any): 26 | 27 | 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | replay_pid* 25 | 26 | 27 | # Byte-compiled / optimized / DLL files 28 | __pycache__/ 29 | *.py[cod] 30 | *$py.class 31 | 32 | # C extensions 33 | *.so 34 | 35 | # Distribution / packaging 36 | .Python 37 | build/ 38 | develop-eggs/ 39 | dist/ 40 | downloads/ 41 | eggs/ 42 | .eggs/ 43 | lib/ 44 | lib64/ 45 | parts/ 46 | sdist/ 47 | var/ 48 | wheels/ 49 | share/python-wheels/ 50 | *.egg-info/ 51 | .installed.cfg 52 | *.egg 53 | MANIFEST 54 | 55 | # PyInstaller 56 | # Usually these files are written by a python script from a template 57 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 58 | *.manifest 59 | *.spec 60 | 61 | # Installer logs 62 | pip-log.txt 63 | pip-delete-this-directory.txt 64 | 65 | # Unit test / coverage reports 66 | htmlcov/ 67 | .tox/ 68 | .nox/ 69 | .coverage 70 | .coverage.* 71 | .cache 72 | nosetests.xml 73 | coverage.xml 74 | *.cover 75 | *.py,cover 76 | .hypothesis/ 77 | .pytest_cache/ 78 | cover/ 79 | 80 | # Translations 81 | *.mo 82 | *.pot 83 | 84 | # Django stuff: 85 | *.log 86 | local_settings.py 87 | db.sqlite3 88 | db.sqlite3-journal 89 | 90 | # Flask stuff: 91 | instance/ 92 | .webassets-cache 93 | 94 | # Scrapy stuff: 95 | .scrapy 96 | 97 | # Sphinx documentation 98 | docs/_build/ 99 | 100 | # PyBuilder 101 | .pybuilder/ 102 | target/ 103 | 104 | # Jupyter Notebook 105 | .ipynb_checkpoints 106 | 107 | # IPython 108 | profile_default/ 109 | ipython_config.py 110 | 111 | # pyenv 112 | # For a library or package, you might want to ignore these files since the code is 113 | # intended to run in multiple environments; otherwise, check them in: 114 | # .python-version 115 | 116 | # pipenv 117 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 118 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 119 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 120 | # install all needed dependencies. 121 | #Pipfile.lock 122 | 123 | # poetry 124 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 125 | # This is especially recommended for binary packages to ensure reproducibility, and is more 126 | # commonly ignored for libraries. 127 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 128 | #poetry.lock 129 | 130 | # pdm 131 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 132 | #pdm.lock 133 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 134 | # in version control. 135 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 136 | .pdm.toml 137 | .pdm-python 138 | .pdm-build/ 139 | 140 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 141 | __pypackages__/ 142 | 143 | # Celery stuff 144 | celerybeat-schedule 145 | celerybeat.pid 146 | 147 | # SageMath parsed files 148 | *.sage.py 149 | 150 | # Environments 151 | .env 152 | .venv 153 | env/ 154 | venv/ 155 | ENV/ 156 | env.bak/ 157 | venv.bak/ 158 | 159 | # Spyder project settings 160 | .spyderproject 161 | .spyproject 162 | 163 | # Rope project settings 164 | .ropeproject 165 | 166 | # mkdocs documentation 167 | /site 168 | 169 | # mypy 170 | .mypy_cache/ 171 | .dmypy.json 172 | dmypy.json 173 | 174 | # Pyre type checker 175 | .pyre/ 176 | 177 | # pytype static type analyzer 178 | .pytype/ 179 | 180 | # Cython debug symbols 181 | cython_debug/ 182 | 183 | # PyCharm 184 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 185 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 186 | # and can be added to the global gitignore or merged into this file. For a more nuclear 187 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 188 | #.idea/ 189 | 190 | # Prerequisites 191 | *.d 192 | 193 | # Compiled Object files 194 | *.slo 195 | *.lo 196 | *.o 197 | *.obj 198 | 199 | # Precompiled Headers 200 | *.gch 201 | *.pch 202 | 203 | # Compiled Dynamic libraries 204 | *.so 205 | *.dylib 206 | *.dll 207 | 208 | # Fortran module files 209 | *.mod 210 | *.smod 211 | 212 | # Compiled Static libraries 213 | *.lai 214 | *.la 215 | *.a 216 | *.lib 217 | 218 | # Executables 219 | *.exe 220 | *.out 221 | *.app -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Contributor Covenant Code of Conduct 4 | 5 | ## Our Pledge 6 | 7 | We, as members, contributors, and leaders, pledge to make participation in our community a **harassment-free experience** for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 8 | 9 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 10 | 11 | ## Our Standards 12 | 13 | Examples of behavior that contributes to a positive environment for our community include: 14 | 15 | - Demonstrating empathy and kindness toward other people 16 | - Being respectful of differing opinions, viewpoints, and experiences 17 | - Giving and gracefully accepting constructive feedback 18 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 19 | - Focusing on what is best not just for us as individuals, but for the overall community 20 | 21 | Examples of unacceptable behavior include: 22 | 23 | - The use of sexualized language or imagery, and sexual attention or advances of any kind 24 | - Trolling, insulting or derogatory comments, and personal or political attacks 25 | - Public or private harassment 26 | - Publishing others' private information, such as a physical or email address, without their explicit permission 27 | - Other conduct which could reasonably be considered inappropriate in a professional setting 28 | 29 | ## Enforcement Responsibilities 30 | 31 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 32 | 33 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned with this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 34 | 35 | ## Scope 36 | 37 | This Code of Conduct applies within all community spaces, and it also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 38 | 39 | ## Enforcement 40 | 41 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at **arya.pathak@outlook.in**. All complaints will be reviewed and investigated promptly and fairly. 42 | 43 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 44 | 45 | ## Enforcement Guidelines 46 | 47 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 48 | 49 | ### 1. Correction 50 | 51 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 52 | 53 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. 54 | 55 | ### 2. Warning 56 | 57 | **Community Impact**: A violation through a single incident or series of actions. 58 | 59 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. 60 | 61 | ### 3. Temporary Ban 62 | 63 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 64 | 65 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 66 | 67 | ### 4. Permanent Ban 68 | 69 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 70 | 71 | **Consequence**: A permanent ban from any sort of public interaction within the community. 72 | 73 | ## Attribution 74 | 75 | This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html](https://www.contributor-covenant.org/version/2/1/code_of_conduct.html). 76 | 77 | For answers to common questions about this code of conduct, see [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). 78 | 79 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Contributing to LeetCode Daily October Hacktoberfest 2024 4 | 5 | Thank you for your interest in contributing to the **LeetCode Daily October Hacktoberfest Challenge 2024**! Your contributions help us create a robust and diverse set of solutions for LeetCode’s daily challenges in various programming languages. This guide will help you get started with contributing. 6 | 7 | ## Table of Contents 8 | 9 | - [How to Contribute](#how-to-contribute) 10 | - [Fork the Repository](#fork-the-repository) 11 | - [Clone the Repository](#clone-the-repository) 12 | - [Work on Your Contribution](#work-on-your-contribution) 13 | - [Create a Pull Request](#create-a-pull-request) 14 | - [Contribution Guidelines](#contribution-guidelines) 15 | - [Code Quality](#code-quality) 16 | - [Documentation](#documentation) 17 | - [Languages Supported](#languages-supported) 18 | - [Testing Your Solution](#testing-your-solution) 19 | - [Pull Request Review Process](#pull-request-review-process) 20 | - [Reporting Issues](#reporting-issues) 21 | 22 | --- 23 | 24 | ## How to Contribute 25 | 26 | We are excited to have you contribute! Follow the steps below to add your solutions or improve the project. 27 | 28 | ### 1. Fork the Repository 29 | 30 | Start by **forking** this repository. Forking will create a copy of the repository under your GitHub account where you can make your changes. You can fork the repository by clicking on the "Fork" button at the top-right of the [repository page](https://github.com/arya2004/leetcode-daily-october-hacktoberfest-2024). 31 | 32 | ### 2. Clone the Repository 33 | 34 | After forking, clone the repository to your local machine so you can work on it. 35 | 36 | ```bash 37 | git clone https://github.com/your-username/leetcode-daily-october-hacktoberfest-2024.git 38 | ``` 39 | 40 | Make sure to replace `your-username` with your actual GitHub username. 41 | 42 | ### 3. Work on Your Contribution 43 | 44 | Navigate to the appropriate directory for the day you want to contribute a solution for: 45 | 46 | ```bash 47 | cd solutions/dayXX 48 | ``` 49 | 50 | Where `dayXX` is the folder for the day's problem you're solving (e.g., `day01`, `day02`, etc.). Add your solution file in one of the preferred programming languages (or another language if you'd like): 51 | 52 | - **Python**: `solution_python.py` 53 | - **Java**: `solution_java.java` 54 | - **C++**: `solution_cpp.cpp` 55 | 56 | If you're adding a solution in a different language, feel free to create a new file, like `solution_ruby.rb`. 57 | 58 | Once you've added your solution, create or update the `README.md` file within that day's folder to describe your approach to solving the problem. Make sure to document the following: 59 | 60 | - The **problem statement** (if not already present in the folder). 61 | - A brief **explanation of your solution** and approach. 62 | - Any additional **comments** on time/space complexity or optimizations (if applicable). 63 | 64 | ### 4. Create a Pull Request 65 | 66 | Once you're satisfied with your solution and documentation: 67 | 68 | 1. **Commit** your changes: 69 | 70 | ```bash 71 | git add . 72 | git commit -m "Add solution for Day XX problem in Python" 73 | ``` 74 | 75 | 2. **Push** your changes to your forked repository: 76 | 77 | ```bash 78 | git push origin main 79 | ``` 80 | 81 | 3. Navigate to the original repository on GitHub, and you should see an option to **Compare & pull request**. Click it and create your **pull request** (PR). 82 | 83 | - In the PR description, mention the day and language you're submitting for (e.g., "Solution for Day 3 in C++"). 84 | - Optionally, mention any edge cases you handled or special insights about your approach. 85 | 86 | We will review your PR as soon as possible and merge it if everything looks good. 87 | 88 | --- 89 | 90 | ## Contribution Guidelines 91 | 92 | ### Code Quality 93 | 94 | Please ensure that your code is: 95 | 96 | - **Well-structured** and follows coding conventions for the chosen language. 97 | - **Efficient**, aiming for the best time and space complexity possible. 98 | - **Readable** with meaningful comments and clear variable/function names. 99 | 100 | ### Documentation 101 | 102 | In each day's `README.md` file, document your approach, optimizations, and complexity analysis if applicable. This helps others learn from your solution. You can also include pseudocode or a breakdown of your thought process. 103 | 104 | ### Languages Supported 105 | 106 | We primarily support solutions in: 107 | 108 | - **Python** 109 | - **Java** 110 | - **C++** 111 | 112 | However, contributions in other languages are welcome, such as JavaScript, Go, Ruby, or Rust. Just make sure your solution works correctly in the language of your choice. 113 | 114 | ### Testing Your Solution 115 | 116 | Before submitting, ensure that: 117 | 118 | 1. Your solution is working correctly by testing it against the problem's example cases and any edge cases you can think of. 119 | 2. You include meaningful **comments** to explain the logic, especially if your solution involves complex algorithms or techniques. 120 | 121 | --- 122 | 123 | ## Pull Request Review Process 124 | 125 | Once you open a pull request: 126 | 127 | 1. The maintainers will review your code to ensure it follows the project's guidelines. 128 | 2. If changes are required, we will leave feedback, and you can update your PR. 129 | 3. Once approved, the PR will be merged into the main repository. 130 | 131 | If you’re not sure how to address feedback or need help, feel free to ask questions in the PR discussion. 132 | 133 | --- 134 | 135 | ## Reporting Issues 136 | 137 | If you notice any issues or problems with the repository, such as: 138 | 139 | - **Bugs** in existing solutions 140 | - Incorrect problem statements 141 | - Suggestions for new features 142 | 143 | Feel free to open a new issue! We have templates for reporting daily problems and feature requests. You can use these templates to describe your issue clearly. 144 | 145 | To report an issue, go to the **Issues** tab of the repository and click **New Issue**. Choose the appropriate template and fill it out with relevant details. 146 | 147 | --- 148 | 149 | Thank you for contributing to **LeetCode Daily October Hacktoberfest 2024**! Every contribution, no matter how small, helps grow our community and makes this project better. We look forward to your participation and solutions! 150 | 151 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Arya Pathak 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 | 2 | 3 | # LeetCode Daily October Hacktoberfest 2024 4 | 5 |
6 | Hacktoberfest Banner 7 |
8 | 9 | 10 | Welcome to the **LeetCode Daily October Hacktoberfest Challenge 2024**! This repository is dedicated to solving **LeetCode's daily problems** for the month of October, while also giving you the chance to participate in **Hacktoberfest 2024** by contributing to an open-source project. 11 | 12 | ## 🌟 What is Hacktoberfest? 13 | 14 |
15 | Hacktoberfest Logo Horizontal 16 |
17 | 18 | 19 | 20 | Hacktoberfest is a month-long celebration of open-source software development, organized by **DigitalOcean**, **GitHub**, and **other partners**. It's a fantastic opportunity to contribute to open-source projects and make an impact on the developer community. Participants who contribute successfully to open-source projects during the month of October are eligible to win **exclusive T-shirts** and **swag**. 21 | 22 | For more details, visit the [official Hacktoberfest website](https://hacktoberfest.com). 23 | 24 | ## 🚀 About This Repository 25 | 26 | This repository contains **solutions to LeetCode's daily coding challenges** for October 2024. The primary focus of this repo is to provide solutions in **Java**, **C++**, and **Python**, but contributions in **any language** are welcome. 27 | 28 | Each day will have a dedicated issue and folder for the corresponding problem, and contributors can submit solutions in their preferred language. 29 | 30 | ## 📂 Repository Structure 31 | 32 | Each **day** of October has its own folder in the `solutions/` directory, where contributors can add their solutions in multiple languages. 33 | 34 | ## 💡 How to Contribute 35 | 36 | Contributing is easy and welcome! Here's a step-by-step guide: 37 | 38 | ### 1. Fork this Repository 39 | 40 | Start by **forking** this repository. This will create a copy of the project under your GitHub account. 41 | 42 | ### 2. Clone the Forked Repository 43 | 44 | Next, clone the forked repository to your local machine: 45 | 46 | ```bash 47 | git clone https://github.com/arya2004/leetcode-daily-october-hacktoberfest-2024.git 48 | ``` 49 | 50 | ### 3. Navigate to the Correct Directory 51 | 52 | Go to the `solutions/` folder and navigate to the directory corresponding to the day you're contributing to: 53 | 54 | ```bash 55 | cd solutions/day01 56 | ``` 57 | 58 | ### 4. Add Your Solution 59 | 60 | You can add your solution in **any language** (e.g., Python, Java, C++, etc.). Here's an example for Python: 61 | 62 | ```bash 63 | touch solution_python.py 64 | ``` 65 | 66 | Don't forget to add comments to explain your solution and make it easier for others to understand. 67 | 68 | ### 5. Commit and Push Changes 69 | 70 | Once you've added your solution, commit your changes: 71 | 72 | ```bash 73 | git add . 74 | git commit -m "Add Day 1 solution in Python" 75 | git push origin main 76 | ``` 77 | 78 | ### 6. Open a Pull Request 79 | 80 | Go to the original repository and **open a pull request** from your forked version. Make sure to describe your solution and mention the problem you're solving. 81 | 82 | We will review your pull request as soon as possible! 83 | 84 | ## 🎯 Contribution Guidelines 85 | 86 | Please adhere to the following guidelines when contributing: 87 | 88 | 1. **One solution per pull request**: Only submit one day's solution per pull request. 89 | 2. **Proper documentation**: Add a brief explanation of your approach in the `README.md` file inside the relevant day’s folder. 90 | 3. **Code quality**: Follow best practices for writing clean and efficient code. 91 | 4. **Respect the structure**: Place your solution files in the appropriate day's folder under `solutions/`. 92 | 93 | For more detailed guidelines, please check the [CONTRIBUTING.md](CONTRIBUTING.md) file. 94 | 95 | ## 🏆 Hacktoberfest 2024 96 | 97 | By contributing to this repository, you are taking part in **Hacktoberfest 2024**. Once you've made four contributions to eligible repositories, you'll be eligible to receive a limited-edition Hacktoberfest Holopin Badge. 98 | 99 |
100 | Hacktoberfest Logo Vertical 101 |
102 | 103 | 104 | ### What to Work On? 105 | 106 | - Solve daily LeetCode problems and submit your solutions. 107 | - Add comments explaining your code. 108 | - Contribute to the problem descriptions or documentation. 109 | - Help by reviewing and improving existing solutions. 110 | 111 | ## 📜 License 112 | 113 | This repository is licensed under the [MIT License](LICENSE), so feel free to use the code and contribute under the terms of that license. 114 | 115 | ## 🙌 Join Us and Start Contributing! 116 | 117 | We are excited to see your contributions and help you grow in your open-source journey. Whether you're a beginner or an experienced developer, there's a place for you in this repository. 118 | 119 | Let’s solve problems together and make Hacktoberfest 2024 awesome! 120 | 121 | --- 122 | 123 | -------------------------------------------------------------------------------- /solutions/day01/solution_cpp.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canArrange(vector& arr, int k) { 4 | int n = arr.size(); 5 | 6 | vectorresult(k,0); 7 | 8 | for(int i=0 ; i arrayRankTransform(vector& arr) { 4 | sets; 5 | for(auto i:arr) 6 | s.insert(i); 7 | 8 | unordered_mapmp; 9 | int t=1; 10 | for(auto i:s){ 11 | mp[i]=t; 12 | t++; 13 | } 14 | vectorans; 15 | for(int i=0;i hs = new HashMap<>(); 9 | int[] ans = new int[arr.length]; 10 | int[] temp = new int[arr.length]; 11 | 12 | for(int i = 0; i < arr.length; i++){ 13 | temp[i] = arr[i]; 14 | 15 | } 16 | Arrays.sort(temp); 17 | 18 | int n = arr.length; 19 | 20 | int j = 1; 21 | 22 | for(int i = 0; i < n; i++){ 23 | if(!hs.containsKey(temp[i])){ 24 | hs.put(temp[i], j); 25 | j++; 26 | }else{ 27 | continue; 28 | } 29 | } 30 | 31 | for(int i = 0; i < n; i++){ 32 | ans[i] = hs.get(arr[i]); 33 | 34 | } 35 | 36 | return ans; 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /solutions/day02/solution_python.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arrayRankTransform(self, arr: List[int]) -> List[int]: 3 | s = set(arr) 4 | mp = {} 5 | r = 1 6 | 7 | for value in sorted(s): 8 | mp[value] = r 9 | r += 1 10 | 11 | for i in range(len(arr)): 12 | arr[i] = mp[arr[i]] 13 | 14 | return arr -------------------------------------------------------------------------------- /solutions/day03/solution_cpp.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minSubarray(vector& nums, int p) { 4 | long long sum = 0; 5 | for (int i : nums) { 6 | sum += i; 7 | } 8 | 9 | int rem = sum % p; 10 | if (rem == 0) return 0; 11 | 12 | unordered_map prefixModMap; 13 | prefixModMap[0] = -1; 14 | long long prefixSum = 0; 15 | int minLength = nums.size(); 16 | 17 | for (int i = 0; i < nums.size(); i++) { 18 | prefixSum += nums[i]; 19 | int currentMod = prefixSum % p; 20 | int targetMod = (currentMod - rem + p) % p; // Find the mod that would remove the remainder 21 | 22 | if (prefixModMap.find(targetMod) != prefixModMap.end()) { 23 | minLength = min(minLength, i - prefixModMap[targetMod]); 24 | } 25 | 26 | prefixModMap[currentMod] = i; 27 | } 28 | 29 | return (minLength == nums.size()) ? -1 : minLength; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /solutions/day03/solution_elisp.el: -------------------------------------------------------------------------------- 1 | ;; Given an array of positive integers nums, remove the smallest subarray (possibly empty) 2 | ;; such that the sum of the remaining elements is divisible by p. It is not allowed to remove 3 | ;; the whole array. 4 | ;; 5 | ;; Return the length of the smallest subarray that you need to remove, or -1 if it's impossible. 6 | ;; 7 | ;; A subarray is defined as a contiguous block of elements in the array. 8 | ;; 9 | ;; Example 1: 10 | ;; Input: nums = [3,1,4,2], p = 6 11 | ;; Output: 1 12 | ;; Explanation: The sum of the elements in nums is 10, which is not divisible by 6. 13 | ;; We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6. 14 | ;; 15 | ;; Example 2: 16 | ;; Input: nums = [6,3,5,2], p = 9 17 | ;; Output: 2 18 | ;; Explanation: We cannot remove a single element to get a sum divisible by 9. 19 | ;; The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9. 20 | ;; 21 | ;; Example 3: 22 | ;; Input: nums = [1,2,3], p = 3 23 | ;; Output: 0 24 | ;; Explanation: Here the sum is 6, which is already divisible by 3. Thus we do not need to remove anything. 25 | 26 | (defun min-length-subarray (nums p) 27 | "Return the length of the smallest subarray to remove from NUMS such that the sum of the remaining elements is divisible by P." 28 | (let* ((total-sum (apply '+ nums)) 29 | (target-remainder (mod total-sum p))) 30 | (if (zerop target-remainder) 31 | 0 ;; Already divisible by p 32 | (let ((n (length nums)) 33 | (min-length (1+ n)) ;; Start with a value larger than any possible subarray 34 | (prefix-sum (make-vector (1+ (length nums)) 0))) 35 | ;; Calculate prefix sums 36 | (dotimes (i n) 37 | (aset prefix-sum (1+ i) (+ (aref prefix-sum i) (nth i nums)))) 38 | ;; Use a hash table to store the last index of each prefix sum modulo p 39 | (let ((last-index (make-hash-table :test 'equal))) 40 | (dotimes (i (1+ n)) 41 | (let ((current-remainder (mod (aref prefix-sum (1+ i)) p))) 42 | (when (gethash current-remainder last-index) 43 | (let ((start-index (gethash current-remainder last-index))) 44 | (setq min-length (min min-length (- i start-index))))) 45 | ;; Update the last index for the current remainder 46 | (unless (gethash current-remainder last-index) 47 | (puthash current-remainder i last-index))))) 48 | ;; Return the result 49 | (if (= min-length (1+ n)) 50 | -1 ;; No valid subarray found 51 | min-length))))) 52 | 53 | ;; Example usage: 54 | (min-length-subarray [3 1 4 2] 6) ;; => 1 55 | (min-length-subarray [6 3 5 2] 9) ;; => 2 56 | (min-length-subarray [1 2 3] 3) ;; => 0 57 | -------------------------------------------------------------------------------- /solutions/day03/solution_java.java: -------------------------------------------------------------------------------- 1 | package solutions.day03; 2 | 3 | import java.util.HashMap; 4 | 5 | public class solution_java { 6 | public int minSubarray(int[] nums, int p) { 7 | long totalSum = 0; 8 | for (int num : nums) { 9 | totalSum += num; 10 | } 11 | 12 | // Find remainder when total sum is divided by p 13 | int rem = (int)(totalSum % p); 14 | if (rem == 0) return 0; // If remainder is 0, no subarray needs to be removed 15 | 16 | HashMap prefixMod = new HashMap<>(); 17 | prefixMod.put(0, -1); // Initialize to handle full prefix 18 | long prefixSum = 0; 19 | int minLength = nums.length; 20 | 21 | for (int i = 0; i < nums.length; ++i) { 22 | prefixSum += nums[i]; 23 | int currentMod = (int)(prefixSum % p); 24 | int targetMod = (currentMod - rem + p) % p; 25 | 26 | if (prefixMod.containsKey(targetMod)) { 27 | minLength = Math.min(minLength, i - prefixMod.get(targetMod)); 28 | } 29 | 30 | prefixMod.put(currentMod, i); 31 | } 32 | 33 | return minLength == nums.length ? -1 : minLength; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /solutions/day03/solution_javascript.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} p 4 | * @return {number} 5 | */ 6 | var minSubarray = function(nums, p) { 7 | let n = nums.length; 8 | let target = nums.reduce((a, b) => a + b, 0) % p; 9 | 10 | if (target === 0) return 0; 11 | 12 | let answer = n; 13 | let prefix_sum = 0; 14 | let hashmap = {0: -1}; 15 | 16 | for (let i = 0; i < n; i++) { 17 | prefix_sum += nums[i]; 18 | let key = (prefix_sum % p - target + p) % p; 19 | 20 | if (key in hashmap) { 21 | answer = Math.min(answer, i - hashmap[key]); 22 | } 23 | 24 | hashmap[prefix_sum % p] = i; 25 | } 26 | 27 | return answer < n ? answer : -1; 28 | }; 29 | -------------------------------------------------------------------------------- /solutions/day03/solution_python.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSubarray(self, nums: List[int], p: int) -> int: 3 | total_sum = sum(nums) 4 | remainder = total_sum % p 5 | if remainder == 0: 6 | return 0 7 | 8 | prefix_mod = {0: -1} # A dictionary to store prefix sums modulo p 9 | pref_sum = 0 10 | min_length = len(nums) 11 | 12 | for i in range(len(nums)): 13 | pref_sum += nums[i] 14 | curr = pref_sum % p 15 | target_mod = (curr - remainder + p) % p 16 | 17 | if target_mod in prefix_mod: 18 | min_length = min(min_length, i - prefix_mod[target_mod]) 19 | 20 | prefix_mod[curr] = i 21 | 22 | return -1 if min_length == len(nums) else min_length -------------------------------------------------------------------------------- /solutions/day04/solution_cpp.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long dividePlayers(vector& skill) { 4 | sort(skill.begin(),skill.end()); 5 | int n=skill.size(); 6 | sets; 7 | 8 | long long pro=0; 9 | for(int i=0;i a - b); 7 | 8 | let numPlayers = skillLevels.length; 9 | let requiredSum = skillLevels[0] + skillLevels[numPlayers - 1]; 10 | let totalChemistry = 0; 11 | 12 | for (let i = 0; i < numPlayers / 2; i++) { 13 | if (skillLevels[i] + skillLevels[numPlayers - i - 1] !== requiredSum) { 14 | return -1; 15 | } 16 | totalChemistry += skillLevels[i] * skillLevels[numPlayers - i - 1]; 17 | } 18 | 19 | return totalChemistry; 20 | }; 21 | -------------------------------------------------------------------------------- /solutions/day04/solution_python.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def dividePlayers(self, skill): 3 | n = len(skill) 4 | skill.sort() # Sort the skill array 5 | ans = 0 6 | i = 0 7 | j = n - 1 8 | k = skill[i] + skill[j] # Target sum for each pair 9 | 10 | while i < j: 11 | if skill[i] + skill[j] != k: # Check if current pair sum matches target 12 | return -1 13 | ans += skill[i] * skill[j] # Add the product of the current pair 14 | i += 1 15 | j -= 1 16 | 17 | return ans 18 | -------------------------------------------------------------------------------- /solutions/day05/solution_cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Solution { 5 | public: 6 | bool checkInclusion(std::string s1, std::string s2) { 7 | if (s1.length() > s2.length()) return false; // Early exit if s1 is longer than s2 8 | 9 | std::vector a(26, 0); // Frequency array for s1 10 | for (char ch : s1) { 11 | a[ch - 'a']++; 12 | } 13 | 14 | for (int i = 0; i <= s2.length() - s1.length(); i++) { 15 | std::vector b(26, 0); // Frequency array for the current substring of s2 16 | for (int j = 0; j < s1.length(); j++) { 17 | b[s2[i + j] - 'a']++; 18 | } 19 | if (check(a, b)) { 20 | return true; // Found a permutation 21 | } 22 | } 23 | return false; // No permutation found 24 | } 25 | 26 | bool check(const std::vector& a, const std::vector& b) { 27 | for (int i = 0; i < 26; i++) { 28 | if (a[i] != b[i]) { 29 | return false; // Frequencies do not match 30 | } 31 | } 32 | return true; // Frequencies match 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /solutions/day05/solution_java.java: -------------------------------------------------------------------------------- 1 | package solutions.day05; 2 | 3 | import java.util.Arrays; 4 | 5 | public class solution_java { 6 | public boolean checkInclusion(String s1, String s2) { 7 | int[] h1 = new int[26]; 8 | int[] h2 = new int[26]; 9 | 10 | int l1 = s1.length(); 11 | int l2 = s2.length(); 12 | 13 | if(l1 > l2) return false; 14 | 15 | for(int i = 0; i < l1; i++){ 16 | h1[s1.charAt(i) - 'a'] += 1; 17 | h2[s2.charAt(i) - 'a'] += 1; 18 | } 19 | 20 | if(Arrays.equals(h1, h2)) return true; 21 | 22 | for(int i = 1; i <= l2 - l1; i++){ 23 | //remove 24 | h2[s2.charAt(i - 1) - 'a'] -= 1; 25 | //add 26 | h2[s2.charAt(i + l1 - 1) - 'a'] += 1; 27 | 28 | if(Arrays.equals(h1, h2)) return true; 29 | } 30 | 31 | return false; 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /solutions/day05/solution_javascript.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s1 3 | * @param {string} s2 4 | * @return {boolean} 5 | */ 6 | var checkInclusion = function(s1, s2) { 7 | const areVectorsEqual = (a, b) => { 8 | for (let i = 0; i < 26; i++) { 9 | if (a[i] !== b[i]) return false; 10 | } 11 | return true; 12 | }; 13 | 14 | if (s2.length < s1.length) return false; 15 | 16 | let f1 = new Array(26).fill(0); // f1 is the frequency array for s1 17 | for (let char of s1) { 18 | f1[char.charCodeAt(0) - 'a'.charCodeAt(0)]++; 19 | } 20 | 21 | let f2 = new Array(26).fill(0); // f2 is the frequency array for the sliding window in s2 22 | let i = 0, j = 0; 23 | 24 | while (j < s2.length) { 25 | f2[s2[j].charCodeAt(0) - 'a'.charCodeAt(0)]++; 26 | 27 | if (j - i + 1 === s1.length) { 28 | if (areVectorsEqual(f1, f2)) return true; 29 | } 30 | 31 | if (j - i + 1 < s1.length) { 32 | j++; 33 | } else { 34 | f2[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)]--; 35 | i++; 36 | j++; 37 | } 38 | } 39 | 40 | return false; 41 | }; 42 | -------------------------------------------------------------------------------- /solutions/day06/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day06/.gitkeep -------------------------------------------------------------------------------- /solutions/day06/Readme.md: -------------------------------------------------------------------------------- 1 | ### Solution Approach 2 | 3 | Lets assume longer string be s1 and shorter string be s2 4 | In order to be similar senetences 5 | - Complete s2 should be a prefix of s1 6 | 7 | Ex: s1 = ["My","Name","is","Rock"] s2 = ["My","Name"] 8 | - Complete s2 should be a suffic of s2 9 | 10 | Ex: s1 = ["My","Name","is","Rock"] s2 = ["is","Rock"] 11 | - Entire s2 should be sum of longest matching prefix and longest Matching suffix 12 | 13 | Ex: s1 = ["My","Name","is","Rock"] s2 = ["My","Rock"] 14 | 15 | Longest Matching Prefix pf: "My" 16 | 17 | Longest Mathcing Suffix sf: "Name" 18 | 19 | pf+sf == s2 20 | 21 | In any other cases it will not be a similar senetences 22 | 23 | 24 | 25 | use stringstream to build a stream of characters and split the words based on whitespace (you can use any other utils as well) 26 | use two pointers to find longest matching prefix and suffixe lengths and 27 | check if it length of sums greater than or equal to length of s2 28 | 29 | ### Time complexity: 30 | - O(∣sentence1∣+∣sentence2∣) 31 | 32 | ### Space complexity: 33 | - O(∣sentence1∣+∣sentence2∣) 34 | 35 | ### Tags 36 | Two Pointer , Strings 37 | -------------------------------------------------------------------------------- /solutions/day06/solution_cpp.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool areSentencesSimilar(string sentence1, string sentence2) { 4 | vector v1,v2; 5 | stringstream ss1(sentence1); 6 | stringstream ss2(sentence2); 7 | string s; 8 | while (ss1>>s) { 9 | v1.push_back(s); 10 | } 11 | while (ss2>>s) { 12 | v2.push_back(s); 13 | } 14 | 15 | if(v2.size() > v1.size()) swap(v1,v2); 16 | int l = 0 , r = 0 , n1 = v1.size() , n2 = v2.size(); 17 | while(l < v2.size() and v1[l] == v2[l]) l++; 18 | while(r < v2.size() and v1[n1-1-r] == v2[n2-1-r]) r++; 19 | 20 | return l+r >= n2; 21 | } 22 | 23 | 24 | }; 25 | 26 | // solution approach in readme.md -------------------------------------------------------------------------------- /solutions/day06/solution_java.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean areSentencesSimilar(String sentence1, String sentence2) { 3 | 4 | String[] words1 = sentence1.split(" "); 5 | String[] words2 = sentence2.split(" "); 6 | 7 | 8 | if (words1.length > words2.length) { 9 | String[] temp = words1; 10 | words1 = words2; 11 | words2 = temp; 12 | } 13 | 14 | int l1 = words1.length; 15 | int l2 = words2.length; 16 | 17 | 18 | int prefixLen = 0; 19 | while (prefixLen < l1 && words1[prefixLen].equals(words2[prefixLen])) { 20 | prefixLen++; 21 | } 22 | 23 | 24 | int suffixLen = 0; 25 | while (suffixLen < l1 && words1[l1 - 1 - suffixLen].equals(words2[l2 - 1 - suffixLen])) { 26 | suffixLen++; 27 | } 28 | 29 | 30 | return prefixLen + suffixLen >= l1; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /solutions/day06/solution_python.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def areSentencesSimilar(self, sentence_1: str, sentence_2: str) -> bool: 3 | # Split the sentences into words 4 | sentence_1_split = sentence_1.split() 5 | sentence_2_split = sentence_2.split() 6 | 7 | # Ensure sentence_1_split is the longer or equal length sentence 8 | if len(sentence_2_split) > len(sentence_1_split): 9 | sentence_1_split, sentence_2_split = sentence_2_split, sentence_1_split 10 | 11 | l, r = 0, 0 12 | sen_1_len, sen_2_len = len(sentence_1_split), len(sentence_2_split) 13 | 14 | # Count matching words from the start 15 | while l < len(sentence_2_split) and sentence_1_split[l] == sentence_2_split[l]: 16 | l += 1 17 | 18 | # Count matching words from the end 19 | while r < len(sentence_2_split) and sentence_1_split[sen_1_len - 1 - r] == sentence_2_split[sen_2_len - 1 - r]: 20 | r += 1 21 | 22 | # Check if the total number of matching words is at least the length of the shorter sentence 23 | return l + r >= sen_2_len 24 | 25 | 26 | 27 | 28 | import unittest 29 | 30 | class TestSolution(unittest.TestCase): 31 | def setUp(self): 32 | self.solution = Solution() 33 | 34 | def test_are_sentences_similar(self): 35 | # Test cases 36 | self.assertTrue(self.solution.areSentencesSimilar("My name is Jack", "My name is")) 37 | self.assertTrue(self.solution.areSentencesSimilar("Hello world", "Hello")) 38 | self.assertFalse(self.solution.areSentencesSimilar("Hello world", "world Hello")) 39 | self.assertTrue(self.solution.areSentencesSimilar("I love programming", "I love")) 40 | self.assertFalse(self.solution.areSentencesSimilar("I love programming", "programming love I")) 41 | 42 | if __name__ == '__main__': 43 | unittest.main() -------------------------------------------------------------------------------- /solutions/day07/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day07/.gitkeep -------------------------------------------------------------------------------- /solutions/day07/KrounositySolution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minLength(String s) { 3 | 4 | // Faster than Stack<> 5 | Deque stack = new ArrayDeque<>(); 6 | 7 | // For each character from left to right in input string. 8 | for (char ch : s.toCharArray()) { 9 | 10 | // Pushing the character in stack. 11 | stack.push(ch); 12 | 13 | // Whether the character has been removed in the current iteration or not. (Set 14 | // "removed" to "true" as default). 15 | boolean removed = true; 16 | 17 | // Iterating for whether "removed" or not AND stack has atleast 2 elements. 18 | while (stack.size() > 1 && removed) { 19 | 20 | // Fetching first character in stack. 21 | char top = stack.pop(); 22 | 23 | // Checking second character and first character whether they are to be popped 24 | // or not. 25 | 26 | // If so, we remove the 2nd character too. 27 | if ((stack.peek() == 'A' && top == 'B') || (stack.peek() == 'C' && top == 'D')) 28 | stack.pop(); 29 | else { 30 | 31 | // Else, we push the 1st element at the top again. 32 | stack.push(top); 33 | 34 | // Setting removed to false. 35 | removed = false; 36 | } 37 | } 38 | } 39 | 40 | // Returning length of string, i.e., stack's size. 41 | return stack.size(); 42 | } 43 | } -------------------------------------------------------------------------------- /solutions/day07/Readme.md: -------------------------------------------------------------------------------- 1 | ### Solution Approach 2 | This problem involves reducing a string by repeatedly removing the substrings "AB" or "CD" whenever they appear. The goal is to find the minimum possible length of the string after all such removals. 3 | 4 | ### Approach 5 | Use a stack to simulate the removals: 6 | - Push characters onto the stack. 7 | - If "A" is followed by "B" or "C" is followed by "D", remove them (pop from the stack). 8 | - After processing the string, the size of the stack will be the minimum length of the string. 9 | 10 | ### Time complexity: 11 | - O(n) 12 | 13 | ### Space complexity: 14 | - O(n) 15 | 16 | ### Tags 17 | Stack, Strings -------------------------------------------------------------------------------- /solutions/day07/solutionInConstantSpace.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minLength(string s) { 4 | int writeIdx = 0; // Acts like the stack pointer 5 | for (char currentChar : s) { 6 | if (writeIdx > 0 && 7 | ((s[writeIdx - 1] == 'A' && currentChar == 'B') || 8 | (s[writeIdx - 1] == 'C' && currentChar == 'D'))) { 9 | writeIdx--; // Remove the last character (pop) 10 | } else { 11 | s[writeIdx++] = currentChar; // Add the current character (push) 12 | } 13 | } 14 | return writeIdx; // Size of the remaining valid string 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /solutions/day07/solution_cpp.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minLength(string s) { 4 | stack st; 5 | for(int i = 0 ; i < s.length() ; i++){ 6 | if(st.empty()){ 7 | st.push(s[i]); 8 | } 9 | else if(s[i] == 'B' and st.top() == 'A'){ 10 | st.pop(); 11 | } 12 | else if(s[i] == 'D' and st.top() == 'C'){ 13 | st.pop(); 14 | } 15 | else{ 16 | st.push(s[i]); 17 | } 18 | } 19 | return st.size(); 20 | } 21 | }; 22 | 23 | // TC : O(N) Sc : O(N) -------------------------------------------------------------------------------- /solutions/day07/solution_java.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minLength(String s) { 3 | Stack st = new Stack<>(); 4 | st.push(s.charAt(0)); 5 | 6 | for(int i = 1; i < s.length(); i++){ 7 | Character curr = s.charAt(i); 8 | 9 | if(st.empty()){ 10 | st.push(curr); 11 | continue; 12 | } 13 | Character top = st.peek(); 14 | 15 | if(top == 'A' && curr == 'B'){ 16 | st.pop(); 17 | } 18 | else if(top == 'C' && curr == 'D'){ 19 | st.pop(); 20 | } 21 | else{ 22 | st.push(curr); 23 | } 24 | } 25 | 26 | return st.size(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /solutions/day07/solution_python.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minLength(self, s: str) -> int: 3 | stack = [] # Initialize an empty stack to keep track of characters 4 | 5 | # Iterate over each character in the string 's' 6 | for c in s: 7 | if not stack: # If empty, add the character 8 | stack.append(c) 9 | continue 10 | 11 | # If current char is 'B' and the top is 'A', 12 | # forms "AB",remove 'A' to simulate removal of "AB" 13 | if c == "B" and stack[-1] == "A": 14 | stack.pop() 15 | 16 | # If current char is 'D' and the top is 'C', 17 | # forms "CD",remove 'C' to simulate removal of "D" 18 | elif c == "D" and stack[-1] == "C": 19 | stack.pop() 20 | 21 | else: # neither "AB" nor "CD" ,add the char to the stack 22 | stack.append(c) 23 | 24 | return len(stack) -------------------------------------------------------------------------------- /solutions/day08/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day08/.gitkeep -------------------------------------------------------------------------------- /solutions/day08/README: -------------------------------------------------------------------------------- 1 | # Minimum Swaps to Balance Brackets USING PYTHON 2 | 3 | ## Overview 4 | This algorithm determines whether a given string is a valid palindrome, ignoring non-alphanumeric characters and case differences. 5 | 6 | ## Explanation 7 | 8 | ### Two Pointers 9 | - Two pointers (left and right) are used to compare characters from the start and end of the string. 10 | 11 | ### Loop 12 | We iterate while left is less than right: 13 | 14 | 1. **If character at left is not alphanumeric**: 15 | - Move left to the right. 16 | 17 | 2. **If character at right is not alphanumeric**: 18 | - Move right to the left. 19 | 20 | 3. **If both are alphanumeric**: 21 | - **If characters don't match (after converting to lowercase)**: 22 | - Return false (not a palindrome). 23 | 24 | - **If they match**: 25 | - Move left to the right and right to the left. 26 | 27 | ### Return 28 | If the loop completes without finding any mismatches, return true (it's a palindrome). 29 | 30 | ### Helper Function 31 | **isAlphanumeric** 32 | - Uses a regular expression to check if a character is alphanumeric. 33 | This approach efficiently handles the palindrome check by: 34 | 35 | 1. Ignoring non-alphanumeric characters. 36 | 2. Performing case-insensitive comparison. 37 | 3. Using a single pass through the string with two pointers. 38 | -------------------------------------------------------------------------------- /solutions/day08/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSwaps(String s) { 3 | int size = 0; 4 | for (int i = 0; i < s.length(); i++) { 5 | char ch = s.charAt(i); 6 | if (ch == '[') 7 | size++; 8 | else if (size > 0) 9 | size--; 10 | } 11 | return (size + 1) / 2; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /solutions/day08/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minSwaps(string s) { 4 | int size = 0; // Counter for unmatched opening brackets 5 | int n = s.size(); // Get the length of the string 6 | 7 | // Iterate through each character in the string 8 | for (int i = 0; i < n; i++) { 9 | char ch = s[i]; 10 | if (ch == '[') { 11 | size++; // Increase counter for an opening bracket 12 | } else if (size > 0) { 13 | size--; // Match with an unmatched opening bracket 14 | } 15 | // If size is 0 or negative, it means we have more closing brackets 16 | // than opening brackets so far. 17 | } 18 | 19 | // Calculate the number of swaps needed to balance the string 20 | // (size + 1) / 2 gives us the minimum swaps needed 21 | return (size + 1) / 2; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /solutions/day08/solution.go: -------------------------------------------------------------------------------- 1 | package leetcode_project 2 | 3 | import ( 4 | "regexp" 5 | "strings" 6 | ) 7 | 8 | func isPalindrome(s string) bool { 9 | left, right := 0, len(s)-1 10 | 11 | for left < right { 12 | // Skip non-alphanumeric characters from the left 13 | if !isAlphanumeric(string(s[left])) { 14 | left += 1 15 | // Skip non-alphanumeric characters from the right 16 | } else if !isAlphanumeric(string(s[right])) { 17 | right -= 1 18 | } else { 19 | // Compare characters (case-insensitive) 20 | if strings.ToLower(string(s[left])) != strings.ToLower(string(s[right])) { 21 | return false 22 | } 23 | // Move both pointers inward 24 | left += 1 25 | right -= 1 26 | } 27 | } 28 | return true 29 | } 30 | 31 | func isAlphanumeric(str string) bool { 32 | var alphanumeric = regexp.MustCompile("^[a-zA-Z0-9]*$") 33 | return alphanumeric.MatchString(str) 34 | } -------------------------------------------------------------------------------- /solutions/day08/solution_java.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSwaps(String s) { 3 | Stack st = new Stack<>(); 4 | int ans = 0; 5 | for(int i = 0;i < s.length(); i++){ 6 | Character temp = s.charAt(i); 7 | if(temp == '['){ 8 | st.push(temp); 9 | }else{ 10 | if(!st.isEmpty()){ 11 | st.pop(); 12 | }else{ 13 | ans++; 14 | } 15 | } 16 | } 17 | 18 | return (ans + 1) / 2; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /solutions/day08/solution_python.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSwaps(self, s: str) -> int: 3 | stack = [] 4 | ans = 0 5 | 6 | for char in s: 7 | if char == '[': 8 | stack.append(char) 9 | else: # char == ']' 10 | if stack: 11 | stack.pop() 12 | else: 13 | ans += 1 14 | 15 | return (ans + 1) // 2 16 | -------------------------------------------------------------------------------- /solutions/day09/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day09/.gitkeep -------------------------------------------------------------------------------- /solutions/day09/Readme.md: -------------------------------------------------------------------------------- 1 | # Minimum Add to make Parentheses Valid Problem 🧩 2 | 3 | ## Problem Statement 4 | 5 | Given a string `s` consisting of `'('` and `')'` characters, the task is to determine the minimum number of parentheses that must be added to the string to make it valid. 6 | 7 | A string is valid if: 8 | - Open parentheses `'('` must be closed by the corresponding closing parentheses `')'`. 9 | - Open parentheses must be closed in the correct order. 10 | 11 | ## Function Description 12 | 13 | The function `minAddToMakeValid` processes the string and returns the number of unmatched opening and closing parentheses that need to be added to make the string valid. 14 | 15 | 16 | ## Explanation 17 | 18 | 1. **openings**: This variable counts the number of unmatched opening parentheses `'('`. 19 | 2. **closings**: This variable counts the number of unmatched closing parentheses `')'`. 20 | 3. The function iterates through the string `s`: 21 | - If an opening parenthesis `'('` is encountered, it increments the `openings` count. 22 | - If a closing parenthesis `')'` is encountered: 23 | - It first checks if there is an unmatched opening parenthesis. If there is, it decrements the `openings` count, effectively forming a valid pair. 24 | - If no unmatched opening exists, it increments the `closings` count to account for the unmatched closing parenthesis. 25 | 4. The result is the sum of unmatched `openings` and `closings`, representing the minimum number of parentheses that need to be added. 26 | 27 | ## Time Complexity ⏱️ 28 | 29 | - **O(n)** where `n` is the length of the string `s`. 30 | - The function iterates through the string exactly once, processing each character in constant time `O(1)`. 31 | 32 | ## Space Complexity 💾 33 | 34 | - **O(1)** (constant space). 35 | - The function uses only a fixed amount of extra space: two integer variables (`openings` and `closings`). 36 | - No additional space is required that grows with the input size, making the space complexity constant. 37 | 38 | ## Example 39 | 40 | **Input**: `s = "())"` 41 | 42 | **Output**: `1` 43 | 44 | - Explanation: The second `)` has no matching opening parenthesis. We need to add one `'('` to make the string valid. 45 | 46 | **Input**: `s = "((("` 47 | 48 | **Output**: `3` 49 | 50 | - Explanation: All three opening parentheses are unmatched. We need to add three `)` to make the string valid. 51 | 52 | ## Conclusion 53 | 54 | The function `minAddToMakeValid` efficiently computes the number of parentheses to add to make the string valid by keeping track of unmatched opening and closing parentheses as it scans the input string. It operates in linear time and uses constant space, making it optimal for large inputs. 55 | -------------------------------------------------------------------------------- /solutions/day09/krounosity_solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minAddToMakeValid(String s) { 3 | 4 | // Brackets to be paired. 5 | int pair = 0; 6 | 7 | // Brackets which are not paired and we will have to add brackets for them. 8 | int cannotPair = 0; 9 | 10 | // Iterating through the string. 11 | for(int i=0;i 0) c--; 11 | else b++; 12 | } 13 | } 14 | return c+b; 15 | } 16 | }; 17 | // TC : O(N) SC : O(1) 18 | -------------------------------------------------------------------------------- /solutions/day09/solution_java.java: -------------------------------------------------------------------------------- 1 | package solutions.day09; 2 | 3 | public class solution_java{ 4 | public int minAddToMakeValid(String s) { 5 | int openings = 0; //counts the opening parenthesis in the string. 6 | int closings = 0; //counts the closing parenthesis. 7 | for (int i = 0; i < s.length(); i++) { 8 | if (s.charAt(i) == '(') //checks if the the character at index is an opening parenthesis. 9 | openings++; //if true, increment it by 1. 10 | else { //else, it's a closing parenthesis. 11 | if (openings > 0) //first check if there is any opening parenthesis in the string. 12 | openings--; //if found a good pair, decrement openings. 13 | else 14 | closings++; //otherwise, increment the closings. 15 | } 16 | } 17 | return openings + closings; //adding openings and closings - gets how many are not paired. 18 | } 19 | } -------------------------------------------------------------------------------- /solutions/day09/solution_python.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minAddToMakeValid(self, s: str) -> int: 3 | open_needed = 0 4 | close_needed = 0 5 | 6 | for char in s: 7 | if char == '(': 8 | # Unmatched opening parenthesis 9 | open_needed += 1 10 | elif char == ')': 11 | # If there's an unmatched opening parenthesis, match it 12 | if open_needed > 0: 13 | open_needed -= 1 14 | else: 15 | # Otherwise, we need an extra opening parenthesis 16 | close_needed += 1 17 | 18 | # The total moves required 19 | return open_needed + close_needed 20 | -------------------------------------------------------------------------------- /solutions/day10/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day10/.gitkeep -------------------------------------------------------------------------------- /solutions/day10/maxWidthRamp.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxWidthRamp(vector& nums) 4 | { 5 | stack s; 6 | for(int i=0;inums[i]) 11 | s.push(i); 12 | } 13 | int ma = 0; 14 | for(int i=nums.size()-1;i>0;i--) 15 | { 16 | while(!s.empty() && nums[s.top()]<=nums[i]) 17 | { 18 | ma = max(ma,i-s.top()); 19 | s.pop(); 20 | } 21 | } 22 | return ma; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /solutions/day10/solution_java.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxWidthRamp(int[] nums) { 3 | int ans = 0; 4 | int n = nums.length; 5 | Stack stack = new Stack<>(); 6 | for (int i = 0; i < n; i++) { 7 | if (stack.isEmpty() || nums[stack.peek()] > nums[i]) { 8 | stack.push(i); 9 | } 10 | } 11 | for (int i = n - 1; i >= 0; i --) { 12 | while (!stack.isEmpty() && nums[stack.peek()] <= nums[i]) { 13 | ans = Math.max(ans, i - stack.pop()); 14 | } 15 | } 16 | return ans; 17 | } 18 | } -------------------------------------------------------------------------------- /solutions/day10/solution_python.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxWidthRamp(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | stack = [] 5 | 6 | # Step 1: Build a decreasing stack of indices 7 | for i in range(n): 8 | if not stack or nums[stack[-1]] > nums[i]: 9 | stack.append(i) 10 | 11 | maxWidth = 0 12 | 13 | # Step 2: Traverse from the end and find maximum width ramp 14 | for j in range(n - 1, -1, -1): 15 | while stack and nums[stack[-1]] <= nums[j]: 16 | maxWidth = max(maxWidth, j - stack.pop()) 17 | 18 | return maxWidth 19 | 20 | 21 | # Explanation of the Code: 22 | # Initialization: 23 | 24 | # n stores the length of the input list nums. 25 | # stack is initialized as an empty list to hold indices. 26 | # Building the Decreasing Stack: 27 | 28 | # The first loop iterates through the list. If the stack is empty or the current number is less than the number at the index stored at the top of the stack, the current index is pushed onto the stack. This ensures that the stack contains indices of elements in a decreasing order. 29 | # Finding the Maximum Width Ramp: 30 | 31 | # The second loop iterates backward through the list. For each index j, it checks if the current number is greater than or equal to the number at the index stored at the top of the stack. If so, it calculates the width of the ramp and updates maxWidth if the current width is greater than the previously recorded maximum. The index is then popped from the stack. 32 | # Return Statement: Finally, the method returns the maximum width found. 33 | -------------------------------------------------------------------------------- /solutions/day11/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day11/.gitkeep -------------------------------------------------------------------------------- /solutions/day11/solution_java.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int smallestChair(int[][] times, int targetFriend) { 3 | int targetStart = times[targetFriend][0]; 4 | Arrays.sort(times, (a, b) -> a[0] - b[0]); 5 | 6 | PriorityQueue available = new PriorityQueue<>(); 7 | for (int i = 0; i < times.length; ++ i) { 8 | available.offer(i); 9 | } 10 | 11 | PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); 12 | 13 | for (int i = 0; i < times.length; ++ i) { 14 | while (!pq.isEmpty() && pq.peek()[0] <= times[i][0]) { 15 | available.offer(pq.poll()[1]); 16 | } 17 | 18 | if (times[i][0] == targetStart) { 19 | break; 20 | } 21 | 22 | pq.offer(new int[]{times[i][1], available.poll()}); 23 | } 24 | 25 | return available.peek(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /solutions/day11/soultion_cpp.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int smallestChair(vector>& times, int targetFriend) { 4 | int n = times.size(); 5 | priority_queue, vector>, 6 | greater>> 7 | occChair; 8 | priority_queue, greater> freeChair; 9 | 10 | int tar = times[targetFriend][0]; 11 | sort(times.begin(), times.end()); 12 | 13 | int chair = 0; 14 | 15 | for (int i = 0; i < n; i++) { 16 | int arr = times[i][0]; 17 | int dep = times[i][1]; 18 | 19 | while (!occChair.empty() && occChair.top().first <= arr) { 20 | freeChair.push(occChair.top().second); 21 | occChair.pop(); 22 | } 23 | 24 | if (freeChair.empty()) { 25 | occChair.push({dep, chair}); 26 | if (arr == tar) { 27 | return chair; 28 | } 29 | chair++; 30 | } else { 31 | int minChair = freeChair.top(); 32 | freeChair.pop(); 33 | if (arr == tar) { 34 | return minChair; 35 | } 36 | occChair.push({dep, minChair}); 37 | } 38 | } 39 | return -1; 40 | } 41 | }; -------------------------------------------------------------------------------- /solutions/day12/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day12/.gitkeep -------------------------------------------------------------------------------- /solutions/day12/Readme.md: -------------------------------------------------------------------------------- 1 | # Divide Intervals into Minimum Number of Groups 🧩 2 | 3 | ## Problem Statement 4 | 5 | In a given a list of intervals, where each interval is represented as `[start, end]`. Your task is to group these intervals so that no two intervals in the same group overlap. Return the `minimum number` of groups required. 6 | 7 | ## Function Description 8 | **Function Name**: `minGroups(intervals)` 9 | 10 | - Input: A list of intervals, where each interval is an array with inclusive start and end times. 11 | - Output: The minimum number of groups required such that no intervals overlap within the same group. 12 | 13 | ## Explanation 14 | 15 | 1. **Sort the Intervals**: Separate the `start times` and `end times` of the intervals and sort both lists. 16 | 2. **Two-Pointer Technique**: Use two pointers to track the start and end times: 17 | - One pointer tracks the current `starting` interval. 18 | - The other pointer tracks the current `ending` interval. 19 | 3. **Count Overlaps**: As you iterate through the sorted lists: 20 | - When a new interval starts before an existing one ends, increment the count of overlapping intervals. 21 | - When an interval ends, decrement the count of overlapping intervals. 22 | 4. **Track Maximum Overlaps**: Maintain a variable to keep track of the maximum number of overlapping intervals at any point. This maximum will represent the minimum number of groups needed. 23 | 24 | ## Time Complexity ⏱️ 25 | Sorting the intervals takes `O(n log n)`, where n is the number of intervals. 26 | The traversal using the two-pointer technique is `O(n)`. 27 | Overall complexity: `O(n log n)`. 28 | 29 | ## Space Complexity 💾 30 | The extra space used for storing start and end times is `O(n)`. 31 | Overall space complexity: `O(n)`. 32 | 33 | ## Example 34 | `Input: [[1, 5], [3, 7], [6, 10], [8, 12]]` 35 | `Output: 2` 36 | 37 | Explanation: 38 | - Group 1: [1, 5], [6, 10] 39 | - Group 2: [3, 7], [8, 12] 40 | 41 | ## Conclusion 42 | This solution efficiently divides intervals into the minimum number of non-overlapping groups by sorting the start and end times and utilizing a two-pointer approach to track overlaps. This approach provides an optimal and scalable solution for the problem, regardless of the programming language used. -------------------------------------------------------------------------------- /solutions/day12/solution_cpp.cpp: -------------------------------------------------------------------------------- 1 | #include // This includes most standard libraries 2 | using namespace std; // Use the standard namespace 3 | 4 | class Solution { 5 | public: 6 | int minGroups(vector>& intervals) { 7 | vector> vp; // Create a vector to store starting and ending intervals separately. 8 | 9 | for (int i = 0; i < intervals.size(); i++) { 10 | vp.push_back({intervals[i][0], 1}); // Push the starting intervals into the vector vp. 11 | vp.push_back({intervals[i][1] + 1, -1}); // Push the ending intervals into the vector vp. 12 | } 13 | 14 | sort(vp.begin(), vp.end()); // Sort the vector vp. 15 | 16 | int maxi = 1; // This is for the final answer 17 | int cnt = 0; // This is for counting 18 | 19 | for (auto it : vp) { 20 | int type = it.second; // Iterate each point; if it is 1, add 1 to cnt, if -1, subtract 1 from cnt 21 | cnt += type; 22 | maxi = max(maxi, cnt); // Store the max value of cnt 23 | } 24 | 25 | return maxi; // Return maxi 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /solutions/day12/solution_java.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int smallestChair(int[][] times, int targetFriend) { 3 | int n = times.length; 4 | int targetFriendStartTime = times[targetFriend][0]; 5 | int seatNo = 0; 6 | Queue availableSeats = new PriorityQueue<>(); 7 | for (int i = 0; i < n; i++) { 8 | availableSeats.add(i); 9 | } 10 | List timeList = new ArrayList<>(); 11 | for (int i = 0; i < n; i++) { 12 | if (times[i][0] <= targetFriendStartTime) { 13 | timeList.add(new Triplet(i, times[i][0], true)); 14 | if (times[i][1] <= targetFriendStartTime) { 15 | timeList.add(new Triplet(i, times[i][1], false)); 16 | } 17 | } 18 | } 19 | Collections.sort(timeList, (t1, t2) -> t1.time != t2.time ? t1.time - t2.time : t1.isStart ? 1 : -1); 20 | int[] seats = new int[n]; 21 | 22 | for (int i = 0; i < timeList.size(); i++) { 23 | if (timeList.get(i).isStart == true) { 24 | seats[timeList.get(i).index] = availableSeats.poll(); 25 | } else { 26 | availableSeats.add(seats[timeList.get(i).index]); 27 | } 28 | } 29 | return seats[targetFriend]; 30 | } 31 | } 32 | 33 | class Triplet { 34 | int index; 35 | int time; 36 | boolean isStart; 37 | 38 | Triplet(int index, int time, boolean isStart) { 39 | this.index = index; 40 | this.time = time; 41 | this.isStart = isStart; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /solutions/day12/solution_python.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def minGroups(self, intervals: List[List[int]]) -> int: 5 | # Use seperate start and end time lists to keep track of the intervals 6 | start_times = sorted(interval[0] for interval in intervals) 7 | end_times = sorted(interval[1] for interval in intervals) 8 | 9 | # Use pointers to keep track of the current interval being processed 10 | start_pointer, end_pointer = 0, 0 11 | current_groups = 0 12 | max_groups = 0 13 | 14 | # Process the intervals by comparing start and end times 15 | while start_pointer < len(intervals): 16 | if start_times[start_pointer] <= end_times[end_pointer]: 17 | # When a new interval starts, increment the group count 18 | current_groups += 1 19 | start_pointer += 1 20 | else: 21 | # AWhen an interval ends, decrement the group count 22 | current_groups -= 1 23 | end_pointer += 1 24 | 25 | # Keep track of the maximum number of overlapping intervals 26 | max_groups = max(max_groups, current_groups) 27 | 28 | return max_groups 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /solutions/day13/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day13/.gitkeep -------------------------------------------------------------------------------- /solutions/day13/solution_java.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minGroups(int[][] intervals) { 3 | int n = intervals.length; 4 | int[] start_times = new int[n]; 5 | int[] end_times = new int[n]; 6 | 7 | // Extract start and end times 8 | for (int i = 0; i < n; i++) { 9 | start_times[i] = intervals[i][0]; 10 | end_times[i] = intervals[i][1]; 11 | } 12 | 13 | // Sort start and end times 14 | Arrays.sort(start_times); 15 | Arrays.sort(end_times); 16 | 17 | int end_ptr = 0, group_count = 0; 18 | 19 | // Traverse through the start times 20 | for (int start : start_times) { 21 | if (start > end_times[end_ptr]) { 22 | end_ptr++; 23 | } else { 24 | group_count++; 25 | } 26 | } 27 | 28 | return group_count; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /solutions/day13/uniqueEmailAddress/Readme.md: -------------------------------------------------------------------------------- 1 | To solve this problem, we need to normalize the local names of the email addresses while keeping the domain names intact. The steps are: 2 | 3 | 1. Split each email address into local and domain parts using @. 4 | 2. Handle the local name: 5 | a. Ignore everything after +. 6 | b. Remove all . characters. 7 | 3. Combine the modified local name with the original domain name. 8 | 4. Use a HashSet to store all unique email addresses. HashSet is used because it automatically handles duplicates. 9 | 5. Return the size of the HashSet as the result. -------------------------------------------------------------------------------- /solutions/day13/uniqueEmailAddress/Solution.java: -------------------------------------------------------------------------------- 1 | package uniqueEmailAddress; 2 | 3 | import java.util.HashSet; 4 | // 929. Unique Email Addresses 5 | 6 | public class Solution { 7 | 8 | public int uniqueEmail(String[] emails){ 9 | HashSet hs = new HashSet<>(); 10 | int n = emails.length; 11 | 12 | for(int i=0;i& nums, int k) { 47 | long long int ans = 0; 48 | priority_queue pq; 49 | for (auto& i : nums) { 50 | pq.push(i); 51 | } 52 | 53 | while (k--) { 54 | int maxElement = pq.top(); 55 | ans += maxElement; 56 | pq.pop(); 57 | pq.push(ceil(maxElement / 3.0)); 58 | } 59 | return ans; 60 | } 61 | }; 62 | ``` 63 | 64 | ### Explanation of the Code: 65 | - **Input:** A vector of integers `nums` and an integer `k`. 66 | - **Priority Queue:** A max-heap (`priority_queue`) is used to store elements in descending order. 67 | - **Main Loop:** For each iteration (k times): 68 | - Extract the largest element from the heap (`pq.top()`). 69 | - Add it to the result (`ans`). 70 | - Replace the extracted element with its one-third value (rounded up) and push it back into the heap (`pq.push(ceil(maxElement / 3.0))`). 71 | - **Return Value:** The final result (`ans`) is returned after performing the `k` operations. 72 | 73 | ## Usage 74 | 75 | To use this solution, clone the repository and compile the solution with your favorite C++ compiler. You can pass different `nums` arrays and values of `k` to test the functionality. 76 | 77 | --- 78 | -------------------------------------------------------------------------------- /solutions/day14/solution_cpp.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long maxKelements(vector& nums, int k) { 4 | long long int ans = 0; 5 | priority_queue pq; 6 | for (auto& i : nums) { 7 | pq.push(i); 8 | } 9 | 10 | while (k--) { 11 | int maxElement = pq.top(); 12 | ans += maxElement; 13 | pq.pop(); 14 | pq.push(ceil(maxElement / 3.0)); 15 | } 16 | return ans; 17 | } 18 | }; -------------------------------------------------------------------------------- /solutions/day14/solution_java.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long maxKelements(int[] nums, int k) { 3 | long score = 0; 4 | Queue pq = new PriorityQueue<>((a, b) -> b-a); 5 | for(int num: nums) { 6 | pq.add(num); 7 | } 8 | int peek; 9 | while(k-- > 0) { 10 | peek = pq.poll(); 11 | score += peek; 12 | pq.add((peek+2)/3); 13 | } 14 | return score; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /solutions/day14/solution_py.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxKelements(self, nums: List[int], k: int) -> int: 3 | heapify(pq:=[-x for x in nums]) 4 | score=0 5 | for i in range(k): 6 | x=-heappop(pq) 7 | score+=x 8 | if x==1: 9 | score+=k-1-i 10 | break 11 | heappush(pq, -((x+2)//3)) 12 | return score 13 | -------------------------------------------------------------------------------- /solutions/day15/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day15/.gitkeep -------------------------------------------------------------------------------- /solutions/day15/Separate Black and White Balls.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long minimumSteps(String s) { 3 | int[] a = new int[s.length()]; 4 | long count=0; 5 | int n=0; 6 | for (int i = 0; i < s.length(); i++) { 7 | a[i]=s.charAt(i); 8 | if (a[i]==49) n++; //49 is ASCII value of 1 9 | else if (a[i]==48) count+=n; //48 is ASCII value of 0 10 | }return count; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /solutions/day15/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public long minimumSteps(String s) { 4 | //keep track of where the last '0' while itrating array 5 | int zeroPos = 0; 6 | // total number of swaps 7 | long swap = 0; 8 | char[] ch = s.toCharArray(); 9 | 10 | for (int i = 0; i < ch.length; i++) { 11 | if (ch[i] == '0') { 12 | // the number of swaps needed to bring this '0' to its correct position 13 | //it basically keep track of total 0's in array till current(i) position and then get count of 1's 14 | swap += i - zeroPos; 15 | 16 | // Increment zeroPos for keep track of zeros till current position for swap count 17 | zeroPos++; 18 | } 19 | } 20 | return swap; 21 | } 22 | } 23 | 24 | 25 | //Time Complexity :: O(n) 26 | // Space Complexity :: O(n) 27 | -------------------------------------------------------------------------------- /solutions/day15/Solution_cpp.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long minimumSteps(string s) { 4 | 5 | long l = s.size(); 6 | long count =0; 7 | long Zcount =0; //Variable to count zero 8 | long Count = 0; //Variable to count count swap number 9 | 10 | for(long i =l-1; i>=0; i--){ 11 | if(s[i] == '0'){ 12 | Zcount++; 13 | }else if(s[i] == '1'){ 14 | Count = Count + Zcount; 15 | } 16 | } 17 | 18 | return Count; 19 | } 20 | }; -------------------------------------------------------------------------------- /solutions/day15/shortEncodingofWords.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumLengthEncoding(self, words): 3 | # Sort words by length in descending order 4 | words.sort(key=len, reverse=True) 5 | encoded_length = 0 6 | suffix_map = {} 7 | 8 | # Create a map of suffixes 9 | for word in words: 10 | for i in range(len(word)): 11 | suffix = word[i:] 12 | suffix_map[suffix] = suffix_map.get(suffix, 0) + 1 13 | 14 | # Calculate the length of the shortest encoding 15 | for word in words: 16 | if suffix_map[word] == 1: # Only consider unique words 17 | encoded_length += len(word) + 1 # +1 for the '#' character 18 | 19 | return encoded_length 20 | -------------------------------------------------------------------------------- /solutions/day15/solution_java.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long minimumSteps(String s) { 3 | int i = s.length() - 1; 4 | long minOps = 0; 5 | while(i>= 0 && s.charAt(i) == '1') { 6 | i--; 7 | } 8 | if(i == -1) { 9 | return minOps; 10 | } 11 | int zeroIndex = i; 12 | while(i >= 0) { 13 | if(s.charAt(i) == '1') { 14 | minOps += zeroIndex - i; 15 | zeroIndex--; 16 | } 17 | i--; 18 | } 19 | return minOps; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /solutions/day15/solution_javascript.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | const minimumSteps = function(s) { 6 | let countSteps = 0; 7 | let numberOfOnes = 0; 8 | for (let i = 0; i < s.length; i++) { 9 | // Increment number of 1s found 10 | if (s[i] === '1') { 11 | numberOfOnes++; 12 | } else { 13 | // Increment the swap counter 14 | countSteps += numberOfOnes; 15 | } 16 | } 17 | return countSteps; 18 | }; -------------------------------------------------------------------------------- /solutions/day15/uniqueEmail.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numUniqueEmails(self, emails): 3 | unique_emails = set() 4 | 5 | for email in emails: 6 | local, domain = email.split('@') 7 | # Remove everything after '+' 8 | local = local.split('+')[0] 9 | # Remove all dots in the local part 10 | local = local.replace('.', '') 11 | # Recombine the local and domain parts 12 | unique_emails.add(local + '@' + domain) 13 | 14 | return len(unique_emails) 15 | -------------------------------------------------------------------------------- /solutions/day16/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day16/.gitkeep -------------------------------------------------------------------------------- /solutions/day16/Solution_cpp.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestDiverseString(int a, int b, int c) { 4 | priority_queue> pq; 5 | if (a > 0) pq.push({a, 'a'}); 6 | if (b > 0) pq.push({b, 'b'}); 7 | if (c > 0) pq.push({c, 'c'}); 8 | 9 | string result = ""; 10 | 11 | while (!pq.empty()) { 12 | auto [count1, char1] = pq.top(); 13 | pq.pop(); 14 | 15 | if (result.size() >= 2 && result.back() == char1 && result[result.size() - 2] == char1) { 16 | if (pq.empty()) break; // No valid characters left. 17 | 18 | auto [count2, char2] = pq.top(); 19 | pq.pop(); 20 | 21 | result += char2; 22 | count2--; 23 | 24 | if (count2 > 0) pq.push({count2, char2}); 25 | 26 | pq.push({count1, char1}); 27 | } else { 28 | result += char1; 29 | count1--; 30 | 31 | if (count1 > 0) pq.push({count1, char1}); 32 | } 33 | } 34 | 35 | return result; 36 | } 37 | }; -------------------------------------------------------------------------------- /solutions/day16/solution_java.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | class Solution { 4 | public String longestDiverseString(int a, int b, int c) { 5 | // Priority queue to store the characters and their counts. 6 | PriorityQueue pq = new PriorityQueue<>((x, y) -> y[0] - x[0]); 7 | if (a > 0) pq.offer(new int[]{a, 'a'}); 8 | if (b > 0) pq.offer(new int[]{b, 'b'}); 9 | if (c > 0) pq.offer(new int[]{c, 'c'}); 10 | 11 | StringBuilder result = new StringBuilder(); 12 | 13 | while (!pq.isEmpty()) { 14 | int[] first = pq.poll(); 15 | 16 | // Check if last two characters are the same. 17 | if (result.length() >= 2 && result.charAt(result.length() - 1) == first[1] && 18 | result.charAt(result.length() - 2) == first[1]) { 19 | 20 | if (pq.isEmpty()) break; // No more valid characters. 21 | 22 | // Pick the second character. 23 | int[] second = pq.poll(); 24 | result.append((char) second[1]); 25 | second[0]--; 26 | 27 | if (second[0] > 0) pq.offer(second); 28 | pq.offer(first); 29 | } else { 30 | result.append((char) first[1]); 31 | first[0]--; 32 | 33 | if (first[0] > 0) pq.offer(first); 34 | } 35 | } 36 | 37 | return result.toString(); 38 | } 39 | } -------------------------------------------------------------------------------- /solutions/day17/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day17/.gitkeep -------------------------------------------------------------------------------- /solutions/day17/Day17.py: -------------------------------------------------------------------------------- 1 | #670. Maximum Swap in python 2 | class Solution: 3 | def maximumSwap(self, num: int) -> int: 4 | # Convert the number to a list of characters for easy manipulation 5 | num_list = list(str(num)) 6 | 7 | # Track the last occurrence of each digit (0-9) 8 | last = {int(d): i for i, d in enumerate(num_list)} 9 | 10 | # Traverse the number from left to right 11 | for i, digit in enumerate(num_list): 12 | # Check for a larger digit to swap 13 | for d in range(9, int(digit), -1): 14 | if last.get(d, -1) > i: 15 | # Swap and return the new number 16 | num_list[i], num_list[last[d]] = num_list[last[d]], num_list[i] 17 | return int(''.join(num_list)) 18 | 19 | # If no swap occurred, return the original number 20 | return num 21 | -------------------------------------------------------------------------------- /solutions/day17/Readme.md: -------------------------------------------------------------------------------- 1 | # Maximum Swap 🔄 2 | 3 | ## Problem Statement 4 | 5 | You are given an integer num. You can swap two digits at most once to get the maximum valued number. 6 | Return the maximum valued number you can get. 7 | 8 | ## Function Description 9 | **Function Name**: `maximumSwap` 10 | 11 | - **Input**: A non-negative integer `num`. 12 | - **Output**: The largest possible number after at most one swap of two digits. 13 | 14 | ## Explanation 15 | 16 | ### 1. **Convert the Number into Digits**: 17 | - Extract the individual digits of the number by repeatedly taking the modulo (`% 10`) of the number and store them in a vector. 18 | - Since digits are extracted from least significant to most significant, reverse the vector to restore the original digit order. 19 | 20 | ### 2. **Find the Optimal Swap**: 21 | - Traverse the digits from left to right. For each digit, search for the largest digit that appears after it (and is larger than the current digit). 22 | - If such a larger digit is found, swap it with the current digit and break the loop, as only one swap is allowed. 23 | 24 | ### 3. **Reconstruct the Number**: 25 | - After performing the swap, reconstruct the number by combining the digits in the correct order. 26 | 27 | ### Time Complexity ⏱️ 28 | - The number of digits in `num` is `O(log10(num))`. 29 | - Extracting and reversing the digits takes `O(log10(num))`. 30 | - The nested loop to find the optimal swap takes `O((log10(num))^2)` since for each digit, you compare it with all subsequent digits. 31 | 32 | Thus, the overall **time complexity** is `O((log10(num))^2)`. 33 | 34 | ### Space Complexity 💾 35 | - The space complexity is `O(log10(num))` due to the storage of digits in the vector. 36 | 37 | ### JAVA Approach Explanation 38 | 39 | ### 1. **Convert the Number to a String**: 40 | - The integer `num` is converted to a string to facilitate easy manipulation of its digits. 41 | 42 | ### 2. **Character Array Conversion**: 43 | - The string representation of the number is converted into a character array, allowing direct access to individual digits for swapping. 44 | 45 | ### 3. **Iterate Through Each Digit**: 46 | - An outer loop iterates through each digit of the number, starting from the leftmost digit. 47 | 48 | ### 4. **Finding the Maximum Digit**: 49 | - For each digit at index `i`, an inner loop searches for the largest digit to the right. If a larger digit is found, its value and index are recorded. 50 | 51 | ### 5. **Performing the Swap**: 52 | - If a larger digit is identified, a swap occurs between the current digit and the maximum digit found. This is designed to yield the maximum number with a single swap. 53 | 54 | ### 6. **Break After the First Swap**: 55 | - The loop exits after the first swap to maximize the number, as further swaps are unnecessary. 56 | 57 | ### 7. **Convert Back and Return**: 58 | - Finally, the modified character array is converted back into an integer and returned as the result. 59 | 60 | ### Time Complexity ⏱️ 61 | - The overall **time complexity** is `O((n)^2)`. This is due to the nested loops used to find the maximum digit. 62 | 63 | ### Space Complexity 💾 64 | - The space complexity is `O(n)` for storing the character array representing the digits of the number. -------------------------------------------------------------------------------- /solutions/day17/day17.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumSwap(int num) { 4 | vector nums; 5 | while(num){ 6 | nums.push_back(num%10); 7 | num/=10; 8 | } 9 | 10 | int max_idx ; 11 | reverse(nums.begin(),nums.end()); 12 | int size = nums.size(); 13 | for(int i=0;i=nums[max_idx]){ 18 | 19 | max_idx = j; 20 | } 21 | } 22 | if(max_idx!=i && nums[max_idx]!=nums[i]){ 23 | 24 | swap(nums[i],nums[max_idx]); 25 | break; 26 | } 27 | 28 | } 29 | num = 0; 30 | for(int i = 0; i < size; i++) { 31 | num = num * 10 + nums[i]; 32 | } 33 | return num; 34 | } 35 | }; -------------------------------------------------------------------------------- /solutions/day17/day17.java: -------------------------------------------------------------------------------- 1 | // Easy approach for beginners 2 | class Solution 3 | { 4 | public int maximumSwap(int num) 5 | { 6 | // Convert the integer to a string to easily manipulate individual digits. 7 | String n = Integer.toString(num); 8 | // Convert the string to a character array to facilitate swapping. 9 | char[] c = n.toCharArray(); 10 | int len = c.length; 11 | for(int i = 0; i < len; i++) 12 | { 13 | // Initialize max to the current character and max_ind to its index. 14 | char max = c[i]; 15 | int max_ind = i; 16 | // Check for any larger digits to the right of the current digit. 17 | for(int j = i + 1; j < len; j++) 18 | { 19 | // Update max and max_ind if we find a larger digit. 20 | if(max <= c[j]) 21 | { 22 | max = c[j]; 23 | max_ind = j; 24 | } 25 | } 26 | // If max is different from the current digit, we found a larger digit to swap with. 27 | if(max != c[i]) 28 | { 29 | char temp = c[i]; 30 | c[i] = c[max_ind]; 31 | c[max_ind] = temp; 32 | break; 33 | } 34 | } 35 | // Convert the array to an Integer and return it 36 | String res = new String(c); 37 | return Integer.parseInt(res); 38 | } 39 | } -------------------------------------------------------------------------------- /solutions/day18/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day18/.gitkeep -------------------------------------------------------------------------------- /solutions/day18/solution_cpp.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void backtrack(const vector &nums, int index, int currentOR, int maxOR, int &count) 5 | { 6 | if (currentOR == maxOR) 7 | { 8 | count++; 9 | } 10 | 11 | for (int i = index; i < nums.size(); ++i) 12 | { 13 | backtrack(nums, i + 1, currentOR | nums[i], maxOR, count); 14 | } 15 | } 16 | 17 | int countMaxOrSubsets(vector &nums) 18 | { 19 | int maxOR = 0; 20 | 21 | // Step 1: Compute the maximum OR 22 | for (int num : nums) 23 | { 24 | maxOR |= num; 25 | } 26 | 27 | int count = 0; 28 | // Step 2: Backtrack to count the subsets 29 | backtrack(nums, 0, 0, maxOR, count); 30 | 31 | return count; 32 | } 33 | }; -------------------------------------------------------------------------------- /solutions/day18/solution_java.java: -------------------------------------------------------------------------------- 1 | package solutions.day18; 2 | 3 | class Solution { 4 | public int countMaxOrSubsets(int[] nums) { 5 | int maxOr = 0; 6 | for(int x : nums){ 7 | maxOr |= x; 8 | } 9 | 10 | int currOr = 0; 11 | 12 | return count(0,nums,currOr,maxOr); 13 | } 14 | 15 | public int count(int idx, int[] nums, int currOr, int maxOr){ 16 | 17 | if(idx==nums.length){ 18 | if(currOr==maxOr){ 19 | return 1; 20 | } 21 | return 0; 22 | } 23 | 24 | 25 | int take = count(idx+1, nums, currOr | nums[idx], maxOr); 26 | 27 | int notTake = count(idx+1, nums, currOr, maxOr); 28 | 29 | return take + notTake; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /solutions/day19/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day19/.gitkeep -------------------------------------------------------------------------------- /solutions/day19/README.md: -------------------------------------------------------------------------------- 1 | # Find Kth Bit in Nth Binary String 2 | 3 | ## Problem Statement 4 | Given two positive integers n and k, the binary string Sn is formed as follows: 5 | 6 | S1 = "0" 7 | Si = Si - 1 + "1" + reverse(invert(Si - 1)) for i > 1 8 | 9 | Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0). 10 | 11 | ## Explanation 12 | For example, the first four strings in the above sequence are: 13 | 14 | S1 = "0" 15 | S2 = "011" 16 | S3 = "0111001" 17 | S4 = "011100110110001" 18 | 19 | Return the kth bit in Sn. It is guaranteed that k is valid for the given n. 20 | 21 | ## Example 22 | Example 1: 23 | 24 | Input: n = 3, k = 1 25 | Output: "0" 26 | Explanation: S3 is "0111001". 27 | The 1st bit is "0". 28 | 29 | Example 2: 30 | 31 | Input: n = 4, k = 11 32 | Output: "1" 33 | Explanation: S4 is "011100110110001". 34 | The 11th bit is "1". 35 | 36 | ### JAVA Approach Explanation 37 | 38 | 1. Base case: When n = 1, the binary string is "0" 39 | 2. Find the length of the current string Sn, which is 2^n - 1 40 | 3. Find the middle position 41 | 4. If k is the middle position, return '1' 42 | 5. If k is in the first half, find the bit in Sn-1 43 | 6. If k is in the second half, find the bit in Sn-1 and invert it 44 | 45 | ### Time Complexity ⏱️ 46 | - The overall **time complexity** is `O(n)` because we recursively reduce the problem size with each step by one level. 47 | 48 | ### Space Complexity 💾 49 | - The space complexity is `O(n)` due to the recursion stack. -------------------------------------------------------------------------------- /solutions/day19/solution_cpp.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | char findKthBit(int n, int k) { 4 | if (n == 1) { 5 | return '0'; 6 | } 7 | 8 | int len = (1 << n) - 1; 9 | int mid = len / 2 + 1; 10 | 11 | if (k == mid) { 12 | return '1'; 13 | } 14 | 15 | if (k < mid) { 16 | return findKthBit(n - 1, k); 17 | } 18 | 19 | char bit = findKthBit(n - 1, len - k + 1); 20 | return bit == '0' ? '1' : '0'; 21 | 22 | } 23 | }; -------------------------------------------------------------------------------- /solutions/day19/solutions/day19/solution_java.java: -------------------------------------------------------------------------------- 1 | package solutions.day19; 2 | 3 | public class solution_java { 4 | public char findKthBit(int n, int k) { 5 | if (n == 1) 6 | return '0'; 7 | 8 | int length = (1 << n) - 1; 9 | 10 | int mid = length / 2 + 1; 11 | 12 | if (k == mid) 13 | return '1'; 14 | 15 | if (k < mid) 16 | return findKthBit(n - 1, k); 17 | 18 | return findKthBit(n - 1, length - k + 1) == '0' ? '1' : '0'; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /solutions/day20/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day20/.gitkeep -------------------------------------------------------------------------------- /solutions/day20/README.md: -------------------------------------------------------------------------------- 1 | # 1106. Parsing A Boolean Expression 2 | 3 | ## Problem Statement 4 | 5 | You're given a string that represents a boolean expression. You need to evaluate this expression and return the result. The expression can be in one of the following forms: 6 | 7 | - `'t'` which evaluates to `true`. 8 | - `'f'` which evaluates to `false`. 9 | - `'!(subExpr)'` which evaluates to the logical NOT of the inner expression `subExpr`. 10 | - `'&(subExpr1, subExpr2, ..., subExprn)'` which evaluates to the logical AND of the inner expressions `subExpr1, subExpr2, ..., subExprn` where `n >= 1`. 11 | - `'|(subExpr1, subExpr2, ..., subExprn)'` which evaluates to the logical OR of the inner expressions `subExpr1, subExpr2, ..., subExprn` where `n >= 1`. 12 | 13 | The expression is guaranteed to be valid and follow the given rules. 14 | 15 | ### Examples 16 | 17 | 1. **Input**: `"&(|(f))"` 18 | **Output**: `false` 19 | **Explanation**: 20 | - First, evaluate `|(f)` --> `f`. The expression is now `"&(f)"`. 21 | - Then, evaluate `&(f)` --> `f`. The expression is now `"f"`. 22 | - Finally, return `false`. 23 | 24 | 2. **Input**: `"|(f,f,f,t)"` 25 | **Output**: `true` 26 | **Explanation**: The evaluation of `(false OR false OR false OR true)` is `true`. 27 | 28 | 3. **Input**: `"!(&(f,t))"` 29 | **Output**: `true` 30 | **Explanation**: 31 | - First, evaluate `&(f,t)` --> `(false AND true)` --> `false` --> `f`. The expression is now `"!(f)"`. 32 | - Then, evaluate `!(f)` --> `NOT false` --> `true`. We return `true`. 33 | 34 | ## Solution Approach 35 | 36 | ### Brute-Force Approach 37 | 38 | A brute-force approach involves recursively parsing the expression and evaluating each sub-expression. This can be inefficient due to the overhead of recursive calls and the complexity of managing nested expressions. 39 | 40 | ### Optimized Approach 41 | 42 | The optimized approach uses a stack to efficiently parse and evaluate the boolean expression. Here's how it works: 43 | 44 | 1. **Initialize a Stack**: Use a stack to keep track of the current expression and its components. 45 | 2. **Iterate through the Expression**: As you go through each character in the expression, handle different types of characters (`(`, `)`, `&`, `|`, `!`, `t`, `f`, `,`). 46 | 3. **Handle Different Operators**: 47 | - For `t` and `f`, push them onto the stack. 48 | - For `!`, `&`, and `|`, push them onto the stack. 49 | - For `(`, push it onto the stack to mark the beginning of a new sub-expression. 50 | - For `)`, evaluate the sub-expression up to the last `(` and replace it with the result. 51 | 4. **Evaluate Sub-expressions**: 52 | - For `!`, pop the top element (which should be a boolean value) and push the negation of that value. 53 | - For `&`, pop all elements up to the last `(` and evaluate the logical AND of these elements. 54 | - For `|`, pop all elements up to the last `(` and evaluate the logical OR of these elements. 55 | 56 | ### Explanation 57 | 58 | **Stack Operations**: The stack is used to keep track of the current state of the expression. When you encounter a `(`, you push it onto the stack to mark the beginning of a new sub-expression. When you encounter a `)`, you evaluate the sub-expression up to the last `(` and replace it with the result. 59 | 60 | **Boolean Evaluation**: For `!`, you simply negate the top value on the stack. For `&` and `|`, you pop all values up to the last `(` and evaluate them accordingly. 61 | 62 | ### Time Complexity 63 | 64 | The time complexity of this approach is O(n), where n is the length of the expression. This is because we process each character in the expression exactly once. 65 | -------------------------------------------------------------------------------- /solutions/day20/Solution.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution { 4 | 5 | public boolean parseBoolExpr(String expression) { 6 | Stack st = new Stack<>(); 7 | 8 | for (char currChar : expression.toCharArray()) { 9 | if (currChar == ',' || currChar == '(') continue; 10 | if ( 11 | currChar == 't' || 12 | currChar == 'f' || 13 | currChar == '!' || 14 | currChar == '&' || 15 | currChar == '|' 16 | ) { 17 | st.push(currChar); 18 | } 19 | else if (currChar == ')') { 20 | boolean hasTrue = false, hasFalse = false; 21 | 22 | while ( 23 | st.peek() != '!' && st.peek() != '&' && st.peek() != '|' 24 | ) { 25 | char topValue = st.pop(); 26 | if (topValue == 't') hasTrue = true; 27 | if (topValue == 'f') hasFalse = true; 28 | } 29 | 30 | char op = st.pop(); 31 | if (op == '!') { 32 | st.push(hasTrue ? 'f' : 't'); 33 | } else if (op == '&') { 34 | st.push(hasFalse ? 'f' : 't'); 35 | } else { 36 | st.push(hasTrue ? 't' : 'f'); 37 | } 38 | } 39 | } 40 | return st.peek() == 't'; 41 | } 42 | } -------------------------------------------------------------------------------- /solutions/day20/leetcode_daily_20.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def parseBoolExpr(self, expression: str) -> bool: 3 | stack = [] 4 | 5 | for char in expression: 6 | if char == 't' or char == 'f': 7 | stack.append(char == 't') 8 | elif char == '!' or char == '&' or char == '|': 9 | stack.append(char) 10 | elif char == '(': 11 | stack.append(char) 12 | elif char == ')': 13 | # Evaluate the expression inside the parentheses 14 | temp = [] 15 | while stack and stack[-1] != '(': 16 | temp.append(stack.pop()) 17 | # Pop the '(' 18 | stack.pop() 19 | # Get the operator 20 | operator = stack.pop() 21 | if operator == '!': 22 | stack.append(not temp[0]) 23 | elif operator == '&': 24 | result = True 25 | for val in temp: 26 | result = result and val 27 | stack.append(result) 28 | elif operator == '|': 29 | result = False 30 | for val in temp: 31 | result = result or val 32 | stack.append(result) 33 | 34 | return stack[0] -------------------------------------------------------------------------------- /solutions/day20/solutions.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool parseBoolExpr(string expression) { 4 | stack s; 5 | 6 | for (char currChar : expression) { 7 | if (currChar == ',' || currChar == '(') 8 | continue; 9 | if (currChar == 't' || currChar == 'f' || currChar == '!' || 10 | currChar == '&' || currChar == '|') { 11 | s.push(currChar); 12 | } 13 | else if (currChar == ')') { 14 | bool hasTrue = false, hasFalse = false; 15 | 16 | while (s.top() != '!' && s.top() != '&' && s.top() != '|') { 17 | char topValue = s.top(); 18 | s.pop(); 19 | if (topValue == 't') hasTrue = true; 20 | if (topValue == 'f') hasFalse = true; 21 | } 22 | char op = s.top(); 23 | s.pop(); 24 | if (op == '!') { 25 | s.push(hasTrue ? 'f' : 't'); 26 | } else if (op == '&') { 27 | s.push(hasFalse ? 'f' : 't'); 28 | } else { 29 | s.push(hasTrue ? 't' : 'f'); 30 | } 31 | } 32 | } 33 | return s.top() == 't'; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /solutions/day21/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day21/.gitkeep -------------------------------------------------------------------------------- /solutions/day21/Solution.java: -------------------------------------------------------------------------------- 1 | package solutions.day21; 2 | 3 | import java.util.*; 4 | 5 | public class Solution { 6 | private int maxUniqueSplits; 7 | 8 | public int maxUniqueSplit(String s) { 9 | maxUniqueSplits = 0; 10 | backtrack(s, 0, new HashSet<>()); 11 | return maxUniqueSplits; 12 | } 13 | 14 | private void backtrack(String s, int start, Set currentSet) { 15 | if (start == s.length()) { 16 | maxUniqueSplits = Math.max(maxUniqueSplits, currentSet.size()); 17 | return; 18 | } 19 | 20 | for (int end = start + 1; end <= s.length(); end++) { 21 | String substring = s.substring(start, end); 22 | 23 | if (!currentSet.contains(substring)) { 24 | currentSet.add(substring); 25 | backtrack(s, end, currentSet); 26 | 27 | currentSet.remove(substring); 28 | } 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /solutions/day21/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxUniqueSplit(string s) { 4 | size_t ans = 0; 5 | dfs(s, 0, {}, ans); 6 | return ans; 7 | } 8 | 9 | private: 10 | void dfs(const string& s, int start, unordered_set&& seen, 11 | size_t& ans) { 12 | if (start == s.length()) { 13 | ans = max(ans, seen.size()); 14 | return; 15 | } 16 | 17 | for (int i = 1; start + i <= s.length(); ++i) { 18 | const string cand = s.substr(start, i); 19 | if (seen.contains(cand)) 20 | continue; 21 | seen.insert(cand); 22 | dfs(s, start + i, std::move(seen), ans); 23 | seen.erase(cand); 24 | } 25 | } 26 | }; -------------------------------------------------------------------------------- /solutions/day21/solution.js: -------------------------------------------------------------------------------- 1 | class Solution { 2 | maxUniqueSplit(s) { 3 | let ans = 0; 4 | this.dfs(s, 0, new Set(), ans); 5 | return ans; 6 | } 7 | 8 | dfs(s, start, seen, ans) { 9 | if (start === s.length) { 10 | ans = Math.max(ans, seen.size); 11 | return; 12 | } 13 | 14 | for (let i = 1; start + i <= s.length; i++) { 15 | const cand = s.substring(start, start + i); 16 | if (seen.has(cand)) continue; 17 | seen.add(cand); 18 | this.dfs(s, start + i, new Set(seen), ans); 19 | seen.delete(cand); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /solutions/day22/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day22/.gitkeep -------------------------------------------------------------------------------- /solutions/day23/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day23/.gitkeep -------------------------------------------------------------------------------- /solutions/day23/solution_cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct TreeNode { 4 | int val; 5 | TreeNode *left; 6 | TreeNode *right; 7 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | }; 9 | 10 | class Solution { 11 | public: 12 | TreeNode* replaceValueInTree(TreeNode* root) { 13 | root->val = 0; 14 | dfs(std::vector{root}); 15 | return root; 16 | } 17 | 18 | private: 19 | void dfs(std::vector arr) { 20 | if (arr.empty()) return; 21 | 22 | int sum = 0; 23 | for (auto node : arr) { 24 | if (!node) continue; 25 | if (node->left) sum += node->left->val; 26 | if (node->right) sum += node->right->val; 27 | } 28 | 29 | std::vector childArr; 30 | for (auto node : arr) { 31 | int curSum = 0; 32 | if (node->left) curSum += node->left->val; 33 | if (node->right) curSum += node->right->val; 34 | 35 | if (node->left) { 36 | node->left->val = sum - curSum; 37 | childArr.push_back(node->left); 38 | } 39 | if (node->right) { 40 | node->right->val = sum - curSum; 41 | childArr.push_back(node->right); 42 | } 43 | } 44 | 45 | dfs(childArr); 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /solutions/day23/solution_java.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public TreeNode replaceValueInTree(TreeNode root) { 3 | dfs(new TreeNode[] {root}); 4 | root.val = 0; 5 | return root; 6 | } 7 | 8 | private void dfs(TreeNode[] arr) { 9 | if (arr.length == 0) return; 10 | 11 | int sum = 0; 12 | for (TreeNode node : arr) { 13 | if (node == null) continue; 14 | if (node.left != null) sum += node.left.val; 15 | if (node.right != null) sum += node.right.val; 16 | } 17 | 18 | TreeNode[] childArr = new TreeNode[arr.length * 2]; 19 | int index = 0; 20 | 21 | for (TreeNode node : arr) { 22 | int curSum = 0; 23 | if (node.left != null) curSum += node.left.val; 24 | if (node.right != null) curSum += node.right.val; 25 | 26 | if (node.left != null) { 27 | node.left.val = sum - curSum; 28 | childArr[index++] = node.left; 29 | } 30 | if (node.right != null) { 31 | node.right.val = sum - curSum; 32 | childArr[index++] = node.right; 33 | } 34 | } 35 | 36 | dfs(java.util.Arrays.copyOf(childArr, index)); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /solutions/day23/solution_python.py: -------------------------------------------------------------------------------- 1 | #Cousins in Binary Tree II 2 | # Definition for a binary tree node. 3 | class TreeNode(object): 4 | def __init__(self, val=0, left=None, right=None): 5 | self.val = val 6 | self.left = left 7 | self.right = right 8 | 9 | class Solution(object): 10 | def replaceValueInTree(self, root): 11 | """ 12 | :type root: Optional[TreeNode] 13 | :rtype: Optional[TreeNode] 14 | """ 15 | if not root: 16 | return root 17 | 18 | self.dfs([root]) 19 | root.val = 0 20 | return root 21 | 22 | def dfs(self, arr): 23 | if not arr: 24 | return 25 | 26 | total_sum = 0 27 | for node in arr: 28 | if node is None: 29 | continue 30 | if node.left is not None: 31 | total_sum += node.left.val 32 | if node.right is not None: 33 | total_sum += node.right.val 34 | 35 | child_arr = [] 36 | 37 | for node in arr: 38 | cur_sum = 0 39 | if node.left is not None: 40 | cur_sum += node.left.val 41 | if node.right is not None: 42 | cur_sum += node.right.val 43 | 44 | if node.left is not None: 45 | node.left.val = total_sum - cur_sum 46 | child_arr.append(node.left) 47 | if node.right is not None: 48 | node.right.val = total_sum - cur_sum 49 | child_arr.append(node.right) 50 | 51 | self.dfs(child_arr) 52 | -------------------------------------------------------------------------------- /solutions/day24/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day24/.gitkeep -------------------------------------------------------------------------------- /solutions/day24/solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | public boolean flipEquiv(TreeNode root1, TreeNode root2) { 18 | if(root1 == null && root2 == null){ 19 | return true; 20 | } 21 | if(root1 == null || root2 == null || root1.val != root2.val){ 22 | return false; 23 | } 24 | boolean same = flipEquiv(root1.right, root2.right) && flipEquiv(root1.left, root2.left); 25 | boolean not = flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left); 26 | 27 | return same || not; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /solutions/day24/solution_cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct TreeNode { 5 | int val; 6 | TreeNode* left; 7 | TreeNode* right; 8 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 9 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 10 | TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} 11 | }; 12 | 13 | /* 14 | You are given the roots of two binary trees root1 and root2. 15 | We define a flip operation as choosing any node and swapping the left and right child subtrees. 16 | 17 | A binary tree X is flip equivalent to a binary tree Y if and only if 18 | we can make X equal to Y after performing some number of flip operations. 19 | 20 | Return true if the two trees are flip equivalent, or false otherwise. 21 | 22 | Example 1: 23 | Input: root1 = [1,2,3,4,5,6,null,null,null,7,8] 24 | root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7] 25 | Output: true 26 | Explanation: We flipped at nodes with values 1, 3, and 5. 27 | 28 | Example 2: 29 | Input: root1 = [], root2 = [] 30 | Output: true 31 | 32 | Example 3: 33 | Input: root1 = [], root2 = [1] 34 | Output: false 35 | 36 | Constraints: 37 | - The number of nodes in each tree is in the range [0, 100]. 38 | - Each tree will have unique node values in the range [0, 99]. 39 | */ 40 | 41 | class Solution { 42 | public: 43 | bool flipEquiv(TreeNode* root1, TreeNode* root2) { 44 | // if both are null then the trees are equal 45 | if (!root1 && !root2) { 46 | return true; 47 | } 48 | 49 | // if only one is null then the trees are not equal 50 | if (!root1 || !root2) { 51 | return false; 52 | } 53 | 54 | // if the values are not equal then the trees are not equal 55 | if (root1->val != root2->val) { 56 | return false; 57 | } 58 | 59 | // case 1: check if the left and right subtrees are equal 60 | bool isSame = (flipEquiv(root1->left, root2->left) && flipEquiv(root1->right, root2->right)); 61 | 62 | // case 2: check if the left and right subtrees are equal when flipped 63 | bool isFlip = (flipEquiv(root1->left, root2->right) && flipEquiv(root1->right, root2->left)); 64 | 65 | // check if trees are equal in at least one case 66 | return isSame || isFlip; 67 | } 68 | }; 69 | -------------------------------------------------------------------------------- /solutions/day24/solution_java.java: -------------------------------------------------------------------------------- 1 | package leetCode; 2 | 3 | class TreeNode { 4 | int val; 5 | TreeNode left; 6 | TreeNode right; 7 | 8 | TreeNode() { 9 | this.val = 0; 10 | this.left = null; 11 | this.right = null; 12 | } 13 | 14 | TreeNode(int val) { 15 | this.val = val; 16 | this.left = null; 17 | this.right = null; 18 | } 19 | 20 | TreeNode(int val, TreeNode left, TreeNode right) { 21 | this.val = val; 22 | this.left = left; 23 | this.right = right; 24 | } 25 | } 26 | 27 | /* 28 | You are given the roots of two binary trees root1 and root2. 29 | We define a flip operation as choosing any node and swapping the left and right child subtrees. 30 | 31 | A binary tree X is flip equivalent to a binary tree Y if and only if 32 | we can make X equal to Y after performing some number of flip operations. 33 | 34 | Return true if the two trees are flip equivalent, or false otherwise. 35 | 36 | Example 1: 37 | Input: root1 = [1,2,3,4,5,6,null,null,null,7,8] 38 | root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7] 39 | Output: true 40 | Explanation: We flipped at nodes with values 1, 3, and 5. 41 | 42 | Example 2: 43 | Input: root1 = [], root2 = [] 44 | Output: true 45 | 46 | Example 3: 47 | Input: root1 = [], root2 = [1] 48 | Output: false 49 | 50 | Constraints: 51 | - The number of nodes in each tree is in the range [0, 100]. 52 | - Each tree will have unique node values in the range [0, 99]. 53 | */ 54 | 55 | 56 | class Solution { 57 | public boolean flipEquiv(TreeNode root1, TreeNode root2) { 58 | // if both are null then the trees are equal 59 | if (root1 == null && root2 == null) { 60 | return true; 61 | } 62 | 63 | // if only one is null then the trees are not equal 64 | if (root1 == null || root2 == null) { 65 | return false; 66 | } 67 | 68 | // if the values are not equal then the trees are not equal 69 | if (root1.val != root2.val) { 70 | return false; 71 | } 72 | 73 | // case 1: check if the left and right subtrees are equal 74 | boolean isSame = flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right); 75 | 76 | // case 2: check if the left and right subtrees are flipped 77 | boolean isFlip = flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left); 78 | 79 | // check if trees are equal in at least one case 80 | return isSame || isFlip; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /solutions/day25/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day25/.gitkeep -------------------------------------------------------------------------------- /solutions/day25/solution.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class solution { 3 | public static List removeSubfolders(String[] folder) 4 | { 5 | //sort the array 6 | Arrays.sort(folder); 7 | 8 | List result=new ArrayList<>(); //result list 9 | 10 | result.add(folder[0]); //Add first folder in the result 11 | for(int i=1;i result = removeSubfolders(folder); 27 | System.out.println(result); // Output: ["/a", "/c/d", "/c/f"] 28 | } 29 | } -------------------------------------------------------------------------------- /solutions/day25/solution_java.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List removeSubfolders(String[] folder) { 3 | Arrays.sort(folder); 4 | 5 | 6 | List ans = new ArrayList<>(); 7 | ans.add(folder[0]); 8 | 9 | for (int i = 1; i < folder.length; i++) { 10 | 11 | String lastFolder = ans.get(ans.size() - 1) + "/"; 12 | 13 | if (!folder[i].startsWith(lastFolder)) { 14 | ans.add(folder[i]); 15 | } 16 | } 17 | 18 | return ans; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /solutions/day26/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day26/.gitkeep -------------------------------------------------------------------------------- /solutions/day26/solution_java.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class solution_java { 17 | int max; 18 | public int[] treeQueries(TreeNode root, int[] queries) 19 | { 20 | int left[]=new int[100001]; 21 | int right[]=new int[100001]; 22 | max=0; 23 | leftquery(root,left,0); 24 | max=0; 25 | rightquery(root,right,0); 26 | for(int i=0;i mp = new HashMap<>(); 5 | 6 | int res = -1; 7 | 8 | for(int i = 0; i< nums.length;i++){ 9 | int temp = (int) Math.sqrt(nums[i]); 10 | 11 | if(temp * temp == nums[i] && mp.containsKey(temp)){ 12 | mp.put(nums[i], mp.get(temp) + 1); 13 | res = Math.max(res, mp.get(nums[i])); 14 | } else { 15 | mp.put(nums[i], 1); 16 | } 17 | } 18 | 19 | return res; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /solutions/day29/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day29/.gitkeep -------------------------------------------------------------------------------- /solutions/day29/README.md: -------------------------------------------------------------------------------- 1 | # 2684. Maximum Number of Moves in a Grid 2 | 3 | ## problem statement: 4 | 5 | You are given a 0-indexed m x n matrix grid consisting of positive integers. 6 | 7 | You can start at any cell in the first column of the matrix, and traverse the grid in the following way: 8 | 9 | From a cell (row, col), you can move to any of the cells: (row - 1, col + 1), (row, col + 1) and (row + 1, col + 1) such that the value of the cell you move to, should be strictly bigger than the value of the current cell. 10 | 11 | Return the maximum number of moves that you can perform. 12 | 13 | ### examples 14 | 1) Input: grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]] 15 | Output: 3 16 | Explanation: We can start at the cell (0, 0) and make the following moves: 17 | - (0, 0) -> (0, 1). 18 | - (0, 1) -> (1, 2). 19 | - (1, 2) -> (2, 3). 20 | It can be shown that it is the maximum number of moves that can be made. 21 | 22 | 2) Input: grid = [[3,2,4],[2,1,9],[1,1,7]] 23 | Output: 0 24 | Explanation: Starting from any cell in the first column we cannot perform any moves. 25 | 26 | # solution 27 | 1) Define a DFS function that computes the max moves from a cell if it has not been visited (memoized). 28 | 2) Check valid directions (top-right, right, bottom-right) where the next cell is greater than the current cell. 29 | 3) Update max moves from each cell by taking 1 + the result of DFS on the next cell. 30 | 4) Memoize the result for each cell to avoid recomputation. 31 | 5) Iterate over the first column of each row, using DFS to find the maximum path length starting from each cell in the first column. 32 | 33 | ## dry run 34 | grid = [[1,2,3],[6,5,4],[7,8,9]]. 35 | 36 | Start at grid[0][0] = 1: 37 | Check the right cell grid[0][1] = 2, which is greater than 1, so move right. 38 | Next, move to grid[0][2] = 3 (greater than 2). 39 | Path length from (0,0): 2 (right-right path). 40 | 41 | Starting from grid[1][0] = 6: 42 | Move top-right to grid[0][1] = 2 (not greater than 6) is invalid. 43 | Move right to grid[1][1] = 5 (not greater than 6) is invalid. 44 | Move bottom-right to grid[2][1] = 8 (greater than 6) → grid[2][2] = 9 (greater than 8). 45 | Path length from (1,0): 2 (bottom-right path). 46 | 47 | Compute other paths similarly to find the longest valid path. 48 | 49 | ### Time complexity: 50 | => O(R×C), where R is the number of rows and C is the number of columns. Each cell is processed once due to memoization 51 | 52 | #### Space complexity: 53 | => O(R×C) for the memoization array mem -------------------------------------------------------------------------------- /solutions/day29/solution_cpp.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int maxMoves(int r,int c,vector>& grid,vector>& mem){ 3 | if(mem[r][c]!=-1) return mem[r][c]; 4 | 5 | int max_moves=0; 6 | if(r-1>=0 and c+1grid[r][c]) 7 | max_moves = 1 + maxMoves(r-1,c+1,grid,mem); 8 | if(c+1grid[r][c]) 9 | max_moves = max(max_moves, 1 + maxMoves(r,c+1,grid,mem)); 10 | if(r+1grid[r][c]) 11 | max_moves = max(max_moves, 1 + maxMoves(r+1,c+1,grid,mem)); 12 | 13 | return mem[r][c]=max_moves; 14 | } 15 | public: 16 | int maxMoves(vector>& grid) { 17 | int r=grid.size(); 18 | int c=grid[0].size(); 19 | 20 | vector> mem(r,vector(c,-1)); 21 | int max_moves = 0; 22 | for(int i=0;i= 0 && c + 1 < grid[0].length && grid[r - 1][c + 1] > grid[r][c]) { 7 | maxMoves = 1 + maxMoves(r - 1, c + 1, grid, mem); 8 | } 9 | if (c + 1 < grid[0].length && grid[r][c + 1] > grid[r][c]) { 10 | maxMoves = Math.max(maxMoves, 1 + maxMoves(r, c + 1, grid, mem)); 11 | } 12 | if (r + 1 < grid.length && c + 1 < grid[0].length && grid[r + 1][c + 1] > grid[r][c]) { 13 | maxMoves = Math.max(maxMoves, 1 + maxMoves(r + 1, c + 1, grid, mem)); 14 | } 15 | 16 | mem[r][c] = maxMoves; 17 | return maxMoves; 18 | } 19 | 20 | public int maxMoves(int[][] grid) { 21 | int rows = grid.length; 22 | int cols = grid[0].length; 23 | 24 | int[][] mem = new int[rows][cols]; 25 | for (int[] row : mem) { 26 | Arrays.fill(row, -1); 27 | } 28 | 29 | int maxMoves = 0; 30 | for (int i = 0; i < rows; ++i) { 31 | maxMoves = Math.max(maxMoves, maxMoves(i, 0, grid, mem)); 32 | } 33 | 34 | return maxMoves; 35 | } 36 | } -------------------------------------------------------------------------------- /solutions/day29/solution_python.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxMoves(self, grid: List[List[int]]) -> int: 3 | def dfs(r, c, grid, mem): 4 | if mem[r][c] != -1: 5 | return mem[r][c] 6 | 7 | max_moves = 0 8 | if r - 1 >= 0 and c + 1 < len(grid[0]) and grid[r - 1][c + 1] > grid[r][c]: 9 | max_moves = 1 + dfs(r - 1, c + 1, grid, mem) 10 | if c + 1 < len(grid[0]) and grid[r][c + 1] > grid[r][c]: 11 | max_moves = max(max_moves, 1 + dfs(r, c + 1, grid, mem)) 12 | if r + 1 < len(grid) and c + 1 < len(grid[0]) and grid[r + 1][c + 1] > grid[r][c]: 13 | max_moves = max(max_moves, 1 + dfs(r + 1, c + 1, grid, mem)) 14 | 15 | mem[r][c] = max_moves 16 | return max_moves 17 | 18 | rows = len(grid) 19 | cols = len(grid[0]) 20 | mem = [[-1] * cols for _ in range(rows)] 21 | 22 | max_moves = 0 23 | for i in range(rows): 24 | max_moves = max(max_moves, dfs(i, 0, grid, mem)) 25 | 26 | return max_moves -------------------------------------------------------------------------------- /solutions/day30/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day30/.gitkeep -------------------------------------------------------------------------------- /solutions/day30/solution_java.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumMountainRemovals(int[] nums) { 3 | int n = nums.length; 4 | int[] lis = new int[n]; 5 | int[] lds = new int[n]; 6 | 7 | for(int j = 0; j< n; j++){ 8 | lis[j] = 1; 9 | lds[j] = 1; 10 | } 11 | 12 | for(int i = 0; i < n; i++){ 13 | for(int j = 0; j< i; j++){ 14 | if(nums[j] < nums[i]){ 15 | lis[i] = Math.max(lis[i], 1 + lis[j]); 16 | } 17 | } 18 | } 19 | 20 | for(int i = n - 1; i >= 0; i--){ 21 | for(int j = i + 1; j< n; j++){ 22 | if(nums[j] < nums[i]){ 23 | lds[i] = Math.max(lds[i], 1 + lds[j]); 24 | } 25 | } 26 | } 27 | 28 | int res = n; 29 | 30 | for(int i = 1;i < n - 1; i++ ){ 31 | if(Math.min(lis[i], lds[i]) > 1){ 32 | res = Math.min(res, n - lis[i] - lds[i] + 1); 33 | } 34 | } 35 | 36 | 37 | 38 | return res; 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /solutions/day31/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arya2004/leetcode-daily-october-hacktoberfest-2024/9c524689795a1ef8d4121c8d4180e3cfa11f0870/solutions/day31/.gitkeep -------------------------------------------------------------------------------- /solutions/solutions.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | --------------------------------------------------------------------------------